Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> if not twitter_options: return 'Module is not configured. You must set `twitter_keys` in settings' api = getattr(bot, 'twitter_api', None) if api is None: api = bot.twitter_api = twitter.Api( consumer_key=twitter_options['cons...
media = prepare_binary_from_url(file_url)
Using the snippet: <|code_start|> if current_color in palette: pos = palette.index(current_color) if pos == len(palette) - 1: return palette[pos] else: return palette[pos + 1] return 0xFFFFFF class CPU(object): def __init__(self): self.registers = {}...
return get_reg_by_size(get_reg_class(reg_string), reg_size)
Given snippet: <|code_start|> if current_color in palette: pos = palette.index(current_color) if pos == len(palette) - 1: return palette[pos] else: return palette[pos + 1] return 0xFFFFFF class CPU(object): def __init__(self): self.registers = {} ...
return get_reg_by_size(get_reg_class(reg_string), reg_size)
Given snippet: <|code_start|># -*- coding: utf-8 -*- """ @author: Tobias """ class Instruction(object): """ @brief Implements the interface to distorm3 Instructions """ def __init__(self, offset, code, type = distorm3.Decode32Bits, feature = 0): """ @param offset Address of the inst...
if SV.dissassm_type == 64:
Using the snippet: <|code_start|> is_mov_ebp(ps_lst, 0, len(ps_lst)-1)) or not has_loc): val_arr.append(PI.PseudoOperand(PI.EXP_T, 'RET_ADDR', 0)) val_arr.append(PI.PseudoOperand(PI.EXP_T, 'ARGS', 0)) new_op =...
register = get_reg_by_size(reg_class, SV.dissassm_type)
Given the code snippet: <|code_start|> @brief Starts recursiv search for jmp addresses @param pp_lst List of PseudoInstructions push/pop represtentation @param jmp_pos Index of jump instruction @return List of Tuple: (position of jump addr, address of jump instruction) """ jmp_inst = pp_lst[jmp_p...
get_reg_class(op.register) == get_reg_class('ebp'))):
Given snippet: <|code_start|> is_mov_ebp(ps_lst, 0, len(ps_lst)-1)) or not has_loc): val_arr.append(PI.PseudoOperand(PI.EXP_T, 'RET_ADDR', 0)) val_arr.append(PI.PseudoOperand(PI.EXP_T, 'ARGS', 0)) new_op = PI....
register = get_reg_by_size(reg_class, SV.dissassm_type)
Here is a snippet: <|code_start|># coding=utf-8 __author__ = 'Anatoli Kalysch' # from PyQt5 import QtGui, QtCore, QtWidgets #################### ### STACK CHANGE ### #################### class StackChangeViewer(PluginViewer): def __init__(self, vr, sorted, stack_changes, title='Stack Changes Analysis'): ...
sa = QtGui.QStandardItem('%s' % key)
Next line prediction: <|code_start|> super(StackChangeViewer, self).__init__(title) self.vr = vr self.sorted = sorted self.stack_changes = stack_changes def PopulateModel(self): for key in self.sorted: sa = QtGui.QStandardItem('%s' % key) chg = QtGui....
self.treeView = QtWidgets.QTreeView()
Next line prediction: <|code_start|># coding=utf-8 __author__ = 'Anatoli Kalysch' #################### ### STACK CHANGE ### #################### class StackChangeViewer(PluginViewer): def __init__(self, vr, sorted, stack_changes, title='Stack Changes Analysis (legacy)'): # context should be a dictionary ...
sa = QtGui.QStandardItem('%s' % key)
Given the code snippet: <|code_start|> clustering_analysis() except Exception, e: print '[*] Exception occured while running Clustering analysis!\n %s' % e.message # optimizations try: optimization_analysis() except Exception, e: print '[*] ...
get_log().log('[VMA] Starting VMAttack and initiating variables ...\n')
Here is a snippet: <|code_start|> @vm_returns.setter def vm_returns(self, value): self.vmr._vm_returns = value @property def vm_ctx(self): return self.vmr._vm_ctx @vm_ctx.setter def vm_ctx(self, value): self.vmr._vm_ctx = value def select_debugger(self): c ...
AboutWindow().exec_()
Here is a snippet: <|code_start|># coding=utf-8 __author__ = 'Anatoli Kalysch' class VMAttack_Manager(object): def __init__(self): self.choice = None self._vmr = get_vmr() # UI Management <|code_end|> . Write the next line using the current file imports: from lib.Logging import get_log...
self.ui_mgr = UIManager()
Given the code snippet: <|code_start|> return '%s\t%s' % (self.disasm[0], self.disasm[1]) else: return self.disasm[0] def to_str_line(self): return "%x %x %s\t\t%s\t\t%s" % (self.thread_id, self.addr, ...
return get_reg_class(self._line[2][1]) is not None
Here is a snippet: <|code_start|> except: pass w.pbar_update(5) ### RECURSION ### try: recursion = 0 vm_func = find_vm_addr(orig_trace) for line in orig_trace: if line.disasm[0].startswith('call') and line.disasm[1].__contai...
v = GradingViewer(trace, save=save)
Continue the code snippet: <|code_start|> v0 = ClusterViewer(cluster, create_bb_diff, trace.ctx_reg_size, save_func=save) w.pbar_update(24) v0.Show() prev_ctx = defaultdict(lambda: 0) stack_changes = defaultdict(lambda: 0) for line in cluster: ...
v = OptimizationViewer(trace, save=save)
Given the code snippet: <|code_start|> if not trace.constant_propagation: trace = optimization_const_propagation(trace) if not trace.stack_addr_propagation: trace = optimization_stack_addr_propagation(trace) except: pass w.pbar_update(30...
v1 = StackChangeViewer(vr, sorted_result, stack_changes)
Given snippet: <|code_start|> try: if func_addr is not None: # TODO enable input / output analysis of all functions input = find_input(deepcopy(trace)) output = find_output(deepcopy(trace)) w.close() else: vr = DynamicAnalyzer(find_virtual_regs, trace)...
v = VMInputOuputViewer(input.get_result(), output.get_result(), ctx)
Based on the snippet: <|code_start|># IDA Debugger def load_idadbg(self): return IDADebugger() # OllyDbg def load_olly(self): return OllyDebugger() # Bochs Dbg def load_bochsdbg(self): LoadDebugger('Bochs', 0) return IDADebugger() # Win32 Dbg def load_win32dbg(self): LoadDebugger('win32', 0) ...
vmr = get_vmr()
Given the code snippet: <|code_start|> """ dbg_handl = get_dh(choice) vmr = get_vmr() trace = dbg_handl.gen_instruction_trace() if trace is not None: vmr.trace = trace else: raise Exception('[*] Trace seems to be None, so it was disregarded!') ### ANALYSIS FUNCTIONALITY### # TODO...
w = NotifyProgress('Address count')
Using the snippet: <|code_start|> def clustering_analysis(visualization=0, grade=False, trace=None): """ Clustering analysis wrapper which clusters the trace into repeating instructions and presents the results in the Clustering Viewer. :param visualization: output via Clustering Viewer or output window ...
v0 = ClusterViewer(cluster, create_bb_diff, trace.ctx_reg_size, save_func=save)
Predict the next line after this snippet: <|code_start|> "<Clustering Importance :{iClu}>\n" "<Pattern Importance :{iPaMa}>\n" "<Memory Usage Importance :{iMeUs}>\n" "<Static Analysis Importan...
vmr = get_vmr()
Predict the next line after this snippet: <|code_start|> def Show(): settings = SettingsView() settings.Compile() vmr = get_vmr() vm_ctx = vmr.vm_ctx settings.iCodeStart.value = vm_ctx.code_start settings.iCodeEnd.value = vm_ctx.code_end settings.iBaseAddr.value = vm_ctx.base_addr setti...
vm_ctx = VMContext()
Here is a snippet: <|code_start|> elif self.size == 4: end_str += '_d ' elif self.size == 8: end_str += '_q ' elif self.inst_class != ASSIGNEMENT_T: end_str += ' ' for pos, op in enumerate(self.op_lst): if (self.inst_class == ASSIGNEMENT_T a...
get_reg_class(op0.register) == get_reg_class('edi')):
Here is a snippet: <|code_start|> end_str = end_str + str(op) + ', ' if (self.list_len != 0): end_str = end_str[0:len(end_str) - 2] + '\n' else: end_str += '\n' end_str = end_str.replace('+0x0', '') return end_str def get_scratch_variable(self)...
for reg in reversed(get_reg_class_lst(reg_class)):
Next line prediction: <|code_start|> @brief Replace plain VmInstruction representation with a push/pop representation. This representation needs temporal variables and each of these temporal variables is unique """ ret = [] if self.inst_class == IN2_OUT2: op0 =...
SV.dissassm_type / 8, PUSH_T))
Based on the snippet: <|code_start|># coding=utf-8 __author__ = 'Anatoli Kalysch' class PluginViewer(PluginForm): def __init__(self, title): super(PluginViewer, self).__init__() self.title = title def Show(self, **kwargs): return PluginForm.Show(self, self.title, options=PluginForm.F...
self.parent = form_to_widget(form)
Using the snippet: <|code_start|> if __name__ == '__main__': DATA_PATH = sys.argv[1] HDF5 = False if HDF5: print('Using hdf5') <|code_end|> , determine the next line of code. You have imports: from crayimage.runutils import hdf5_disk_stream, np_disk_stream import sys import os.path as osp import time ...
stream = hdf5_disk_stream(osp.join(DATA_PATH, 'Co60.hdf5'), batch_sizes=8, cache_size=16)
Predict the next line for this snippet: <|code_start|> if __name__ == '__main__': DATA_PATH = sys.argv[1] HDF5 = False if HDF5: print('Using hdf5') stream = hdf5_disk_stream(osp.join(DATA_PATH, 'Co60.hdf5'), batch_sizes=8, cache_size=16) else: print('Using numpy memmaping') <|code_end|> with the h...
stream = np_disk_stream(osp.join(DATA_PATH, 'Co60'), batch_sizes=8, cache_size=16, mmap_mode='r')
Using the snippet: <|code_start|> def noise(patches): return np.max(patches, axis=(2, 3))[:, 1] < 5 def hit(patches): return np.max(patches, axis=(2, 3))[:, 1] > 25 class TestRunUtils(unittest.TestCase): def test_load_and_filter(self): print(os.getcwd()) <|code_end|> , determine the next line of code. ...
runs = load_index('clean.json', '../../../../data')
Using the snippet: <|code_start|> def noise(patches): return np.max(patches, axis=(2, 3))[:, 1] < 5 def hit(patches): return np.max(patches, axis=(2, 3))[:, 1] > 25 class TestRunUtils(unittest.TestCase): def test_load_and_filter(self): print(os.getcwd()) runs = load_index('clean.json', '../../../.....
results = slice_filter_run(
Given the following code snippet before the placeholder: <|code_start|> if __name__ == '__main__': np.random.seed(1234) xs = np.stack([ np.arange(-10, 10, dtype='int16') for _ in range(128) ]) ys = np.stack([ np.arange(-10, 10, dtype='int16') for _ in range(128) ]) vals = np.random.uniform(1.0e-2,...
stream = SimulationStream(xs, ys, vals, sizes=sizes, cache=-1)
Given snippet: <|code_start|> zip(*[ read_sparse_run(r, track_len=track_len) for r in runs ]) ) return cls(tracks_xs, tracks_xs, tracks_vals, *args, **kwargs) def __init__(self, tracks_xs, tracks_ys, tracks_vals, sizes = (8, 32, 16, 8, 4, 2, 1), img_shape=(128, 128), cache...
self.stream = queue_stream(queue)
Predict the next line after this snippet: <|code_start|>__all__ = [ 'binnig_update', 'binning', 'uniform_mapping', 'greedy_max_entropy_mapping', 'almost_uniform_mapping' ] def binnig_update(img, out, mapping=None): bins = out.shape[-1] n_channels = img.shape[0] if img.dtype == RGB_T: binning_r...
raise wrong_dtype_exception(img.dtype)
Given the code snippet: <|code_start|>copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS O...
if not data.dtype == DTYPE_COORD:
Based on the snippet: <|code_start|> module_filepath = os.path.join(self.location + "/modules", moduleClassName+'.py') py_mod = imp.load_source(moduleClassName, module_filepath) # instantiate the imported module moduleInstance = getattr(py_mod, moduleClassName)(device_name=device_name, d...
parser.add_argument('-c', '--cloudbrain', default=RABBITMQ_ADDRESS,
Given snippet: <|code_start|> parser.add_argument('-i', '--device_id', required=True, help="A unique ID to identify the device you are sending data from. " "For example: 'octopicorn2015'") parser.add_argument('-n', '--device_name', required=True, ...
device_id=MOCK_DEVICE_ID,
Next line prediction: <|code_start|>__author__ = 'odrulea' _SUPPORTED_DEVICES = get_supported_devices() _SUPPORTED_METRICS = get_supported_metrics() class AnalysisService(object): """ Subscribes and writes data to a file Only supports Pika communication method for now, not pipes """ LOGNAME = "[...
raise ValueError(colors.FAIL + self.LOGNAME + "Pika subscriber needs to have a rabbitmq address!" + colors.ENDC)
Predict the next line after this snippet: <|code_start|> if 'num_channels' in global_conf: menu['num_channels'] = global_conf['num_channels'] # send the handshake to the clients self.send(json.dumps(menu)) def on_message(self, message): """ This will r...
rabbitmq_address = (stream_configuration['rabbitmq_address'] if 'rabbitmq_address' in stream_configuration else RABBITMQ_ADDRESS)
Given the following code snippet before the placeholder: <|code_start|>OD """ #logging.getLogger().setLevel(logging.ERROR) class ConnectionPlot(SockJSConnection): """RtStreamConnection connection implementation""" # Class level variable clients = set() conf = None def __init__(self, session):...
message = BufferToMatrix(record, output_type="list")
Next line prediction: <|code_start|> def send_probe(body): #logging.debug("GOT [" + metric_name + "]: " + body) #print "GOT [" + metric_name + "]: [" + data_type + "]" if data_type == MESSAGE_TYPE_MATRIX: """ MESSAGE_TYPE_MATRIX output is a base...
metrics = ListConfOutputMetrics(self.conf, prefix="viz_")
Predict the next line after this snippet: <|code_start|> def connect(self): credentials = pika.PlainCredentials('cloudbrain', 'cloudbrain') self.connection = pika.BlockingConnection(pika.ConnectionParameters( host=self.host, credentials=credentials)) self.channel = self.connection.channel() fo...
print colors.GOLD + "[Subscriber Started] Queue --> [" + key + "] for input [" + metric_id + "]" + colors.ENDC
Next line prediction: <|code_start|> class Connector(object): __metaclass__ = ABCMeta def __init__(self, publishers, buffer_size, step_size, device_name, device_port, device_mac=None): <|code_end|> . Use current file imports: (from abc import ABCMeta, abstractmethod from lib.devices import get_metrics_...
self.metrics = get_metrics_names(device_name)
Given the following code snippet before the placeholder: <|code_start|> def disconnect(self): self.connection.close_file() def consume_messages(self, callback): while True: line = self.pipe.readline() if line == '': return # EOF ## TODO: figure out what ch, method, and pr...
metric_names = get_metrics_names(device_name)
Based on the snippet: <|code_start|> else: self.pipe = open(self.pipe_name, 'r') def disconnect(self): self.connection.close_file() def consume_messages(self, callback): while True: line = self.pipe.readline() if line == '': return # EOF ## TODO: figure out wha...
host = RABBITMQ_ADDRESS
Predict the next line after this snippet: <|code_start|> device_id, cloudbrain_address, buffer_size, step_size, device_port, pipe_name, publisher, device_mac) def run(device_name="muse", mock_data_enabled=True, device_id=MOCK_DEVICE_ID, clo...
publishers = {metric: PikaPublisher(device_name,
Predict the next line after this snippet: <|code_start|> publisher, device_mac) def run(device_name="muse", mock_data_enabled=True, device_id=MOCK_DEVICE_ID, cloudbrain_address=RABBITMQ_ADDRESS, buffer_size=10, step_size=10, device_port=None, pipe_name=Non...
publishers = {metric: PipePublisher(device_name,
Predict the next line for this snippet: <|code_start|> run(device_name, mock_data_enabled, device_id, cloudbrain_address, buffer_size, step_size, device_port, pipe_name, publisher, device_mac) def run(device_name="muse", mock_data_enabled=True...
metrics = get_metrics_names(device_name)
Next line prediction: <|code_start|> def validate_opts(opts): """ validate that we've got the right options @param opts: (list) options to validate @retun opts_valid: (bool) 1 if opts are valid. 0 otherwise. """ opts_valid = True if (opts.device_name in ["openbci","openbci_daisy"]) and (opt...
parser.add_argument('-c', '--cloudbrain', default=RABBITMQ_ADDRESS,
Here is a snippet: <|code_start|> return opts def main(): opts = get_opts() mock_data_enabled = opts.mock device_name = opts.device_name device_id = opts.device_id cloudbrain_address = opts.cloudbrain buffer_size = int(opts.buffer_size) device_port = opts.device_port pipe_name = opts...
device_id=MOCK_DEVICE_ID,
Next line prediction: <|code_start|> .. code-block:: jinja {{ my_dict|filter_items }} {{ my_dict|filter_items("MY_PREFIX_") }} {{ my_dict|filter_items("MY_PREFIX_", True) }} This is most useful in combination with the special :ref:`_all_env <all_env>` variable that shpkpr injects i...
class IntegerRequired(exceptions.ShpkprException):
Given the following code snippet before the placeholder: <|code_start|># stdlib imports # third-party imports # local imports @pytest.fixture def runner(): runner = CliRunner() <|code_end|> , predict the next line using imports from the current file: import functools import pytest from click.testing import Cli...
return functools.partial(runner.invoke, cli)
Next line prediction: <|code_start|>def render_json_template(template_path, template_name, **values): """Initialise a jinja2 template and render it with the passed-in values. The template, once rendered is treated as JSON and converted into a python dictionary. If the template is not valid JSON after rende...
template_env.filters['filter_items'] = template_filters.filter_items
Next line prediction: <|code_start|># third-party imports # local imports def _write_template_to_disk(tmpdir, template_name, template_data): """shpkpr loads template files from disk normally. This convenience function writes a template file to disk and returns a (directory, name) tuple. """ with ...
values = load_values_from_environment()
Based on the snippet: <|code_start|># third-party imports # local imports def _mock_gethostbyname_ex(aliaslist=None, ipaddrlist=None): """Returns a mocked socket.gethostbyname_ex function for testing use """ if aliaslist is None: aliaslist = [] if ipaddrlist is None: ipaddrlist = ['12...
actual_urls = resolver.resolve('http://foobar.com:1234')
Given the code snippet: <|code_start|>@options.chronos_client @options.job_name @options.output_formatter def show(chronos_client, job_name, output_formatter, **kw): """List application configuration. """ jobs = chronos_client.list() if job_name is None: payload = jobs else: payload...
@arguments.env_pairs
Continue the code snippet: <|code_start|># stdlib imports # third-party imports # local imports logger = logging.getLogger(__name__) @click.group('cron', context_settings=CONTEXT_SETTINGS) def cli(): """Manage Chronos jobs. """ @cli.command('show', short_help='List Chronos Jobs as json', context_setting...
@options.chronos_client
Given snippet: <|code_start|> def _inject_secrets(template, secrets): """Given an object containing secrets, inject them into a Chronos job prior to deployment. """ if not template.get("environmentVariables"): template["environmentVariables"] = [] for key, secret in secrets.items(): ...
values = load_values_from_environment(prefix=env_prefix, overrides=env_pairs)
Using the snippet: <|code_start|> to deployment. """ if not template.get("environmentVariables"): template["environmentVariables"] = [] for key, secret in secrets.items(): template["environmentVariables"].append({ "name": key, "value": secret, }) return...
rendered_template = render_json_template(template_path, template_name, **values)
Predict the next line for this snippet: <|code_start|> """ if not template.get("environmentVariables"): template["environmentVariables"] = [] for key, secret in secrets.items(): template["environmentVariables"].append({ "name": key, "value": secret, }) retu...
resolved_secrets = resolve_secrets(vault_client, rendered_template)
Based on the snippet: <|code_start|># third-party imports # local imports @pytest.fixture @freeze_time("2011-11-11T11:11:11.111111Z") def app_definition(json_fixture): """Prepare an app definition for deployment. This fixture prepares an app and assumes that no existing stack is present on Marathon. ...
return prepare_app_definition(app_definition_fixture, None, app_states_fixture['apps'])
Based on the snippet: <|code_start|># stdlib imports # third-party imports # local imports @pytest.fixture def runner(): @click.command() <|code_end|> , predict the immediate next line with the help of imports: import functools import click import pytest from click.testing import CliRunner from shpkpr.cli impo...
@options.marathon_client
Given snippet: <|code_start|># third-party imports # local imports @pytest.fixture def valid_app_definition(json_fixture): return json_fixture("marathon/bluegreen_app_new") def test_valid_app(valid_app_definition): """Test that an app validates successfully when all the required labels are present. ...
validator = AppDefinitionValidator()
Predict the next line for this snippet: <|code_start|># third-party imports # local imports @pytest.fixture def valid_app_definition(json_fixture): return json_fixture("marathon/bluegreen_app_new") def test_valid_app(valid_app_definition): """Test that an app validates successfully when all the required la...
except ValidationError as e:
Next line prediction: <|code_start|># stdlib imports # third-party imports # local imports @pytest.fixture def haproxy_stats(file_fixture): csv_data = file_fixture("haproxy/stats.csv") <|code_end|> . Use current file imports: (import collections import pytest from shpkpr.marathon_lb.stats import Stats) and co...
return Stats(csv_data)
Given the following code snippet before the placeholder: <|code_start|># third-party imports # local imports @pytest.fixture def valid_app_definition(json_fixture): return json_fixture("marathon/bluegreen_app_new") def test_valid_state(valid_app_definition): """Test that an app validates successfully when ...
validator = MarathonStateValidator(marathon_client)
Predict the next line after this snippet: <|code_start|># third-party imports # local imports @pytest.fixture def valid_app_definition(json_fixture): return json_fixture("marathon/bluegreen_app_new") def test_valid_state(valid_app_definition): """Test that an app validates successfully when no existing sta...
except ValidationError as e:
Predict the next line after this snippet: <|code_start|># third-party imports # local imports @pytest.fixture(scope="session") def env(): # read the required environment variables into a dictionary and assert # that they're set appropriately env = { "SHPKPR_MARATHON_APP_ID": os.environ.get("SHPKP...
return functools.partial(runner.invoke, cli)
Here is a snippet: <|code_start|># third-party imports # local imports @pytest.fixture def app_definition(json_fixture): """Prepare an app definition for deployment. This fixture prepares an app and assumes that an existing stack is present on Marathon. """ new_app_definition_fixture = json_fixt...
return prepare_app_definition(new_app_definition_fixture,
Based on the snippet: <|code_start|> # app, otherwise we treat it as a list of multiple applications to be # deployed together. if isinstance(application_payload, (list, tuple)): path = "/v2/apps/" else: path = "/v2/apps/" + application_payload['id'] param...
raise DeploymentNotFound(deployment_id)
Using the snippet: <|code_start|> applications = response.json()['apps'] application_list = [] for app in applications: application_list.append(app) return application_list raise ClientError("Unknown Marathon error: %s\n\n%s" % (response.status_cod...
return MarathonDeployment(self, deployment['deploymentId'])
Predict the next line after this snippet: <|code_start|> @mock.patch("shpkpr.cli.options.hvac.Client") def test_resolve_secrets(mock_vault_client_class): mock_vault_data = { 'secret/my_project/my_path': { 'my_key': 'some_secret_info' } } mock_rendered_template = { 'secr...
result = resolve_secrets(mock_vault_client, mock_rendered_template)
Continue the code snippet: <|code_start|># Copyright 2017--2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not # use this file except in compliance with the License. A copy of the License # is located at # # http://aws.amazon....
check_condition(warmup >= 0, "warmup needs to be >= 0.")
Here is a snippet: <|code_start|># Copyright 2017--2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not # use this file except in compliance with the License. A copy of the License # is located at # # http://aws.amazon.com/apac...
b = sockeye.scoring.BatchScorer(scorer=CandidateScorer(1.0, 0.0, 0.0),
Using the snippet: <|code_start|># Copyright 2017--2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not # use this file except in compliance with the License. A copy of the License # is located at # # http://aws.amazon.com/apac...
rouge_score = rouge.rouge_1(hypotheses, references)
Continue the code snippet: <|code_start|> 'encoder.layers.1.pre_ff.layer_norm.beta', 'encoder.layers.1.pre_ff.layer_norm.gamma', 'encoder.layers.1.pre_self_attention.layer_norm.beta', 'encoder.layers.1.pre_self_attention.layer_norm.gamma', 'encoder.layers.1.self_attention.ff_in.weight', 'encoder....
fixed_param_names = fixed_param_names_from_strategy(config, params, strategy)
Given the following code snippet before the placeholder: <|code_start|> assert raw_vocab == Counter({"a": 1, "b": 1, "c": 2, "d": 1, "e": 1}) test_vocab = [ # Example 1 (["one two three", "one two three"], None, 1, {"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "two": 4, "three": 5, "one": ...
vocab = build_vocab(data=data, num_words=size, min_count=min_count)
Using the snippet: <|code_start|> data = [" ".join('word%d' % i for i in range(num_types))] size = None min_count = 1 vocab = build_vocab(data, size, min_count, pad_to_multiple_of=pad_to_multiple_of) assert len(vocab) == expected_vocab_size test_constants = [ # Example 1 (["one two ...
assert get_ordered_tokens_from_vocab(vocab) == expected_output
Continue the code snippet: <|code_start|> vocab = build_vocab(data, size, min_count) for const in constants: assert const in vocab @pytest.mark.parametrize("vocab, expected_output", [({"<pad>": 0, "a": 4, "b": 2}, ["<pad>", "b", "a"]), ({}, [])]) def ...
assert is_valid_vocab(vocab) == expected_result
Based on the snippet: <|code_start|>def test_get_ordered_tokens_from_vocab(vocab, expected_output): assert get_ordered_tokens_from_vocab(vocab) == expected_output @pytest.mark.parametrize( "vocab, expected_result", [ ({symbol: idx for idx, symbol in enumerate(C.VOCAB_SYMBOLS + ["w1", "w2"])}, True...
fnames = _get_sorted_source_vocab_fnames(None)
Predict the next line after this snippet: <|code_start|># Copyright 2017--2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not # use this file except in compliance with the License. A copy of the License # is located at # # htt...
scheduler = lr_scheduler.get_lr_scheduler('inv-sqrt-decay',
Given snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' RESPONSE_STATUS = Choices( ('OK', 'OK'), ) class MerchantHttpRequest(HttpRequest): def __init__(self, merchant, order): self.merchant = merchant self.order = order <|code...
if self.merchant.result_url_method == Merchant.URL_METHODS.GET:
Using the snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class OrderListView(TemplateView): template_name = 'orders/list.html' def get(self, request, *args, **kwargs): orders_page = create_paginated_page( query_set=Order...
objects_per_page=ORDERS_PER_PAGE
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class OrderListView(TemplateView): template_name = 'orders/list.html' def get(self, request, *args, **kwargs): orders_page = create_pagin...
query_set=Order.objects.filter(user=request.user).order_by("-id"),
Here is a snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class OrderPaymentViewTestCase(BaseViewTestCase): fixtures = [ "payway_accounts_auth.json", "payway_accounts_accounts.json", "payway_merchants_merchants.json", ...
self.merchant = Merchant.objects.get(uid=972855239)
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class OrderPaymentViewTestCase(BaseViewTestCase): fixtures = [ "payway_accounts_auth.json", "payway_accounts_accounts.json", "payway_merchants_merchants.json", ...
self.order = Order(
Given snippet: <|code_start|> def setUp(self): self.create_new_user_with_account() self.order = Order( uid=1234, sum=Money(10, self.account.currency), description=u"Тестовый товар", ) self.merchant = Merchant.objects.get(uid=972855239) self....
mocks.mock_MerchantHttpClient_success_execute()
Next line prediction: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' admin.site.register(Purse) <|code_end|> . Use current file imports: (from django.contrib import admin from payway.webmoney.models import Purse, ResultResponsePayment) and context includin...
admin.site.register(ResultResponsePayment)
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' CURRENCY_CHOICES = [(CURRENCIES['RUB'].code, CURRENCIES['RUB'].name)] class Purse(models.Model): purse = models.CharField(_('purse'), max_length=13, unique=True) ...
class ResultResponsePayment(ResponsePayment):
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' urlpatterns = patterns('', <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls.defaults import patterns, url from django.contrib.auth.decorators ...
url(r'add-money/(?P<invoice_uid>\d+)/$', login_required(WebmoneyView.as_view()), name='webmoney_add_money'),
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' urlpatterns = patterns('', url(r'add-money/(?P<invoice_uid>\d+)/$', login_required(WebmoneyView.as_view()), name='webmoney_add_money'), <|code_end|> ,...
url(r'result/$', csrf_exempt(WebmoneyResultView.as_view()), name='webmoney_result'),
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' urlpatterns = patterns('', url(r'add-money/(?P<invoice_uid>\d+)/$', login_required(WebmoneyView.as_view()), name='webmoney_add_money'), url(r'resu...
url(r'success/$', login_required(csrf_exempt(WebmoneySuccessView.as_view())), name='webmoney_success'),
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' urlpatterns = patterns('', url(r'add-money/(?P<invoice_uid>\d+)/$', login_required(WebmoneyView.as_view()), name='webmoney_add_money'), url(r'result/$', csrf_exempt(WebmoneyRes...
url(r'fail/$', login_required(csrf_exempt(WebmoneyFailView.as_view())), name='webmoney_fail'),
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class AddMoneyView(TemplateView): template_name = 'accounts/add_money.html' def get(self, request, *args, **kwargs): account_uid = int(kwargs.get('account_uid', -1))...
'money_amount': Money(ADD_MONEY_INITIAL_SUM, account.currency)
Using the snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class AddMoneyView(TemplateView): template_name = 'accounts/add_money.html' def get(self, request, *args, **kwargs): account_uid = int(kwargs.get('account_uid', -1)) ...
context['add_money_form'] = AddMoneyForm({
Using the snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class AddMoneyView(TemplateView): template_name = 'accounts/add_money.html' def get(self, request, *args, **kwargs): account_uid = int(kwargs.get('account_uid', -1)) ...
'payment_system': dict(PAYMENT_SYSTEM_CHOICES).keys()[0],
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class AddMoneyView(TemplateView): template_name = 'accounts/add_money.html' def get(self, request, *args, **kwargs): account_uid = int(kwargs.get('account_uid', -1))...
invoice, created = Invoice.objects.get_or_create(
Next line prediction: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' class AddMoneyView(TemplateView): template_name = 'accounts/add_money.html' def get(self, request, *args, **kwargs): account_uid = int(kwargs.get('account_uid', -1)) ...
account = get_object_or_404(Account, uid=account_uid)
Using the snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' TNX_ID_RE = re.compile(ur'^\w{1,30}$') class RequestPaymentForm(forms.Form): txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=forms.HiddenInput()) ...
max_digits=MAX_MONEY_DIGITS,
Predict the next line for this snippet: <|code_start|># -*- coding: UTF-8 -*- __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' TNX_ID_RE = re.compile(ur'^\w{1,30}$') class RequestPaymentForm(forms.Form): txn_id = forms.RegexField(regex=TNX_ID_RE, label=_(u'unique payment number'), widget=for...
decimal_places=MAX_MONEY_PLACES,