query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Create instance of PyRPS. redis_url Redis instance address (tuple containing (hostname, port)). namespace Namespace to separate Pub/Sub instance from another running on the same redis host. | def __init__(self, namespace, redis_url=("localhost", 6379)):
self.namespace = namespace
if isinstance(redis_url, tuple):
self.redis = StrictRedis(host=redis_url[0], port=redis_url[1])
elif isinstance(redis_url, str):
self.redis = StrictRedis(host=redis_url) | [
"def connect_to_redis():\n return Redis(host=redis_host, port=redis_port, db=0)",
"def __init__(self):\n try:\n config = redis_settings[\"REDIS_BACKEND\"]\n self.servers = config[\"servers\"]\n self.port = config[\"port\"]\n self.db = config[\"db\"]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Publish new message into queue. queue Queue name. message Message data. ttl How long the message should stay alive. | def publish(self, queue, message, ttl=3600):
# Get next message ID
message_id = self.redis.incr(self._ns_nextid())
# Push message to queue
self.redis.setex(self._ns_message(queue, message_id), ttl, message)
# List all consumers of given queue
consumers = self.r... | [
"def publish(self, message, exchange, routing_key, **kwargs):\r\n mqueue.put(message)",
"def publish(self, message, routing_key):\n\t\t#msg = amqp.Message(message)\n\t\t#msg.properties[\"content_type\"] = \"text/plain\"\n\t\t#msg.properties[\"delivery_mode\"] = 2\n\t\t#self.channel.basic_publish(exchange=s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return key for subscribers list for given queue. | def _ns_subscriptions(self, queue):
return self._ns(queue, "consumers") | [
"def queue_keys(self) -> List[str]:\n return [queue.key for queue in self.queues]",
"def key_for_name(name):\n return 'hotqueue:%s' % name",
"def queue_id(self) -> str:\n return pulumi.get(self, \"queue_id\")",
"def get_queue_oid(self, port, queue_num):\n redis_cmd = [\n \"r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unsubscribe from message queue and destroy it. Do not call if you want persistent queues or if you access one queue from multiple processes. | def unsubscribe(self):
# Unsubscribe
self.pyrps.redis.srem(self.pyrps._ns_subscriptions(self.queue), self.consumer_id)
# Remove message queue
self.pyrps.redis.delete(self.pyrps._ns_queue(self.queue, self.consumer_id)) | [
"def destroy_queue(self):\n response = self.queue.delete()\n if self._is_error_call(response):\n raise RuntimeError('SQS could not delete queue: %s' % response)\n self.queue, self.queue_name = None, None",
"def unsubscribe(self):\n if self.pubsub_thread:\n self.lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instead of rendering each wall block, we create a single shape which can be drawn in a single call, rather than a call for each wall block | def create_wall_shape(self):
self.shape_walls = arcade.ShapeElementList()
self.shape_walls.center_x = 0
self.shape_walls.center_y = 0
self.shape_walls.angle = 0
point_list = []
color_list = []
# create the walls into a single shape
walls = self.g... | [
"def __make_walls(self):\n x,y,z = self.params['inner_dimensions']\n thickness = self.params['wall_thickness']\n wall_x_overhang = self.params['x_r_overhang']\n d_tab = self.params['wall_tab_dist']\n tab_width = self.params['wall_tab_width']\n dia = self.params['wall_hole_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create/Update the sprite shape for an entity and add/update the entry for it in `self.entities_shapelist` | def update_shape_sprite(self, entity: Entity):
shape_sprite: ShapeSprite = entity.shape_sprite
if entity.id not in self.entities_shapelist:
entity_shapelist = arcade.ShapeElementList()
# we need to convert from general colours to arcade specific col... | [
"def add_shape(self, x, y, shape):\n # Awkward as the shape cell coordinates have absolute coordinates\n norm_shape = shape.normalise()\n adj_x, adj_y = norm_shape.center()\n for cell in norm_shape:\n xpos = x + cell.x - adj_x\n ypos = y + cell.y - adj_y\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the pixel positions for positioning a menu in the center of the screen | def get_menu_coords(self, menu):
menu_center_x = (self.width // 2)
menu_center_y = (self.height // 2)
# get a mapping of the menu co-ordinates for relative positioning of things inside the menu
menu_cords = (
(menu_center_x - (menu.width // 2), menu_center_y + (menu.... | [
"def _menuCoords(self, Lx, Ly):\r\n\r\n if Lx < 0:\r\n xCoord = self.width + Lx + (self.pWidth - self.width) / 2\r\n else:\r\n xCoord = Lx + (self.pWidth - self.width) / 2\r\n\r\n if Ly < 0:\r\n yCoord = self.height + Ly + (self.pHeight - self.height) / 2\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes logits based on features from the model | def logits_on_features(self, h, batch):
batch = batch.to(h.device)
# Extract features with the model
features = h.view(batch.size, -1)
# Log loss
logits = self.head(features)
return logits | [
"def logit_fn(data, ve_noise_scale):\n data = preprocess(data)\n logits = classifier.apply({'params': classifier_params}, data, ve_noise_scale, train=False, mutable=False)\n return logits",
"def get_logits(image):\n x = image\n for filters in (32, 64):\n x = tf.layers.conv2d(x, filters, 3)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the NLL loss given features h and targets y This assumes that the features have already be computed with the model | def nll_on_features(self, h, batch, reduction="mean"):
batch = batch.to(h.device)
y = batch.outputs
# Extract features with the model
features = h.view(batch.size, -1)
# Log loss
logits = self.head(features)
log_probs = F.log_softmax(logits, dim=-1)
nll_lo... | [
"def lossFun(inputs, targets, hprev):\n xs, hs, ys, ps = {}, {}, {}, {}\n hs[-1] = np.copy(hprev)\n loss = 0\n # forward pass(손실값 계산)\n for t in range(len(inputs)):\n xs[t] = np.zeros((vocab_size, 1)) # 1-of-k(one-hot) 형태로 변환. 모든 값이 0인 array 준비\n xs[t][inputs[t]] = 1 # 해당하는 글자에만 값을 1로... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build this task's classification head. | def build_head(self, n_features, device=None):
# By default this is a linear layer
self.head = self.create_compatible_head(n_features, device) | [
"def head(self) -> tf.estimator.Head:\n\n task_type = self._problem_statement.tasks[0].type\n if task_type.HasField('one_dimensional_regression'):\n return tf.estimator.RegressionHead()\n num_classes = (\n self._tf_transform_output.num_buckets_for_transformed_feature(\n self.raw_labe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test data for this task | def test_data(self):
return self._test_data | [
"def make_test_data(self):\n import data",
"def load_test_data(self):\n last_update = datetime.strptime(\n '2020-08-04T16:32:38.390390Z', DATETIME_FORMAT)\n self.task_data = [\n {\n 'id': '0xfakeTaskId',\n 'instance': 'MyTurbiniaInstance',\n 'last_update... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dataloader type for this task | def dataloader(self):
return DataLoader | [
"def dataloader(self):\n return self.augment_cfg['dataloader'].format(self.plan[\"network_dim\"])",
"def dataloader(self):\n\n # load / split data\n train_data = self.data.get_train_data()\n if self.args.use_dev:\n train_data, dev_data = self.data.split_data(train_data)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Concatenate two task's datasets | def concatenate_tasks(
tasks,
concat_train=True,
concat_valid=True,
concat_test=True,
):
new_task = deepcopy(tasks[0])
new_task._name = "+".join(task.name for task in tasks)
if concat_train:
new_task._train_data = ConcatDataset(
[task.train_data for task in tasks])
if... | [
"def _combine_datasets(data0, data1):\n data_new = xr.concat([data0, data1], dim=\"timesteps\")\n # Ensure time dimension is ordered\n data_new = data_new.loc[{\"timesteps\": data_new.timesteps.to_index().sort_values()}]\n\n return data_new",
"def _combine_datasets(data0, data1):\n data_new = xr.co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The exception of ValueError when format was unsupported. | def _raise_format_error(self, name: str, format_str: str, source_format: str):
raise ValueError(f"The '{ name }' should be { format_str }, rather than { source_format }") | [
"def _unknown_format(self, format):\n\n raise errors.NotAcceptable('unknown data format: ' + format)",
"def test_format_model_exception_for_unsupported_format():\n with pytest.raises(Exception) as e:\n assert parser.format_model(model=None, type='bsr')\n assert str(e.value) == 'type bsr is not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The train iterator that executes a standard training flow per batch. | def _train_batch(self):
# start epoch
for i, (source, target) in enumerate(self.train_dataset):
result = self._batch_iter(source, target, i)
# yield
yield result | [
"def train_batch_iter(self, batch_size, num_epochs):\n return self.batch_iter(0, batch_size, num_epochs)",
"def _train_loop(self, iterator: DataIterator) -> None:\n epoch = 0\n iteration = 0\n\n # Initialize metrics.\n for metric in self.train_metrics.values():\n metr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the process of training, which includes the loss meter reset, epoch reset and model's weights reset. | def reset_train(self):
self.model.apply(self._reset_weights)
self.epoch_loss.reset()
self.epoch = 0
del self.batch_process
self.batch_process = None | [
"def reset(self):\n checkpoint = torch.load(\n 'model_lr_finder.pth.tar',\n map_location=self.device)\n self.model.load_state_dict(checkpoint['state_dict'])\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n self.model.to(self.device)\n self.model.tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
UiView of sett module | def ui_view(request):
return render(request, 'sett_ui_view.html', {}) | [
"def get_ui(self, cfg, id=None):",
"def build_ui(self):\n\n pass",
"def configure_views(self):",
"def getWidget(self):",
"def setup_additional_ui(self):\n\n #set title\n self.setWindowTitle(self.title)\n\n #set question\n self.lbl_question.setText(self.question)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls open file dialog, possible to choose only '.xlsx .xls .xlsm .xlsb' | def callDialog(self):
self.pathTuple = filedialog.askopenfilenames(filetypes=[("Excel files", ".xlsx .xls .xlsm .xlsb")])
self.fileNames = [basename(path.abspath(name)) for name in self.pathTuple] | [
"def askopenfilenames(**options):\n options[\"multiple\"]=1\n return Open(**options).show()",
"def open_file_dialog(self, title, initial_directory=None, file_types=None, multiselect=False):\n return self._impl.open_file_dialog(title, initial_directory, file_types, multiselect)",
"def fileDialog(*ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns tuple of paths stored at class instance | def getPaths(self):
return self.pathTuple | [
"def path_for_class(cls) -> List[str]:\r\n return f\"{cls.__module__}.{cls.__name__}\".split(\".\")",
"def get_instance_paths(self, node):\r\n return self._send({'name': 'getInstancePaths', 'args': [node]})",
"def generate(self):\n for stage in self.stages:\n if not hasattr(self, sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Triggers a manual build of the project. | async def trigger_build(self, *, branch=None, message=None): | [
"def trigger_build(self, postdata):\n pass",
"def on_build(self, project, name):\n pass",
"def build(self):\n logging.info('Build %s of %s (%s)', self._build, self.name,\n self.working_dir)\n self._build += 1\n self._event = None\n status = self._builder... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a specific number of builds from the project. | async def get_builds(self, *, quantity=10): | [
"def get_build_ids():\n global SESSION\n\n if not ARGS.buildtype_id:\n print(\"[error] missing --buildtype-id argument\")\n sys.exit(1)\n\n # if --build-id is not set, get the latest one.\n if ARGS.build_id:\n build_id = ARGS.build_id\n else:\n #http://tc.corp.local/app/re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return `ret_value` `times` times. If generator will receive some value from outside, update `ret_value` | def exercise_gen(ret_val, times): | [
"def random_values():\n while True:\n yield random()",
"def constant_generator(value):\n\n while True:\n yield value",
"def repeat(value: T, times: int) -> List[T]:\n return [value] * times",
"def repeat(cls, value=None, repeat_count=None, scheduler=None):\n\n scheduler = schedul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update `exercise_gen`, so it will ignore all exceptions | def exercise2():
g1 = exercise_gen("I'll ignore errors", 300)
assert next(g1) == "I'll ignore errors"
assert g1.send('new val') == 'new val'
assert g1.throw(Exception) == 'new val'
assert next(g1) == 'new val' | [
"def exercise_gen(ret_val, times):",
"def test_post_codegen_error_query(self):\n with tempfile.TemporaryDirectory() as tmpdirname:\n translator = AstUprootTranslator()\n with pytest.raises(GenerateCodeException):\n translator.generate_code(\"\", cache_path=tmpdirname)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the reference file of a test using the response received. The file will be created in the git references folder provided in the settings file | def create_reference(
self, response_checker=default_checker.default_journey_checker
):
# Check that the file doesn't already exist
filename = self.get_file_name()
filepath = os.path.join(config["REFERENCE_FILE_PATH"], filename)
if os.path.isfile(filepath):
logge... | [
"def ref(request):\n r = referencepytest.ref(request)\n this_dir = os.path.abspath(os.path.dirname(__file__))\n r.set_data_location(os.path.join(this_dir, '..', 'reference'))\n return r",
"def test_with_new_file(self):\n repository = self.create_repository(tool_name='Test')\n review_requ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare the response (which is a dictionary) to the reference First, the function retrieves the reference then filters both ref and resp Finally, it compares them | def compare_with_ref(
self, response, response_checker=default_checker.default_journey_checker
):
def ref_resp2files(output_file, output_json):
"""
Create a file for the filtered response and for the filtered reference
"""
with open(output_file, "w") ... | [
"def compare(results, reference):\n results_only = set(results) - set(reference)\n reference_only = set(reference) - set(results)\n both = set(results) & set(reference)\n\n def make_delta(key):\n return (reference.get(key, 0), results.get(key, 0))\n\n violations = {key: make_delta(key) for key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a file for the filtered response and for the filtered reference | def ref_resp2files(output_file, output_json):
with open(output_file, "w") as reference_text:
reference_text.write(output_json) | [
"def export_file(self):\n if self.args.keyfilter:\n self.filter_keys()\n if self.args.datafilter:\n self.filter_values()\n json.dump(self.outputdata, self.outfile, indent=self.args.indent)\n self.outfile.write('\\n')",
"def create_reference(\n self, respons... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print differences between reference and response in console | def print_diff(ref_file, resp_file):
# open reference
with open(ref_file) as reference_text:
reference = reference_text.readlines()
# open response
with open(resp_file) as response_text:
response = response_text.readlines()
# P... | [
"def compare_with_ref(\n self, response, response_checker=default_checker.default_journey_checker\n ):\n\n def ref_resp2files(output_file, output_json):\n \"\"\"\n Create a file for the filtered response and for the filtered reference\n \"\"\"\n with open... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Proces elements from the input queue until empty. | def run(self) -> None:
while True:
try:
input_element = self.input_queue.get_nowait()
self.process(input_element)
except Empty:
return | [
"def process_entire_queue(self):\r\n\t\twhile self.queue:\r\n\t\t\tself._dequeue()",
"def process_entire_queue(self):\r\n while self.queue:\r\n self._dequeue()",
"def _wait_empty(self):\n while True:\n if self.queue.empty():\n # We still have to wait for the la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process every input using the given worker class. | def multiprocess(inputs: list, worker_class: Any, num_threads: int = 40):
input_queue = Queue() # type: ignore
output_queue = Queue() # type: ignore
for input_elm in inputs:
input_queue.put(input_elm)
threads = [worker_class(input_queue, output_queue)
for _ in range(num_threa... | [
"def processInputs(self):",
"def process_inputs(self, inputs):",
"def run(self):\n self.class_inst_obj.processor(self.msg)",
"def run(self) -> None:\n\n while True:\n try:\n input_element = self.input_queue.get_nowait()\n self.process(input_element)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function allows for current user information modification. There is feature for change of default picture that is assigned during registration of new user. Part of change user picture is connected with save_image() function located in `utils.py` where name of original picture file is processing and then saved new_proje... | def account():
form = UpdateAccountForm()
new_project_form = ProjectForm()
if form.validate_on_submit():
if form.picture.data: # if statement responsible for change of default picture
picture_file = save_image(form.picture.data)
current_user.img_file = picture_file
... | [
"def update_img(form):\n picture_folder = 'static/profile_pics'\n picture_path = picture_folder + '/' + current_user.image_file\n if current_user.image_file != \"default.jpg\":\n delete_picture(picture_path)\n current_user.image_file = save_picture(form.picture.data, picture_folder)",
"def chan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that render form for email input that is destination of utils.send_reset_email function responsible for sending email to user with token that is available for specific period of time and reset user's password | def reset_password():
if current_user.is_authenticated:
return redirect(url_for('main.home'))
form = RequestResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
send_reset_email(user) # located in utils.py
flash('An email has... | [
"def send_password_reset():\r\n form = EmailConfirmationForm()\r\n if form.validate_on_submit():\r\n email = form.email.data\r\n user = verify_email(email)\r\n if user:\r\n token = secrets.token_urlsafe(32)\r\n url = os.environ.get('URL','http://127.0.0.1:5000/passwo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns pandas dataframe which has latest record for each manual id after merging all "sheet_name" in the previously indexed_files which are present in "indexed_files_dir" | def zeta0_creation(self, indexed_files_dir, merge_columns):
indexed_files = [file for file in os.listdir(indexed_files_dir) if not file.startswith("~")]
indexed_files_dict = {}
indexed_files_dict.clear()
dateList = []
del dateList[:]
for file in indexed_files:
... | [
"def build_index(self):\n records = {}\n run_count = 0\n run_iteration = 1\n parse_dict = {}\n for k in self.value_path:\n parse_dict[k] = parse(k)\n s = time.time()\n for rid, json_data in self._file_iter:\n extracted_data = utils.extract(json_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function for break/clear parsing may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. | def lookupmodule(self, filename):
if os.path.isabs(filename) and os.path.exists(filename):
return filename
f = os.path.join(sys.path[0], filename)
if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
return f
root, ext = os.path.splitext(filename)
... | [
"def lookup_module(filename):\r\n\r\n # stolen from pdb\r\n import os\r\n import sys\r\n\r\n if os.path.isabs(filename) and os.path.exists(filename):\r\n return filename\r\n f = os.path.join(sys.path[0], filename)\r\n if os.path.exists(f): # and self.canonic(f) == self.mainpyfile:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait n seconds before returning ok | def timeout(n):
time.sleep(int(n))
return 'ok', 200 | [
"def waitfor(secs):\n time.sleep(secs)",
"def wait_for(test, timeout_seconds=DEFAULT_TIMEOUT):\n start = time.time()\n while True:\n if test():\n return True\n if time.time() - start > timeout_seconds:\n return False\n time.sleep(0.5)",
"def testWait(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
int ploidy return all possible genotypes, completely determined by ploidy | def all_genotype(ploidy):
return ["".join(comb) for comb in cwr("ACGT-", ploidy)] | [
"def genotype(args) :\n from genotyper import genotype_samples\n genotype_samples(args)",
"def collapse_genotypes(pL,gL):\n if len(gL) < 2:\n return gL\n else:\n uniqueL = [] # list of unique genotypes relative to ploidy\n for g in gL:\n s = ''\n for i in xra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
str genotype str base return P(base in genotype) | def prob_t_N(genotype, base):
cnter = Counter(genotype)
return cnter.get(base, 0) * 1/len(genotype) | [
"def get_genotype(gt):\n if ('0/0'):\n return \"0\"\n elif ('0/1'):\n return \"1\"\n else:\n return \"2\"",
"def get_genotype(self, snp):\n pass",
"def get_label(genotype_type):\n if genotype_type == \"Hom\":\n return 0\n elif genotype_type == \"Het\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
str genotype iterableobj bases_all_reads, list or np.array return P(data|genotype) == likelihood | def likelihood_genotype(genotype, bases_all_reads, error_rates):
likelihood = 1
for observed_base in bases_all_reads:
p = 0
for base in "ACGT-":
l = prob_t_N(genotype, base) * error_rates[base][observed_base]
p += l
likelihood *= p
return likelihood | [
"def genotype_likelihoods_of(self, sample):\n\t\treturn self.genotype_likelihoods[self._sample_to_index[sample]]",
"def get_genotypes(record):\n snp_list = []\n\n for sample in range(0, len(record.samples)):\n if record.samples[sample].called:\n snp_list.append(record.samples[sample].gt_ba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The base exception class of connection exceptions. | def __init__(self, error_msg):
super(ConnectionException, self).__init__(error_msg) | [
"def _suggest_error_class(self):\n if self.adoConn is not None:\n for e in self.adoConn.Errors:\n state = str(e.SQLState)\n if state.startswith('23') or state=='40002':\n return IntegrityError\n return DatabaseError",
"def SocketError(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reloads the Polls file. | def reloadpolls(self, irc, msg, args):
try:
self.polls = yaml.load(open(self.pollFile, 'r'), Loader=yamlordereddictloader.Loader)
except FileNotFoundError as e:
log.warning("Couldn't open file: %s" % e)
raise | [
"def reloadfile(self, ):\n self.loadfile()",
"def reload(self,) -> None:\n\n try:\n self._data = self._request(self._self_link)\n\n except requests.exceptions.HTTPError as error:\n warnings.warn(f'Reloading resource failed: {error}')",
"def reload(self):\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[channel] Vote on a poll. Channel is only needed if used in a PM. | def vote(self, irc, msg, args, channel, pid, yaynay):
if yaynay not in ['yay', 'nay']:
irc.error("Valid Answers are 'yay' or 'nay'.")
return
if channel in self.polls.keys():
if self.polls[channel][pid]['concluded']:
irc.reply("Poll #%s is finished, it... | [
"async def _vote_count(\n self, ctx: Context, *, channel: discord.TextChannel = None\n ):\n\n guild: discord.Guild = ctx.guild\n\n if not channel:\n channel = await self.get_vote_channel(guild)\n if isinstance(channel, str):\n return await ctx.send(channe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List waiters within the given configuration. | def ListWaiters(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | [
"def waiters(self):\n waiters = []\n\n for name, item in self._definition.get('waiters', {}).items():\n name = self._get_name('waiter', Waiter.PREFIX + name)\n waiters.append(Waiter(name, item))\n\n return waiters",
"def waiters(self):\n return [cb[0].fiber for cb... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save seed into temp file. | def saveseed(self, seed):
savefile = gettempdir() + '/last_test_seed_fate.tmp'
if args.verbose:
print('Saving run into ' + savefile)
with open(savefile, 'w') as f:
f.write(str(seed)) | [
"def save_seed(target_dir: Path) -> None:\n with open(target_dir / \"seed\", \"wb\") as f:\n pickle.dump(\n {\n \"datasets\": INITIAL_DATASETS,\n \"orig_datablocks\": INITIAL_ORIG_DATABLOCKS,\n \"attachments\": INITIAL_ATTACHMENTS,\n },\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an HTML script element for including a script from the admin media url (or other location if an absolute url is given). | def include_admin_script(script_path):
if not absolute_url_re.match(script_path):
script_path = '%s%s' % (settings.ADMIN_MEDIA_PREFIX, script_path)
return '<script type="text/javascript" src="%s"></script>' % script_path | [
"def external_js():\n return u'\\n'.join(format_html(u'<script src=\"{0}\"></script>', url) for url in settings.EXTERNAL_JS)",
"def resource_js(self):\n \n portal_url = getSite().absolute_url()\n \n return \"\"\"\n <script type=\"text/javascript\" src=\"%s/++resource++swfobje... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The index view, for the home page. Shows Campaigns this UserProfile is in. | def index(request):
context = dict()
if request.user.is_authenticated():
context['campaigns'] = [
CampaignSerializer(c).serialize() for c in
request.user.userprofile.campaigns.order_by('pk')]
return render(request, 'voter_validation/index.html', context) | [
"def index():\n # users = User.query.filter_by(_role_code=UserRole.tefl_pending.value)\n # calls = CallLog.query.filter_by(flagged=True)\n # return render_template('admin/index.html',\n # users=users,\n # active='users',\n # calls=calls)\n users = User.query.all()\n return render... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows validation UI for a given campaign, if this UserProfile is authorized to do data entry for the specified Campaign. This is also the endpoint for searching for Voters as part of validation. If doing a search, assume that a sufficient number of the specified fields is present (taken care of in frontend form validat... | def validate(request, campaign_id):
if not request.user.userprofile.in_campaign(campaign_id):
return HttpResponseRedirect(reverse("voter_validation:index"))
campaign_id = int(campaign_id)
campaign = get_object_or_404(Campaign, id=campaign_id)
# Get the number of signatures validated by the cur... | [
"def index(request):\n context = dict()\n if request.user.is_authenticated():\n context['campaigns'] = [\n CampaignSerializer(c).serialize() for c in\n request.user.userprofile.campaigns.order_by('pk')]\n return render(request, 'voter_validation/index.html', context)",
"def v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is the base Exception class for all step failures. It can be manually raised from recipe code to cause the build to turn red. | def StepFailure(self):
return recipe_api.StepFailure | [
"def raise_step_error(self, error: Exception, step: str):\n error_message = \"{}\\nFailed: Error={}\".format(step, str(error))\n logging.error(error_message)\n self.slacker.send_thread_reply(error_message)\n raise Exception(error_message)",
"def raise_on_error(self):\n if not self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
StepWarning is a subclass of StepFailure, and will translate to a yellow build. | def StepWarning(self):
return recipe_api.StepWarning | [
"def warn(self, warning=None):\r\n\r\n if self.getName() != 'Main':\r\n warning = self.getName() + ': ' + warning\r\n\r\n debug.err('Warning: %s' % warning)\r\n if type(warning) != types.ListType:\r\n warning = [warning]\r\n\r\n if self.result:\r\n self.r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
InfraFailure is a subclass of StepFailure, and will translate to a purple build. This exception is raised from steps which are marked as `infra_step`s when they fail. | def InfraFailure(self):
return recipe_api.InfraFailure | [
"def _GetInfraFailMessages(self, failing):\n msgs = self._GetFailedMessages(failing)\n # Filter out None messages because we cannot analyze them.\n return [x for x in msgs if x and\n x.HasFailureType(failures_lib.InfrastructureFailure)]",
"def raise_on_error(self):\n if not self._status.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
StepTimeout is a subclass of StepFailure and is raised when a step times out. | def StepTimeout(self):
return recipe_api.StepTimeout | [
"def raise_timeout(self, *args, **kwargs):\n\n self.log.error(\"Task timeout encountered.\")\n raise TimeoutError",
"def failed_timeout(self, failed_timeout):\n self._failed_timeout = failed_timeout",
"def StepFailure(self):\n return recipe_api.StepFailure",
"def _on_timeout_expired(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The currently active (open) result from the last step that was run. This is a `types.StepData` object. | def active_result(self):
return self.step_client.previous_step_result() | [
"def current_progress_data(self):\n return self._current_progress_data",
"def get_current_data(self):\n return self.__current_data",
"def get_current_run(self):\n last_run = self.get_last_runs(1)\n if len(last_run) == 0:\n return None\n last_run = last_run[0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Nest allows you to nest steps hierarchically on the build UI. Calling ```python | def nest(self, name):
step_result = self(name, [])
with self.m.context(name_prefix=name, increment_nest_level=True):
yield step_result | [
"def build_step(self):\n pass",
"def stepStarted(build, step):",
"def _run_python_hierblock(self):\n print \"Traversing python...\"\n fname_py = self._info['blockname'] + '.py'\n self._write_tpl('hier_python', 'python', fname_py)\n ed = CMakeFileEditor('python/CMakeLists.txt')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert single row into a table | def _insert_table_row(self, db: str, table: str, row: Dict[str, Any]):
pass | [
"def insert_db_row(self, param):\n c = self._conn.cursor()\n c.execute(self.sqladdrow, param)\n self._conn.commit()",
"def insert_row(self, table: str, row_data: dict):\r\n\r\n columns = \"\".join([f\"'{i}',\" for i in row_data]).rstrip(\",\")\r\n keys = \"\".join([f\"'{row_data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares two response objects based on their NVCness. Only returns true if both responses are in agreement with either responding NVC or not NVC. | def compare(obj_a, obj_b):
return (tuple_to_string(obj_a) == 'NVC') == (tuple_to_string(obj_b) == 'NVC') | [
"def compare(ob1, ob2, verbose=True): \n not_equal = ssdf.ssdf_base._not_equal(ob1, ob2)\n if verbose and not_equal:\n print(not_equal)\n return not not_equal",
"def verify_vn_in_api_server(self):\n self.api_verification_flag = True\n self.api_s_vn_obj = self.api_s_inspect.get_cs_vn(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs main gobject loop. | def run_main_loop():
mainloop = GObject.MainLoop() | [
"def start(self):\n self.mainloop = gobject.MainLoop()\n self.mainloop.run()",
"def loop( self ):\n import gtk\n while self.count >= 1:\n log.debug( 'GTK loop restarting' )\n while gtk.events_pending():\n gtk.main_iteration()\n log.debug( 'GT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialie dbus system bus acquire adapter/interface for org.bluez.GattManager1 register application for 'org.bluez.GattService1' | def __init__(self):
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
self.bus = dbus.SystemBus()
self.adapter = self._find_adapter()
if not self.adapter:
IFaceNotFoundException('%s interface not found' % GATT_MANAGER_IFACE)
self.service_manager = dbus.Interface(
... | [
"def __init__(self):\n dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n self.bus = dbus.SystemBus()\n self.adapter = self._find_adapter()\n if not self.adapter:\n IFaceNotFoundException('%s interface not found' % LE_ADVERTISING_MANAGER_IFACE)\n\n adapter_props = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds service to previously initialize app. | def add_service(self, service):
self.app.add_service(service) | [
"def addService(self, service):\n self.services |= service",
"def addService(self, service):\n\t\tself.services.append(service)\n\t\treturn self",
"def add(self, service: AbstractService):\n self.services.append(service)",
"def register_service(self, service):\n return",
"def initialize... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the date (UTC) from 10 days ago formatted as YYYYMMDD. | def _ten_days_ago() -> str:
ten_days_ago = gmtime(mktime(gmtime()) - TEN_DAYS_SECONDS)
return strftime(DATE_FORMAT, ten_days_ago) | [
"def days_ago(n):\n old_date = datetime.datetime.now() - datetime.timedelta(days=n)\n return fmt(old_date.year) + fmt(old_date.month) + fmt(old_date.day)",
"def n_days_ago(n_days):\n n_days_ago = datetime.datetime.now()-datetime.timedelta(days=n_days)\n return n_days_ago.strftime(\"%Y-%m-%d\")",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the last month (UTC) formatted as YYYYMM. | def _last_month() -> str:
time_now = gmtime()
return (
f"{time_now.tm_year}-{time_now.tm_mon - 1:02d}" if time_now.tm_mon > 1
else f"{time_now.tm_year - 1}-12"
) | [
"def last_month():\n return datetime.now() + relativedelta(months=-1)",
"def last_month():\n LastMonth = datetime.now().month - 1\n currentYear = datetime.now().year\n\n if LastMonth == 0:\n LastMonth = 12\n currentYear = currentYear - 1\n\n return currentYear, LastMonth",
"def CURR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the latest exchange rate from the given ECB data. | def _get_latest_ecb_rate(data: bytes) -> float:
root = etree.fromstring(data)
values = root.xpath('.//generic:ObsValue/@value', namespaces=root.nsmap)
last_value = len(values) - 1
return float(values[last_value]) | [
"def exchange_rate(self):\n res = r.get(self.url + self.current_rate)\n return self.execute(res)",
"def exchange_rate(self, date=None):\n if date is None:\n exchange_rate = self.exchange_rates.latest()\n else:\n exchange_rate = self.exchange_rates.get(date=date)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve and store the 15min delayed BTC market price in EUR. | def _get_btc_eur_15min(self) -> None:
with requests.get(BITCOIN_TICKER) as response:
response.raise_for_status()
json_data = response.json()
self.btc_eur_15min = json_data["EUR"]["15m"] | [
"def get_price(self):\r\n try:\r\n self.price = self.exchange.symbol_ticker()\r\n except Exception as e:\r\n pass",
"def get_buy_price(self,ticker,time):\n return self.broker.get_buy_price(ticker,time)",
"def getprice():\n\n print(\"Get price\")\n latest_price = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve and store last month's EUR to GBP average rate. | def _get_eur_gbp_last_month(self) -> None:
last_month = _last_month()
data = _get_ecb_data(FREQUENCY_MONTHLY, last_month, last_month)
self.eur_gbp_last_month = _get_latest_ecb_rate(data) | [
"def _get_eur_gbp_last_daily(self) -> None:\n data = _get_ecb_data(FREQUENCY_DAILY, _ten_days_ago(), _today())\n\n self.eur_gbp_last_day = _get_latest_ecb_rate(data)",
"def get_avg(self):\r\n df = pd.read_csv(\"MonthlyRate.csv\")\r\n df = df[df.CurrencyCode == self.choice]\r\n m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve and store the latest daily EUR to GBP average rate. | def _get_eur_gbp_last_daily(self) -> None:
data = _get_ecb_data(FREQUENCY_DAILY, _ten_days_ago(), _today())
self.eur_gbp_last_day = _get_latest_ecb_rate(data) | [
"def bitcoinaverage(site):\n url = \"https://apiv2.bitcoinaverage.com/frontend/constants/exchangerates/local\"\n try:\n session = requests.Session()\n cfscrape_requests = cfscrape.create_scraper(sess=session)\n ret = cfscrape_requests.get(url, timeout=(15, 15)).json()[\"rates\"]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the 15min delayed BTC market price in GBP. | def _get_btc_gbp_15min(self) -> None:
self._get_eur_gbp_last_daily()
self.btc_gbp_15min = self.btc_eur_15min * self.eur_gbp_last_day | [
"def calculate_buy_price(price: float):\n return round(price / (1 + CONF.trade_advantage_in_percent / 100), 1)",
"def _get_btc_eur_15min(self) -> None:\n with requests.get(BITCOIN_TICKER) as response:\n response.raise_for_status()\n json_data = response.json()\n\n self.btc_e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiate and run the worker. | def main() -> None:
worker = Worker()
worker.do_work() | [
"def create_and_run_worker(self):\n\n # Run processing on QThread worker - prevents GUI lock up\n # Create processing object, map control data\n processing_hub = ProcessingHub(control=self.control)\n\n # Create worker thread, connect signals to methods in this class and start, which call... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the cosmology that is being used | def get_cosmology(cosmology=conf.cosmology):
if cosmology.lower() not in available_cosmologies:
raise ValueError(
"Unrecognised cosmology {}. Available cosmologies are {}".format(
cosmology, ", ".join(available_cosmologies)
)
)
elif cosmology.lower() in _a... | [
"def get_cosmology(self):\n opt_cosmology = 'cosmology'\n return self.config_parser.get(self.section_data_processing, opt_cosmology)",
"def get_cosmology(self):\n return self.kernel.get_cosmology()",
"def COSMO_DEFAULT():\n return ccl.Cosmology(Omega_c=0.26066676,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Planck15 cosmology coded up in lalsuite | def Planck15_lal_cosmology():
return cosmo.LambdaCDM(H0=67.90, Om0=0.3065, Ode0=0.6935) | [
"def get_cosmology(cosmology=conf.cosmology):\n if cosmology.lower() not in available_cosmologies:\n raise ValueError(\n \"Unrecognised cosmology {}. Available cosmologies are {}\".format(\n cosmology, \", \".join(available_cosmologies)\n )\n )\n elif cosmolo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the base cosmology but with the Riess2019 H0 value. For details | def Riess2019_H0_cosmology(base_cosmology):
_base_cosmology = get_cosmology(base_cosmology)
return cosmo.LambdaCDM(
H0=74.03, Om0=_base_cosmology.Om0, Ode0=_base_cosmology.Ode0
) | [
"def H0_def(h):\n return H0_over_h*h",
"def getChemicalZero(self):\n return self.solver.getChemicalZero()",
"def sound_horizon_EH(self):\n om_m = self.omega_cb\n om_b = self.omega_b\n om_n = np.sum(self.omega_nu)\n h = self.h \n if self.M_nu_tot == 0.: rs = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the supported components e.g. set(['mmic_autodock_vina',...]). Returns Set[str] | def tactic_comps(cls) -> Set[str]:
return set(["mmic_autodock_vina"]) | [
"def supported_components() -> Set[Type[\"Component\"]]:\n return set()",
"def get_supported_components(self):\n props = [cdav.SupportedCalendarComponentSet()]\n response = self.get_properties(props, parse_response_xml=False)\n response_list = response.find_objects_and_props()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the specified mojofile, and return its model id. | def load_model(self, mojofile: str) -> str:
return self._request("GET /loadmojo", params={"file": mojofile}) | [
"def load_model(self, filename):\r\n pass",
"def load_model(self, filename):\n pass",
"def load_model(filename):\n return Model.load_savefile(filename)",
"def load(path_to_model):\n pass",
"def load_model(filename):\n model = joblib.load(filename)\n\n return model",
"def load(fil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shutdown / kill the server. Sometimes the ``POST /shutdown`` request may fail. In any case we attempt to terminate the process with the SIGKILL signal if it still seems to be running. | def shutdown(self):
try:
self._request("POST /shutdown")
time.sleep(0.300)
except requests.exceptions.ConnectionError:
pass
if self._process and self._process.poll() is None:
self._process.kill()
if self._session:
self._session.... | [
"def shutdown():\n os.kill(os.getpid(), signal.SIGTERM)",
"def shutdown(self) -> None:\n prefix = f\"In {ThreadedServer.__name__}.{ThreadedServer.shutdown.__name__}\"\n\n print(f\"{prefix}: Instructing the server to shut down...\", file=self.stdout)\n with self._server_exception_lock:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the kernelspecs table. | def refresh_kernelspecs() -> None:
... | [
"def refresh_kernels() -> None:\n ...",
"def update_spec(self, req, key, opts, spec):",
"def _rename_appkernels_mod_appkernel(self) -> None:\n dry_run = akrr.dry_run\n update_app_kernel_def = True\n update_app_kernel = True\n update_app_kernel_def_list = True\n\n con_appker... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new terminal and returns the name. | def create_terminal() -> str:
... | [
"def create_terminal(self, terminal_name=None, dump_received=None,\n dump_outgoing=None):\n if terminal_name is None:\n terminal_name = self._default_terminal_name\n\n if terminal_name in self._terminals:\n raise TerminalAlreadyExists(\n \"Te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the kernels table. | def refresh_kernels() -> None:
... | [
"def initTable(cls):\n\n # Always include the data kernels first\n Kernel.kernelTable[\"IMAGE\"] = Kernel(\"IMAGE\", \"I\", \"I\")\n Kernel.kernelTable[\"BUFFER\"] = Kernel(\"BUFFER\", \"B\", \"B\")\n Kernel.kernelTable[\"SCALAR\"] = Kernel(\"SCALAR\", \"S\", \"S\")\n\n for node i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new kernel and returns the ID | def create_kernel(name: str) -> str:
... | [
"def create_device(name, device_type, runtime):\n command = 'create \"%s\" \"%s\" \"%s\"' % (\n name, device_type.identifier, runtime.identifier)\n device_id = _run_command(command)\n\n # The device ID has a new line at the end. Strip it when returning.\n return device_id[:-1]",
"def create_ses... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new session or returns existing one if path exists | def create_session(
path: str,
type: str,
name: Optional[str] = None,
kernel_name: Optional[str] = None,
kernel_id: Optional[str] = None,
) -> str:
... | [
"def create_session(self):\n if not self.request.session.session_key:\n self.request.session.save()",
"def use_session(session):\n if session:\n return session\n else:\n return create_session()",
"def create(self):\r\n sessId = Session.generateId()\r\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates an existing session. | def update_session(
id: str,
path: Optional[str] = None,
name: Optional[str] = None,
type: Optional[str] = None,
kernel_name: Optional[str] = None,
kernel_id: Optional[str] = None,
) -> None:
... | [
"def upsert_session(session_data):\n g_db['sessions'].update(\n get_session_id(session_data),\n {\n \"$set\": session_data,\n },\n upsert=True\n )",
"def test_update_session(self):\r\n now = time.time()\r\n\r\n # Make sure the session has data so that it ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a two element tuple. The second element must be a Beliefs object which system1 will use to update the belief module. Once updated, the action queue will be emptied and the rules will be checked for satisfied conditions. The action queue will be refilled with new active actions from the rule list. | def process_belief(self, args):
goal, belief = args
if isinstance(belief, Beliefs):
self.belief_module.process_belief(belief)
self.initialize_action_queue()
return [{}] | [
"def update(self):\n if self.queue != self.last_queue:\n if self.queue == \"OFF\":\n self.cfa.set_led(self.led, 0, 0)\n elif self.queue == \"RED\":\n self.cfa.set_led(self.led, 0, 100)\n elif self.queue == \"GREEN\":\n self.cfa.set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls the belief module's emit_belief method to get and return a Beliefs object with the agents chosen belief for emission. | def emit_belief(self, args):
goal, belief = args
return [{belief: self.belief_module.emit_belief()}] | [
"def process_belief(self, args):\n goal, belief = args\n\n if isinstance(belief, Beliefs):\n self.belief_module.process_belief(belief)\n self.initialize_action_queue()\n\n return [{}]",
"def calculateBeliefs(self):\n\n belief = {}\n\n for question in self.g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if an incoming belief is in conflict with internal beliefs. A conflict occurs when the belief is of opposite valence to a current belief. This method does not update own or perceived beliefs. | def belief_conflict(self, args):
goal, belief = args
if isinstance(belief, Beliefs):
if self.belief_module.is_conflicting_belief(belief):
return [{}]
return [] | [
"def has_conflict(self):\n for diffstat in self.diffstat():\n if diffstat.has_conflict:\n return True\n return False",
"def check_conflicts(self):\n\t\tshutit_global.shutit_global_object.yield_to_draw()\n\t\tcfg = self.cfg\n\t\t# Now consider conflicts\n\t\tself.log('PHASE:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
quad(f, a, b) > \int_a^b f(x) dx Uses some quadrature rule to evaluate the integral. | def quad(f, a, b):
S, D = (b+a)/2.0, (b-a)/2.0
def rescaled_f(x):
return f(x*D + S)*D
return sum(w * rescaled_f(p) for w, p in zip(quad_weights, quad_points)) | [
"def quad(func, a, b, args=()):\n\tx_units = a.units\n\tf_units = func(.5*(a+b)).units\n\n\tI, abserr = sciquad(\n\t\tlambda x : func(x*x_units).to(f_units).magnitude,\n\t\ta.magnitude, b.to(x_units).magnitude,\n\t\targs)\n\n\treturn I*x_units*f_units, abserr*x_units*f_units",
"def adaptive_quad(f, a, b, quad=sim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List or create friendrequests. Create an unconfirmed friendship between two users. Or return all friendships which are not confirmed for the current user. | def create_friend_request():
if request.method == "GET":
friend_requests = [f.to_dict() for f in g.user.get_friend_requests()]
return jsonify({'success': True, 'friend_requests': friend_requests})
if request.method == "POST":
# Get recieving user id from request
json = request.g... | [
"def get_friend_requests(self, user):\n return self.filter(addresser_user=user, status=Friendship.STATUS_PENDING, active=True)",
"def add_friend(self, from_user, to_user, message=None):\n if from_user == to_user:\n raise ValidationError(\"Users cannot be friends with themselves\")\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get, update or delete friendship with the specified id. | def get_friend_request_with_id(id):
# Get friend request
friendship = Friendship.query.get(id)
if friendship is None:
raise CustomError(
404,
message="Friendship with id: {} not found.".format(id)
)
can_view = friendship.actioning_user_id == g.user.id or \
... | [
"def fully_update_friend(id: str):\r\n try:\r\n request_payload = api_helpers.json_payload(request)\r\n api_helpers.verify_required_data_present(\r\n request_payload, FRIEND_RESOURCE_ELEMENTS)\r\n except ValueError as error:\r\n error_response = make_response(jsonify({\"error\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
outLookSender is not utilized in this module but wrote the function in case we want to send from an outlook account in the future | def outLookSender(receiverAddress, receiverName, retainedCompany, companyName, senderName, senderTitle, senderCompany, senderEmail, senderCompanyHomePage, senderPhone, returnHTML=False):
subj = f'Engineers from {retainedCompany} Search'
if returnHTML:
[text, html] = emailTextHTML(receiverName, retainedC... | [
"def _send_outlook(self):\n mail = self._get_outlook_mail()\n mail.send",
"def send_email(to, subject, body, from_name):\r\n\r\n FOOTER = (\"<font color = '#D9D9D9' face = 'Segoe UI'>---------------------------------</font><br/>\" +\r\n \"<span style='font-size: 12px; font-family: Se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
emailJobs is a function that is used to email jobs/careers email addresses for companies in a dataframe | def emailJobs(
df,
retainedCompany,
senderName,
defaultSenderEmail,
emailPassword,
senderTitle,
senderCompany,
senderCompanyHomePage,
senderPhone,
noContactCompanyListPickleFileName,
port=465,
returnHTML=True
):
try:
with open(noContactC... | [
"def send_email(jobs):\n jobs = jobs\n server = smtplib.SMTP(\"smtp.gmail.com\", 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n\n server.login(EMAIL, PASS)\n\n subject = f\"Job Scraper Results\"\n\n if jobs != \"Not working\":\n body = []\n job_ids = [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display HTML icon of OS distribution. | def show_os_icon(self):
if self.os == 0:
return "<i class='devicon-debian-plain'></i>"
elif self.os == 1:
return "<i class='devicon-redhat-plain'></i>"
else:
return "?" | [
"def downloadicon_name(self):\n return 'platform_%s.gif' % \\\n re.sub(r'\\W', '_', self.context.getPlatform()).lower()",
"def icon():\n\n return None",
"def MimeTypeIcon():",
"def icon(self):\r\n return Meta.server_icon(self.guild)",
"def icon(self):\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets "_total_posts" as amount of posts in the VK domain. | async def _set_total_posts_in_domain(self) -> None:
logger.info('Getting total posts in "vk.com/%s"...', self.vk_domain)
params = {
"v": settings.VKAPI_VERSION,
"access_token": settings.VKAPI_TOKEN,
"count": 1, # Enough just to get total post in domain.
... | [
"def get_post_count(self):\n self.post_count = 0\n for post in self.postlist.postlist:\n self.post_count += 1",
"def get_post_count(self):\n self.post_count = 0\n for post in self.postlist:\n self.post_count += 1",
"def posts_count(self):\n return self.ob... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches posts from VK domain asynchronously and put it into "posts" attribute. | async def fetch_posts(self) -> None:
async def fetch_posts_for_offset(offset) -> list:
logger.info(
"(offset %i) Start fetching posts from vk.com/%s...",
offset,
self.vk_domain,
)
# VK Script code for /execute method.
... | [
"async def request_posts(self):\n posts = await database_sync_to_async(self.get_posts)()\n for post in posts:\n await self.send_json(models.post_to_dict(post))",
"def get_posts(self):\n print(\"\\nReading posts currently in database\")\n print(\"-----------------------------... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates posts as Pydantic schemas based on posts data given from VK API. | def posts_as_schemas(posts_from_vk: list[dict]) -> list[Post]:
posts = []
for post_from_vk in posts_from_vk:
try:
post = Post(
date=post_from_vk["date"],
likes=post_from_vk["likes"]["count"],
text=post_from_vk["text"],
path=f"w... | [
"def posts_post():\n data = request.json\n\n try:\n validate(data, post_schema)\n except ValidationError as error:\n data = {\"message\": error.message}\n return Response(json.dumps(data), 422, mimetype=\"application/json\")\n\n post = Post(title=data[\"title\"], body=data[\"body\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds an HParam object with default hyperparameters. | def default_hparams():
raise NotImplementedError('Not implemented') | [
"def get_default_hparams():\n return HParams(\n train_epochs=5,\n do_fine_tuning=False,\n batch_size=32,\n learning_rate=0.005,\n momentum=0.9,\n dropout_rate=0.2,\n l1_regularizer=0.0,\n l2_regularizer=0.0001,\n label_smoothing=0.1,\n validation_split=0.2,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates the trained model using the specified features and labels. | def evaluate(self, features, labels):
raise NotImplementedError('Not implemented') | [
"def evaluate(self, trained_model, model_input, *args, **kwargs):\r\n pass",
"def evaluate_model(model, scaled_test_images, test_labels):\n return model.evaluate(scaled_test_images, test_labels,verbose=2)",
"def evaluate_model(preds, labels):\n ACC, TN, FN, TP, FP = 0, 0, 0, 0, 0\n\n for user in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple wrapper around sklearn's learning curve module | def learning_curve(self, features, labels):
return learning_curve(self._model, features, labels) | [
"def from_sklearn(est):\n return from_sklearn.dispatch(est)",
"def learning_curve(X_train_scaled, Y_train, classifier, score, train_sizes: list):\n # initial parameters\n RANDOM_STATE = 42\n TRAIN_SIZES = train_sizes\n K_FOLDS = 5\n SCORER = make_scorer(score)\n SAMPLING_RATIO = 1\n\n # pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an agent membership | def create_agent_membership(self, context, agent_membership):
am = agent_membership['agent_membership']
with context.session.begin(subtransactions=True):
am_db = AgentMembership(id=am['id'],
ip_address=am['ip_address'])
context.session.add(am_... | [
"def create_agent_membership(self, body=None):\n return self.post(self.agent_memberships_path, body=body)",
"def create_members(client, master_detector_id):\n for account in aws_account_dict.keys():\n # Don't invite yourself, so skip the master account\n if account != master_aws_account_nu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test load class works correctly and raises right exceptions. | def test_load_class():
full_classname = 'collections.namedtuple'
cls_ = load_class(full_classname)
assert cls_ is collections.namedtuple
with pytest.raises(ValueError):
full_classname = 'collections.Foobar'
load_class(full_classname)
with pytest.raises(ImportError):
full_cl... | [
"def test_load_from_class():\n cl = ClassLoader()\n\n cf = ClassFile.create('TestClass')\n cl.update(cf)\n\n assert cl.load('TestClass') is cf",
"def test_load_testcase(self):\n tests = self.loader.load(\"tests.sampletest.hellotest.HelloTest\")\n self.assertEqual(len(tests), 1)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
irq_handler contains the code you want to execute when the interrupt occurs. Define your own callback function here by rewriting the code. We make an LED flash in this example. | def irq_handler():
# open an LED session
with LEDs() as LED:
# specify the LED which you want to control
led = Led.LED1
# specify the LED status
led_on_off = True
# writes values 10 times, which makes LED1 flash for 3 seconds
for x in range(0, 10):
# t... | [
"def irq(self, handler: Callable, trigger: int, hard: bool = False) -> Callable:",
"def enable_irq(state:int):",
"def enable_irq(state=True):\n pass",
"def disable_irq() -> int:",
"def enable_irq(state: bool = True, /) -> None:",
"def disable_irq() -> bool:",
"def test_interrupt_callback(self, mock_g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This property returns the training data, and loads the training data if it doesn't exist. Note that this function returns the training data and labels in the form ([MPS input size, batch, other dimensions], [batch, classifications]) in accordance with how it is used in the MPS and MPSOptimizer classes. If the data is r... | def training_data(self):
if self._training_data is None:
self._load_training_data()
if self._swapped_training_data is None:
self._swapped_training_data = {}
for key, value in self._training_data.items():
self._swapped_training_data[key] = value
... | [
"def load_training_data(self) -> Tuple[List[np.ndarray], np.ndarray]:\n return self._load_set(config.TRAIN_DIR, True)",
"def training_data(self) -> List[state_domain.TrainingDataDict]:\n return self._training_data",
"def load_training_data(self):\n self.flux_data = pd.read_csv(settings['RAW... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Property giving the number of training samples for each key | def num_train_samples(self):
if self._num_training_samples is None:
for key, value in self._training_data.items():
self._num_training_samples[key] = len(value[0])
return self._num_training_samples | [
"def train_size(self):",
"def num_test_samples(self):\n if self._num_test_samples is None:\n for key, value in self._test_data.items():\n self._num_test_samples[key] = len(value[0])\n return self._num_test_samples",
"def _number_of_samples(self):\n return len(self._raw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Property giving the number of test samples | def num_test_samples(self):
if self._num_test_samples is None:
for key, value in self._test_data.items():
self._num_test_samples[key] = len(value[0])
return self._num_test_samples | [
"def num_test_samples(self):\n if self.eval_data is None:\n return 0\n return self.num_test",
"def _number_of_samples(self):\n return len(self._raw_data.samples)",
"def setTestSampleSize(self, Ntest):\n self.Ntest = Ntest",
"def GetNumberOfSamples(self):\n ...",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Highlights currentSelection on stdscr. | def highlightSelection(stdscr, selection):
s = tuple(list(selection.addStrArgs)+[curses.A_REVERSE])
stdscr.addstr(*s) | [
"def capture_highlighted_text(self, event):\n highlighted_by_cursor = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)\n self.text_selected.set(highlighted_by_cursor)",
"def draw_selected(self):\n if self.get_selected() is not None and not self.check_if_locked(self.get_selected()):\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This initializes the DotStars object by setting a buffer, and creating an SPI object. The start and end frames for the SPI communication are created, and the leds are cleared of values. | def __init__(self, leds):
self.ledcount = leds
# create a buffer
self.buffersize = self.ledcount * 4
self.buffer = bytearray(self.ledcount * 4)
self.emptybuffer = bytearray(self.ledcount * 4)
for i in range(0, self.buffersize, 4):
self.emptybuffer[i] = 0xff
... | [
"def SPIsetup(self):\n self.writecmd(0x01,0x10,0,self.data); #SPI/SETUP",
"def spi_init(self):\n self.lw.ctrl_transfer(bmRequestType=0xC0, bRequest=23,\n wValue=0, wIndex=0,\n data_or_wLength=8, timeout=USB_TIMEOUT)",
"def init(\n ba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method clears all the LEDs in the DotStar object | def clearleds(self):
self.buffer = self.emptybuffer[:] | [
"def clear_lights(self):\n pass",
"def clearLEDs(self):\n for pixel in range(self.__striplength):\n self.__pixels[pixel][0:3] = [0, 0, 0]",
"def reset_all(self):\n self.led_service.reset(\"AllLeds\")",
"def reset(self):\n for tlight in self.trafficLights:\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |