query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
List all reactions available in BiGG. The reactions do not contain stoichiometry. To retrieve the full reaction use get_reaction. Returns | def list_reactions():
data = _get("reactions", None, None)
LOGGER.info("Found %i reactions", data[RESULTS_COUNT])
reactions = DictList()
for reaction_data in data[RESULTS]:
reaction_id = reaction_data[BIGG_ID]
if reaction_id in reactions:
continue
reaction = Reaction... | [
"def reactions(self):\n return self.__reactions.list()",
"def AllReactions(self):\n rxns = []\n hashes = set()\n for r in self.reactions.all():\n if r.GetHash() not in hashes:\n rxns.append(r)\n hashes.add(r.GetHash())\n return rxns",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all reactions in a model. | def list_model_reactions(model_id):
data = _get("reactions", None, model_id)
LOGGER.info("Found %i reactions", data[RESULTS_COUNT])
reactions = DictList()
for reaction_data in data[RESULTS]:
reaction_id = reaction_data[BIGG_ID]
if reaction_id in reactions:
continue
r... | [
"def reactions(self):\n return self.__reactions.list()",
"def list_reactions():\n data = _get(\"reactions\", None, None)\n\n LOGGER.info(\"Found %i reactions\", data[RESULTS_COUNT])\n reactions = DictList()\n for reaction_data in data[RESULTS]:\n reaction_id = reaction_data[BIGG_ID]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a reaction in the context of a model from BiGG. | def get_model_reaction(model_id, reaction_or_id, metabolites=None, genes=None):
if genes is None:
genes = {}
if metabolites is None:
metabolites = {}
if isinstance(reaction_or_id, Reaction):
reaction = reaction_or_id
reaction_id = reaction.id
elif isinstance(reaction_or_... | [
"def get_reaction(self, **kwargs):\n rxns = self.get_reactions(**kwargs)\n if len(rxns) == 0:\n print \"KinDA: ERROR: SystemStats.get_reaction() failed to find a reaction with the given criteria.\"\n return None\n elif len(rxns) > 1:\n print \"KinDA: WARNING: SystemStats.get_reactino() found... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all metabolites present in BiGG. Returns | def list_metabolites():
data = _get("metabolites", None, None)
LOGGER.info("Found %i metabolites", data[RESULTS_COUNT])
metabolites = DictList()
for metabolites_data in data[RESULTS]:
metabolite = Metabolite(id=metabolites_data[BIGG_ID], name=metabolites_data[NAME])
metabolites.append(m... | [
"def getAllMembresias(self):\n database = self.database\n sql = \"SELECT * FROM hermes.membresias;\"\n data = database.executeQuery(sql)\n lista = {}\n final = []\n if len(data) > 0:\n for x in data:\n lista = self.convertTuplaToList(x)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all metabolites in a model. | def list_model_metabolites(model_id):
data = _get("metabolites", None, model_id)
LOGGER.info("Found %i reactions", data[RESULTS_COUNT])
metabolites = DictList()
for metabolites_data in data[RESULTS]:
metabolite_id = metabolites_data[BIGG_ID] + "_" + metabolites_data[COMPARTMENT_BIGG_ID]
... | [
"def get_all_from_model(model):\n return get_all_from_query(model.query())",
"def list_metabolites():\n data = _get(\"metabolites\", None, None)\n\n LOGGER.info(\"Found %i metabolites\", data[RESULTS_COUNT])\n metabolites = DictList()\n for metabolites_data in data[RESULTS]:\n metabolite = Met... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a metabolite from BiGG. | def get_metabolite(metabolite_or_id):
if isinstance(metabolite_or_id, str):
metabolite_id = metabolite_or_id
elif isinstance(metabolite_or_id, Metabolite):
metabolite = metabolite_or_id
metabolite_id = metabolite.id
else:
raise ValueError(metabolite_or_id)
match = METAB... | [
"def get_model_metabolite(model_id, metabolite_id):\n data = _get(\"metabolites\", metabolite_id, model_id)\n LOGGER.info(\"Found metabolite %s\", metabolite_id)\n\n metabolite = Metabolite(id=metabolite_id, charge=data[CHARGE],\n formula=data[FORMULA], compartment=data[COMPARTME... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a metabolite in the context of a model from BiGG. | def get_model_metabolite(model_id, metabolite_id):
data = _get("metabolites", metabolite_id, model_id)
LOGGER.info("Found metabolite %s", metabolite_id)
metabolite = Metabolite(id=metabolite_id, charge=data[CHARGE],
formula=data[FORMULA], compartment=data[COMPARTMENT_BIGG_ID])
... | [
"def get_metabolite(metabolite_or_id):\n\n if isinstance(metabolite_or_id, str):\n metabolite_id = metabolite_or_id\n elif isinstance(metabolite_or_id, Metabolite):\n metabolite = metabolite_or_id\n metabolite_id = metabolite.id\n else:\n raise ValueError(metabolite_or_id)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all genes in a model. | def list_model_genes(model_id):
data = _get("genes", None, model_id)
LOGGER.info("Found %i genes", data[RESULTS_COUNT])
genes = []
for gene_data in data[RESULTS]:
gene = Gene(id=gene_data[BIGG_ID], name=gene_data[NAME])
gene.annotation[ORGANISM] = gene_data[ORGANISM]
genes.appen... | [
"def getAllGenes(self):\n return self.data.getAllGenes()",
"def genes(self) -> List[Gene]:\n return self.__genes",
"def get_genres():\n \n return Genre.query.order_by('genre_name').all()",
"def getGenes(self):\n return self.config['GA']['Genes']",
"def genes(context, build):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a gene in the context of a model from BiGG. | def get_model_gene(model_id, gene_or_id):
if isinstance(gene_or_id, str):
gene_id = gene_or_id
elif isinstance(gene_or_id, Gene):
gene_id = gene_or_id.id
else:
raise ValueError(gene_or_id)
data = _get("genes", gene_id, model_id)
LOGGER.info("Found gene %s", gene_id)
g... | [
"def get(gene_id, **kwargs):\n endpoint = endpoints['get-gene'].format(gene_id=gene_id)\n return Gene(get(endpoint, params=kwargs))",
"def get_gene(self, query):\n if len(query) > 4 and query[:4] == 'ENSG':\n g = self.genes[np.where(query == self.gene_ids)[0]]\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get state of alternate images | def get_alt_images(self):
return self.use_alt_images | [
"def get_next_state_from_env(self, imgs):\n state = self.env.get_output_probability(imgs)\n return state",
"def getImageOverride(state: 'SoState') -> \"SbBool\":\n return _coin.SoTextureOverrideElement_getImageOverride(state)",
"def switch_image(self):\n slave = 0xfe\n (status... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify the alternate images | def set_alt_images(self, alt_image):
self.use_alt_images = alt_image
if self.use_alt_images:
self.image_dir = 'images_alt/'
else:
self.image_dir = 'images/' | [
"def setImages(self, image1, image2) -> None:\n ...",
"def update(self, img, boxes):",
"def next_image(self):\n self.index = (self.index + 1) % len(self.images)\n self.show_image(self.images[self.index])",
"def get_alt_images(self):\n return self.use_alt_images",
"def update_all(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a value from the given position in the matrix. >>> M = Matrix(2, 2) >>> M.get_val(0,0) 0 >>> M.set_val(0,0, 1) >>> M.set_val(0,1, 0) >>> M.get_val(0,0) 1 >>> M.get_val(0,1) 0 | def get_val(self, row, column):
return self.__rows[row][column] | [
"def __getitem__(self, position: (int, int) or int):\n x, y = self._position(position)\n\n return self.__matrix[y][x]",
"def value_at(self, pos):\n return self.data[self._data_index(pos)]",
"def get_value(self, addr, value_render=ValueRenderOption.FORMATTED_VALUE):\n addr = format_ad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the value at the given (row, column). >>> M = Matrix(2, 2) >>> M.set_val(0, 0, 1) >>> M.set_val(1, 1, 1) >>> print(M) [1, 0] [0, 1] | def set_val(self, row, column, value):
self.__rows[row][column] = value | [
"def set(self, row, column, value):",
"def set_cell(self, col, row, value):\n \n super(Vec, self).set_cell(col, row, value)\n if self._mat_parent:\n self._mat_parent[1](row, value)",
"def setvalue(self,r,c,value):\n self.M[str(r)+\",\"+str(c)] = value\n self.row[r][... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the last num_bits of num and inserts them into the row. num = 0 0 0 0 0 0 1 0 1 1 row = | def bin_set_row(self, row, num, num_bits, start_offset = 0):
if num_bits + start_offset <= 0:
return
if num_bits + start_offset > self.__column_size:
raise Exception("Num bits cannot be larger than num columns")
if type(num) is list:
num.reverse()
for i in range(0, num_bits):
self.__rows[row][nu... | [
"def toBinary( val, numBits ):\r\n if numBits == 0: return\r\n toBinary( val>>1 , numBits-1 )\r\n print((val & 0x01), end=' ') # print least significant bit\r",
"def make_bits(num, bits):\n assert num < (1 << bits)\n if bits == 0:\n return ''\n return '{num:0{bits}b}'.format... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a row to the end of the matrix. >>> M = Matrix(2, 2) >>> M.insert_row() >>> print(M) [0, 0] [0, 0] [0, 0] >>> M.expand(3, 3) >>> M.insert_row() >>> M [0, 0, 0] [0, 0, 0] [0, 0, 0] [0, 0, 0] | def insert_row(self, new_row = None):
self.__row_size += 1
if new_row is None:
new_row = [self.__init_val for i in range(self.__column_size)]
else:
if len(new_row) < self.__column_size:
raise Exception("Error: Specified column too small for row: {}".format(new_row))
self.__rows.append(new_row) | [
"def insert_row_at_position(self, row_position, new_row = None):\n\t\tif new_row is None:\n\t\t\tnew_row = [self.__init_val for i in range(self.__column_size)]\n\t\telse:\n\t\t\tif len(new_row) < self.__column_size:\n\t\t\t\traise Exception(\"Error: Specified column too small.\")\n\t\t\n\t\tself.__row_size += 1\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts a blank row after the given row. >>> M = Matrix(2, 2, 1) >>> M.set_init_val(0) >>> M.insert_row_at_position(1) >>> print(M) [1, 1] [0, 0] [1, 1] >>> M.insert_row_at_position(1, [1, 1]) >>> print(M) [1, 1] [1, 1] [0, 0] [1, 1] | def insert_row_at_position(self, row_position, new_row = None):
if new_row is None:
new_row = [self.__init_val for i in range(self.__column_size)]
else:
if len(new_row) < self.__column_size:
raise Exception("Error: Specified column too small.")
self.__row_size += 1
self.__rows.insert(row_position, ... | [
"def insert_row(self, new_row = None):\n\t\tself.__row_size += 1\n\t\tif new_row is None:\n\t\t\tnew_row = [self.__init_val for i in range(self.__column_size)]\n\t\telse:\n\t\t\tif len(new_row) < self.__column_size:\n\t\t\t\traise Exception(\"Error: Specified column too small for row: {}\".format(new_row))\n\t\t\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expands the matrix. >>> M = Matrix(2, 2) >>> M.set_val(1, 1, 1) >>> M.expand(3, 3) >>> M.get_row(0) [0, 0, 0] >>> M.get_row(1) [0, 1, 0] >>> M.get_column(0) [0, 0, 0] >>> M.get_column(1) [0, 1, 0] | def expand(self, new_num_rows, new_num_columns):
if new_num_rows < self.__row_size or new_num_columns < self.__column_size:
raise Exception("Expand cannot shrink matrix.")
# Add new columns
for row in self.__rows:
for j in range(self.__column_size, new_num_columns):
row.append(self.__init_val)
# Add... | [
"def expand(self):\n q = self._clone()\n q._expand = True\n return q",
"def exp(self):\n return SparseMatrix(np.exp(self.data), self.rows, self.cols, self.shape)",
"def set_row(self,X,x,j):\n\t\tif not hasattr(x,'shape'):\n\t\t\tx=array(x,dtype=self.dtype)\n\t\t\n\t\t#if self.debug>=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of rows filtered by the given filter function. If no filter is specified returns the whole matrix. >>> M = Matrix(3, 3) >>> M.set_val(0, 0, 1) >>> M.set_val(2, 2, 1) >>> M.filter_rows() [[1, 0, 0], [0, 0, 0], [0, 0, 1]] | def filter_rows(self, row_filter=None):
if row_filter is None:
return self.__rows
return_array = []
for row in self.__rows:
if row_filter(row):
return_array.append(row)
return return_array | [
"def filter(self, filter_func) -> object:\n # creates result array\n filter_new_array = DynamicArray()\n\n # runs filter_func from parameter on each element, then adds to result array\n for index in range(self.size):\n if filter_func(self.get_at_index(index)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts the matrix using the given key. | def sort(self, key=None):
if key is None:
raise Exception("Key cannot be null to sort matrix.")
self.__rows.sort(key=key) | [
"def sort_by_key(ds, key):\n return sorted(ds, key = lambda x : x[key])",
"def sort(self, key, reverse=False):\n self.player_data.sort(key=lambda x: x[key], reverse=not reverse)\n self.display()",
"def order_matrix(mtr, n_column):\n mtr = sorted(mtr, key=lambda mtr: float(mtr[n_column]))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the matrix transposed. Does not modify the matrix itself. >>> M = Matrix(2, 3) >>> M.set_val(0, 0, 1) >>> M.set_val(1, 1, 1) >>> M.set_val(0, 2, 1) >>> M [1, 0, 1] [0, 1, 0] >>> M.get_transposed() [1, 0] [0, 1] [1, 0] | def get_transposed(self):
# Create a matrix with columns and row sizes swapped
matrix = Matrix(0, self.__row_size)
# Begin looping through and making rows
for i in range(0, self.__column_size):
matrix.insert_row([v[i] for v in self.__rows])
return matrix | [
"def transpose(self):\n res = list()\n for col in range(self.columns):\n res.append([self.matrix[row][col] for row in range(self.rows)])\n return Matrix(res)",
"def transpose(self) -> \"SbMatrix\":\n return _coin.SbMatrix_transpose(self)",
"def v_transpose(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes duplicate rows from a matrix. | def remove_duplicate_rows(self):
result = []
for row in self.__rows:
if row in result: continue
result.append(row)
self.__rows = result
self.__row_size = len(self.__rows) | [
"def remove_duplicate_rows(matrix):\n if type(matrix) is not list:\n return matrix\n new_matrix = []\n for line in matrix:\n if line not in new_matrix:\n new_matrix.append(line)\n return new_matrix",
"def unique_rows(matrix):\n return np.vstack({tuple(row) for row in matrix... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of variables where `query` is found in `field_name`. | def search(query, field_name):
params = {'query': query, 'fieldName': field_name}
return _get('search', params)['matches'] | [
"def find_vars(query, is_a_var = is_any_var) :\n\ttry :\n\t\titer = query.__iter__()\n\texcept AttributeError :\n\t\tif is_a_var(query) :\n\t\t\treturn set([var_name(query)])\n\t\treturn set()\n\t\n\tvars = set()\n\tfor i in iter :\n\t\tvars.update(find_vars(i, is_a_var))\n\treturn vars",
"def filter_hostfields_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively pop dictionary entries with '.' in their keys. | def _pop_non_leaf_keys(nested_config: dict) -> None: # noqa: WPS430
for key, val in list(nested_config.items()):
if "." in key:
nested_config.pop(key)
elif isinstance(val, dict): # noqa: WPS220
_pop_non_leaf_keys(val) | [
"def _pop_key(self, doc, key):\n path = key.split('.')\n cur = doc\n for step in path[:-1]:\n cur = cur[step]\n cur.pop(path[-1], None)",
"def pop_dunder_recursive(dictionary):\n keys = [key for key in dictionary.keys()]\n for key in keys:\n if key.startswith(\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event listener for 'save' button on subject information tab. The subject information typed in Gself.ui will be saved to subject.txt | def onClicked_button_save_subject_information(self):
self.participant.first_name = self.ui.lineEdit_first_name.text()
self.participant.last_name = self.ui.lineEdit_last_name.text()
self.participant.gender = self.ui.lineEdit_gender.text()
self.participant.age = self.ui.lineEdit_age.text()... | [
"def save_subject(self) -> None:\n new_subject_name = self.Dialog.line_edit_subject_name.text()\n if len(new_subject_name) <= 30 and len(new_subject_name.strip(\" \")) > 0:\n print(new_subject_name)\n self.list_widget_my_subjects.addItem(new_subject_name)\n self.list_w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Maps services to drivers. | def _map_service_to_driver(self, service):
if service in mapper:
return mapper[service]
return service | [
"def services(\n self,\n ) -> google.protobuf.internal.containers.MessageMap[\n builtins.str, global___GapicMetadata.ServiceForTransport\n ]:",
"def _load_drivers(self):\n self.drivers, self.default_provider = service_base.load_drivers(\n constants.LOADBALANCER, self)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create volume backups using configured backup service. | def create_backup(self, context, backup_id):
bakup = self.db.backup_get(context, backup_id)
volume_id = bakup['volume_id']
volume = self.db.volume_get(context, volume_id)
LOG.info(_LI('Create backup started, backup: %(backup_id)s '
'volume: %(volume_id)s.'),
... | [
"def backup_volume(ec2,instances):\n\n for instance in instances:\n retention = get_retention(instance)\n if not is_master(instance['PrivateIpAddress']):\n #make snapshot only on primary\n continue\n\n for dev in instance['BlockDeviceMappings']:\n if dev.get(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restore volume backups from configured backup service. | def restore_backup(self, context, backup_id, volume_id):
LOG.info(_LI('Restore backup started, backup: %(backup_id)s '
'volume: %(volume_id)s.'),
{'backup_id': backup_id, 'volume_id': volume_id})
backup = self.db.backup_get(context, backup_id)
volume = self... | [
"def restore_backup(self, backup, name, flavor, volume):\r\n return self._manager.restore_backup(backup, name, flavor, volume)",
"def restore_instance(self, backupjob, backupjobrun, backupjobrun_vm, vault_service, db, context, update_task_state = None): \n restored_image = None\n device_rest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a volume backup. This method is used in volumebased instance backup. | def _create_backup_for_instance_backup(self, context, backup_id):
backup = self.db.backup_get(context, backup_id)
volume_id = backup['volume_id']
volume = self.db.volume_get(context, volume_id)
# volume's display_description attribute is used to save
# backup's previous_status a... | [
"def create_backup(self, context, backup_id):\n bakup = self.db.backup_get(context, backup_id)\n volume_id = bakup['volume_id']\n volume = self.db.volume_get(context, volume_id)\n LOG.info(_LI('Create backup started, backup: %(backup_id)s '\n 'volume: %(volume_id)s.')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A key identifying a particular filter for a user's stream. This filter is useful to retrieve relevant items from the stream table. | def getFilterKey(self): | [
"def streamGet(self, filterKey, callback):\n self.streamGet(None, None, None, None, None, filterKey, None, callback)",
"def filter_name(self): # pragma: no cover\n return self._filter_name",
"def _filter(self, stream):\n w = self.widgets\n type = str(w.qComboBox_filterType.currentTe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The URL to the filter icon. For applications, this is the same as your application icon. | def getIconUrl(self): | [
"def icon_url(self):\n return posixpath.join(settings.MEDIA_URL, settings.ICON_DIR, self.icon_file_name)",
"def favicon_url(self):\n return self._favicon_url",
"def icon_path(self):\n return os.path.join(settings.MEDIA_ROOT, settings.ICON_DIR, self.icon_file_name)",
"def icon_file_name(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get type as enum | def getTypeEnum(self):
return Type.valueOf(self.getType()) | [
"def get_enum_type(self, type_name: str) -> EnumType:\n return EnumType.find(self.db, type_name)",
"def get_enum_type(atomic_type):\n return Type(BaseType(atomic_type), None, 1, sys.maxsize)",
"def getEnumNameFromValue(value):\n for t, tobj in list(TypeDef.typeDict.items()):\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the source type, eg gps or router, of the device. | def source_type(self) -> str:
return SOURCE_TYPE_GPS | [
"def GetDeviceType(self):\n if self._deviceType == DeviceType.Unknown:\n v = self.GetVersion()\n modelLine = next((line for line in v.splitlines() if \"Model:\" in line), None)\n if modelLine :\n model = modelLine.split(\":\")[1].strip()\n if model.startswith(\"ex\") or model.start... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return latitude value of the device. | def latitude(self) -> float:
lat = self.__get_mower_attributes()["positions"][0]["latitude"]
return lat | [
"def latitude(self):\n return self.__latitude",
"def min_latitude(self):\n return self._min_latitude",
"def latitude(y: GPSEvent) -> float:\r\n return y.latitude.component",
"def lat(self):\n if self.repr == 'cartesian':\n self.to_spherical_coords()\n\n return switch_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return longitude value of the device. | def longitude(self) -> float:
lon = self.__get_mower_attributes()["positions"][0]["longitude"]
return lon | [
"def longitude(self) -> float:\n return self.raw_data[\"lon\"]",
"def longitude(self):\n return self.__longitude",
"def longitude_meuss (self) :\n return - self.longitude",
"def longitude(self):\n return self.geom.centroid.x",
"def longitude(y: GPSEvent) -> float:\r\n return y... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mutator for circumference of Tree object. | def set_circumference(self, new_circumference: float):
if new_circumference < 0:
raise ValueError("THe tree's circumference cannot be negative")
self.__circumference = new_circumference | [
"def circumference(self, circumference: float):\n\t\tself.r = circumference/(2*PI)",
"def circumference(self):\n\t\treturn 2 * PI * self.r",
"def set_circumference(self, circumference):\n if circumference > 0:\n self.__circumference = circumference",
"def radius_at_node(self):\n try:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return representational string that describes the tree object. | def __repr__(self):
return "Tree(\"" + self.__species + "\", " + str(self.__age) + ", " + str(self.__circumference) + ")" | [
"def __repr__(self):\n \n if self.value == None:\n if self.parent == None:\n return \"none node (key = \\\"\"+self.key+\"\\\", completeName = \"+self.getCompleteName()+\", parent = None, child count = \"+str(len(self.childs))+\", valueSet = \"+str(self.valueSet)+\")\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ct_calibrate convert CT detections to linearised attenuation sinogram = ct_calibrate(photons, material, sinogram, scale) takes the CT detection sinogram in x (angles x samples) and returns a linear attenuation sinogram (angles x samples). photons is the source energy distribution, material is the material structure con... | def ct_calibrate(photons, material, sinogram, scale, correct=True):
# Get dimensions and work out detection for just air of twice the side
# length (has to be the same as in ct_scan.py)
n = sinogram.shape[1]
# work out value of a sinogram point of air
v = ct_detect(photons, material.coeff('Air'), 2*n*scale,1)[0... | [
"def ct_calibrate(photons, material, sinogram, scale, correct=True):\n\n\t# Get dimensions and work out detection for just air of twice the side\n\t# length (has to be the same as in ct_scan.py)\n\tif len(sinogram.shape) > 1:\n\t\tn = sinogram.shape[1]\n\t\tangles = sinogram.shape[0]\n\telse:\n\t\tn = sinogram.shap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a message to a particular UID. No response is given. | def send_message(self, uid, message):
for c in self.client_connections:
if c.their_uid == uid:
if not c.send_data(message):
print "Something is wrong! Player returned an error."
return | [
"def send_message(msg, uid) :\n #get chatpartner\n try:\n u = Users.objects.get(uid=uid)\n except Users.DoesNotExist :\n return -1 ##Could not send because user not found. maybe diconnected?\n \n partner=str(u.partner)\n #put it in his queue\n try:\n p = Users.objects.get(u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the game. This function should not return until we are finished. | def run(self):
while True:
if self.phase == 0: self.welcome_run()
elif self.phase == 1: self.board_negotiation_run()
elif self.phase == 2: self.turn_order_run()
elif self.phase == 3: self.initial_placement_run()
elif self.phase == 4: self.game_play_run... | [
"def run():\n\n clear_shell()\n play(choose_difficulty())",
"def main():\n run_game(even)",
"def continue_game(self):\n self.game()",
"def start_program():\r\n _game.invoke_when_program_starts_callbacks()\r\n _task_runner.loop.call_soon(_game.run)\r\n try:\r\n _task_runner.loop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Welcome phase. Tell all the other players that we're ready to play. | def welcome_run(self):
self.broadcast_message({'ready': True})
print "Waiting for all players to be ready..."
while not all(self.players_ready.values()):
time.sleep(1)
print "..."
print "Ready to play! Starting game in 3 seconds..."
self.all_uids = [c.the... | [
"async def ready(self, ctx):\n if not await self.check_pm(ctx.message):\n return\n if self.game_status == 0:\n await ctx.send(embed=self.make_embed(\"Avalon\", 0xff4055, \"Error\", \"There is no active game. Start a game by running `[p]avalon start`.\"))\n return\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Board negotiation phase. We shuffle the board pieces... | def board_negotiation_run(self):
print "Negotiating board..."
self.decided_board = self.run_public_shuffle(range(19), board.board_shuffle_and_encrypt, board.board_decrypt)
time.sleep(3)
print "Negotiating board roll values..."
self.decided_board_roll_values = self.run_public_shuf... | [
"def test_board(self):\n \n self.finished_board = [\n [ 6 , 8 , 7 ,\"X\",\"X\", 4 , 5 , 2 , 3 ], # \n [ 9 , 5 , 3 ,\"X\",\"X\", 2 , 6 , 1 , 4 ], #\n [ 1 , 4 , 2 , 3 , 5 , 6 , 9 , 7 , 8 ], #\n [ 3 , 1 ,\"X\",\"X\",\"X\", 7 , 2 , 4 , 6 ], #\n [ 7 , ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detemine the turn order of the players by rolling the distributed dice. We roll the dice once for each player in UID order... | def turn_order_run(self):
print "Determining turn order!"
die_order = sorted([c.their_uid for c in self.client_connections] + [self.uid])
die_results = {}
max_roll = -1
max_roller = None
while True:
die_results = {}
for current_uid in die_order:
... | [
"def random_duel(self, players):\n if self.marksmanships[players[0]] == self.marksmanships[players[1]]:\n return players\n\n self.duel_count += 1\n while len(players) == 2 :\n random.shuffle(players)\n starting_player = players[0]\n if flip(self.marksmanships[start... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the scatter plot between the point predictions and the labels | def plot_scatter(predictions, labels, ax=None):
if ax is None:
plt.figure(figsize=(5, 5))
ax = plt.gca()
r_max = max(predictions.max(), labels.max())
r_min = min(predictions.min(), labels.min())
r_max, r_min = r_max + (r_max - r_min) * 0.1, r_min - (r_max - r_min) * 0.1 # Margin of... | [
"def plot_prediction(self, *args):\n pass",
"def plot_true_vs_predicted(labels, predictions, param_labels, fiducial_point):\n # mean and std\n preds_m = np.mean(predictions, axis=1)\n preds_s = np.std(predictions, axis=1)\n\n # number of params\n n_params = len(param_labels)\n\n # plot\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get all customers based on partner | def get_customers_based_on_partner(self):
return Customers.objects.filter(partner_id=self.partner).values_list('id', flat=True) | [
"def get_customers():\n try:\n openConnection\n with conn.cursor() as cur:\n result = cur.run_query('SELECT * FROM customer')\n cur.close()\n conn.close()\n except:\n return Exception\n customers = []\n for row in result:\n if row[0] == 1:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
'if' Exp 'then' Exp ('else' Exp)? | lhs 'if' Exp ('else' Exp)? | def parseIf(self, i, lhs, op=None, rws=EMPTY_SET):
(_, i) = self.consumeKeyword('if', i)
if lhs is None:
(p, i) = self.consumeExp(i, None, None, frozenset(['then']))
(_, i) = self.consumeKeyword('then', i)
(lhs, i) = self.consumeExp(i, None, op, rws | frozenset([... | [
"def assign_with_ternary():\n var = 'first' if 1 == 1 else 'second'\n print(var) # first\n var = 'hello' if 2 == 1 else 'goodbye'\n print(var) # goodbye\n var = 'yes' if (1 == 3 or 2 == 2.0) else 'no'\n print(var) # yes",
"def iif(cond,Then,Else):\n if cond:\n return Then\n return E... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the length of the line segment that is between the two specified coordinates | def GetSegmentLength(X1,Y1,X2,Y2):
DX=X2-X1
DY=Y2-Y1
Length=math.sqrt(DX*DX+DY*DY)
return(Length) | [
"def GetSegmentLength(self,X1,Y1,X2,Y2):\n\tDX=X2-X1\n\tDY=Y2-Y1\n\tLength=math.sqrt(DX*DX+DY*DY)\n\treturn(Length)",
"def segment_length(points):\n return points[0].distance_to(points[1])",
"def path_length(x, y):\n rx = np.asarray([x[0]] + [x[i]-x[i-1] for i in range(1,len(x))])\n ry = np.asarray... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get absolute path to apsERPCommands.h file | def get_apsERPCommands_file(cls):
return os.path.join(cls.get_script_path(), "apsERPCommands.h") | [
"def getAbsPath() -> str:\n thisFile:str = os.path.realpath(__file__)\n absPath:str = thisFile.replace(\"/srcTemplates.py\",\"\")\n return absPath",
"def getSubuserCommandsDir():\r\n return os.path.join(getSubuserDir(),\"logic\",\"subuserCommands\")",
"def get_libedit_include_dir(host: hosts.Host) -> ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Skip and limit values are set together in Python ICAT, limit value should match max entities allowed in one transaction in ICAT as defined in ICAT properties | def test_limit_and_skip_merge_correctly(self, icat_query, skip_value, limit_value):
skip_filter = PythonICATSkipFilter(skip_value)
limit_filter = PythonICATLimitFilter(limit_value)
filter_handler = FilterOrderHandler()
filter_handler.add_filters([skip_filter, limit_filter])
filt... | [
"def set_Limit(self, value):\n super(ListIncidentsInputSet, self)._set_input('Limit', value)",
"def test_start_criteria_limit_flag(self):\n\n flags = {'limit': 1}\n assert not phout.stop_criteria(0, None,\n flags), \"limit flag should not hit\"\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the paramfile to determine the scan params | def getScanParams(paramfile):
outDict = {
"speed": None,
"start": None,
"end": None,
"plateID": None,
}
with open(paramfile, "r") as f:
paramLine = f.readlines()
for line in paramLine:
param, val = line.split()
if param == "plateID":
o... | [
"def load_paramters(self, parameter_file):\n return 0",
"def read_par_file(filename):\n parameter_file=file(filename, \"r\")\n parameters={}\n parameter_match=re.compile(r\"(\\S+) += +(.*)\")\n fnumber_match=re.compile(r\"^[+-]?\\d*(\\.\\d*)?([eE][+-]?\\d+)?$\")\n dnumber... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
call callFunc when acquision has started (first image seen in directory) | def beginAcquisition(self, callFunc=None):
print("beginAcquisition")
if callFunc is not None:
# print("setting acquision cb: %s"%str(callFunc))
self.acquisitionCB = callFunc
self.acquiring = True
# this process initializes and starts the camera
startCaptur... | [
"def execute_launch(self):\n self.ignition()\n self.ascent()\n self.setup_circularization()\n return",
"def reloadImage():\n pass",
"def xray_detector_start(self):\n if self.xray_detector_enabled:\n info(\"Setting up X-ray detector...\")\n import lauec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[in] scanMovie a ScanMovie Obj | def __init__(self, imageDir, scanMovie):
self.imageDir = imageDir
self.scanMovie = scanMovie | [
"def perform_scan() -> None:\n local_movies = list(local_scan())\n database_movies = load_database()\n new_movies = np.setdiff1d(local_movies,database_movies) #Find local movies not appearing in the DB\n for i in new_movies:\n api_result = api_request(i)\n converted_literal = ast.literal_e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns text from render() and generates breaks | def text(self):
text = self.render()
lines = text.split('\n')
breaks = list()
rising_edge = True
for i in range(len(lines)):
try:
if rising_edge:
if space_count(lines[i]) > space_count(lines[i+1]):
rising_edg... | [
"def render(self, user):\n self._render_text = self.content.replace('\\n', '<br>')\n return render_str(\"post.html\", p=self, user=user)",
"def render_text(self, indent: str = \" \") -> str:\n self.preprocess()\n return f\"{self._start()}{self._mid(indent)}{self._end()}\"",
"def r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test running the example timer case | def test001(self):
stream = StringIO.StringIO()
runner = pa.ProgressTimerRunner(stream=stream)
result = runner.run(pa.TimerSuite([
my_module_timers.MyModuleTimers("time_a"),
my_module_timers.MyModuleTimers("time_b"),
my_module_timers.MyModuleTimers("time_c"),
]))
... | [
"def test_timer():\n timer = hug.directives.Timer()\n assert isinstance(timer.start, float)\n assert isinstance(float(timer), float)\n assert isinstance(int(timer), int)\n\n timer = hug.directives.Timer(3)\n assert isinstance(timer.start, float)\n assert isinstance(float(timer), float)\n ass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the contains of this EquipmentUpdate. | def contains(self) -> int:
return self._contains | [
"def intersect(self):\n\n return self._intersect",
"def __contains__(self,item):\n return item in self._set",
"def __contains__(self, item):\n return item in self.__bag",
"def __contains__(self, item):\n return self.has_matching_inventory(item)",
"def is_set(self) -> bool:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the online of this EquipmentUpdate. | def online(self, online: bool):
self._online = online | [
"def _setOnline(self, online):\n if self.online != online:\n self.online = online\n twisted_logger.writeLog(self.logPrefix, self.logName, \"Changing online status to %s\" % online)\n # Call back (trigger) external deferreds\n if online:\n [self.__cal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the resource of this EquipmentUpdate. | def resource(self, resource: int):
self._resource = resource | [
"def update_resource(self, resource):\n raise NotImplementedError(\"update_resource is not implemented\")",
"def resource_version(self, resource_version):\n\n self._resource_version = resource_version",
"def modify_resource(self):\n \"\"\" Create or update resources \"\"\"\n json_payload... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves only modified references for recipes | def _partial_save(self, refs):
remotes, _, prefs = self._load()
self._save(remotes, refs, prefs) | [
"def update_recipes(ideas, recipe_updates):\n\n pass",
"def store_references(context):\n all_references = get_all_references(context)\n key = 'ALL_REFERENCES'\n IAnnotations(context)[key] = all_references\n logger.info('Stored {} relations for later restore.'.format(\n len(all_references)))"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reverse all elements in the provided sequence | def reverse_elements(seq):
return seq[::-1] | [
"def elements_reversed(seq):\n return seq[::-1]",
"def reversed(seq):\n\n l=list(seq)\n l.reverse()\n return l",
"def reverse(L):\r\n return L[::-1]",
"def reverse(self):\n self.flips.reverse()\n for e in self.flips:\n self.permute(e, False)\n self.flips = []",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait until written lines are processed by 'increment_counter' method. | def wait_for_new_lines(self, expected_line_number=1, timeout=3):
with self._increment_line_cv:
start_time = time.time()
while self._reported_lines_count != expected_line_number:
self._increment_line_cv.wait(timeout)
if time.time() - start_time >= timeout:
... | [
"def _wait_for_data(self):\r\n curpos = self.fileobj.tell()\r\n cursize = os.fstat(self.fileobj.fileno()).st_size\r\n while curpos >= cursize:\r\n time.sleep(0.01)\r\n cursize = os.fstat(self.fileobj.fileno()).st_size",
"def _process(self):\n rospy.logwarn(\"BEFOR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select backend for the given source and output formats. | def _get_driver(mime_src, mime_out):
# TODO: make this configurable
if mime_src == 'application/x-esa-envisat' and \
mime_out == 'application/x-netcdf':
return "BEAM", "NetCDF4-BEAM"
elif mime_src == 'application/x-esa-envisat' and \
mime... | [
"def choose_backend(backend, path=None):\n\n if (\n (not check_pygraphviz_installed() and backend is None)\n or (backend == \"d3\")\n or (backend is None and path and Path(path).suffix == \".html\")\n ):\n return \"d3\"\n\n elif backend == \"mermaid\":\n return \"mermaid\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get extent (pixel rectangle) of the source and destination images matching the requested subsetting. | def get_src_and_dst_rect(dataset, subsets):
size_x, size_y = dataset.RasterXSize, dataset.RasterYSize
image_rect = Rect(0, 0, size_x, size_y)
if not subsets:
subset_rect = image_rect
# pixel subset
elif subsets.srid is None: # means "imageCRS"
minx, miny... | [
"def get_extent(y, x):\n dy = y[1] - y[0]\n dx = x[1] - x[0]\n extent = [x[0] - 0.5 * dx, x[-1] + 0.5 * dx, y[-1] + 0.5 * dy, y[0] - 0.5 * dy]\n return extent",
"def extent_2d(self):\n cosine = math.cos(math.radians(self.rot))\n sine = math.sin(math.radians(self.rot))\n width = (s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
All Mitre ATT&CK Techniques should have tactics | def test_tactics_have_techniques(attck_fixture):
for tactic in attck_fixture.enterprise.tactics:
assert getattr(tactic,'techniques') | [
"def attack(self):\r\n pass",
"def getAdjectiveTraits(self):\n\n if self.adjective == 0: #Fierce\n self.speed += 1\n self.dropRate += 1\n self.spriteList.append(self.fierce_sprite)\n\n elif self.adjective == 1: #Monstrous\n self.size *= 2\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch observations from the data store according to criteria defined in the configuration. | def get_observations(self):
self.config.validate()
log.info("Fetching observations.")
datastore_path = make_path(self.settings["observations"]["datastore"])
if datastore_path.is_file():
datastore = DataStore().from_file(datastore_path)
elif datastore_path.is_dir():
... | [
"def get_records(self, context, domain_id, criterion=None):",
"def _fetch_data(self, since=None):\n if since is not None:\n period_start = since\n else:\n period_start = self.building_status[\"first_measurement_date\"]\n period_end = self.building_status[\"last_variable_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make maps and datasets for 3d analysis. | def _map_making(self):
log.info("Creating geometry.")
geom = self._create_geometry(self.settings["datasets"]["geom"])
if "geom-irf" in self.settings["datasets"]:
geom_irf = self._create_geometry(self.settings["datasets"]["geom-irf"])
else:
geom_irf = geom.to_bins... | [
"def generate_empty_3d_map(self):\n self.map = np.zeros(self.dimensions)",
"def build_3D_map_docks(self):\n #self.map_img_dock = Dock(\"2D Map Img\", size=(2, 6))\n self._3D_surface_dock = Dock(\"3D Map\", size=(2, 6))\n\n self._3D_maps_ui.addDock(self._3D_surface_dock, 'left')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set logging parameters for API. | def _set_logging(self):
logging.basicConfig(**self.settings["general"]["logging"])
log.info(
"Setting logging config: {!r}".format(self.settings["general"]["logging"])
) | [
"def log_parameters(self):\n logging.info(\"### TICKER = %s \" % self.ticker)\n logging.info(\"### STRIKE = %f \" % self.strike_price)\n logging.info(\"### DIVIDEND = %f \" % self.dividend)\n logging.info(\"### VOLATILITY = %f \" % self.volatility)\n logging.info(\"### TIME TO MAT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate settings before proceeding to data reduction. | def _validate_reduction_settings(self):
if self.observations and len(self.observations):
self.config.validate()
return True
else:
log.info("No observations selected.")
log.info("Data reduction cannot be done.")
return False | [
"def validate_settings(self):\n pass",
"def clean_and_validate_options(self):\n pass",
"def _validate_fp_settings(self):\n valid = True\n if self.fit:\n self.config.validate()\n else:\n log.info(\"No results available from fit.\")\n valid = Fal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate settings before proceeding to fit 1D. | def _validate_fitting_settings(self):
if not self.model:
log.info("No model fetched for datasets.")
log.info("Fit cannot be done.")
return False
else:
return True | [
"def test_fit(self):\n self._fit()",
"def _validate_reduction_settings(self):\n if self.observations and len(self.observations):\n self.config.validate()\n return True\n else:\n log.info(\"No observations selected.\")\n log.info(\"Data reduction can... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate settings before proceeding to flux points estimation. | def _validate_fp_settings(self):
valid = True
if self.fit:
self.config.validate()
else:
log.info("No results available from fit.")
valid = False
if "flux-points" not in self.settings:
log.info("No values declared for the energy bins.")
... | [
"def validate_settings(self):\n pass",
"def _validate_reduction_settings(self):\n if self.observations and len(self.observations):\n self.config.validate()\n return True\n else:\n log.info(\"No observations selected.\")\n log.info(\"Data reduction c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create AnalysisConfig from existing templates. | def from_template(cls, template="basic"):
filename = CONFIG_PATH / ANALYSIS_TEMPLATES[template]
return cls.from_yaml(filename) | [
"def _create_template_config(self, config):\n pass",
"def create_site_config(template_dir, temp_dir):\n item_config = {}\n for file in Path(template_dir).glob(\"*\"):\n if not file.is_dir():\n with file.open(mode=\"r\", encoding=\"utf-8\") as f:\n line = f.readline()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns dict with commented docs from docs file | def _get_doc_sections():
doc = defaultdict(str)
with open(DOCS_FILE) as f:
for line in filter(lambda line: not line.startswith("---"), f):
line = line.strip("\n")
if line.startswith("# Section: "):
keyword = line.replace("# Section: ", "")
... | [
"def extract_docstrings(filename):\n docstrings = []\n is_in_chunk = False\n chunk = None\n i = 0\n with open(filename, \"r\") as filedata:\n for raw_line in filedata.readlines():\n i += 1\n line = raw_line.strip('\\n')\n if line.startswith(\"----\") or line.st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check a number may also be an astropy quantity. | def _astropy_quantity(_, instance):
is_number = jsonschema.Draft7Validator.TYPE_CHECKER.is_type(instance, "number")
return is_number or is_quantity(instance) | [
"def require_quantity(self):\n n = self.require_quant_exact()\n m = None\n if self.the_char == \",\":\n self.next_char()\n if self.match_one(\"0123456789\"):\n m = self.require_quant_exact()\n if n > m:\n raise RegularExpres... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
main function to create OddNumbers instance and get use of it | def main():
oddnumbers = OddNumbers()
oddnumbers.get_oddnumbes() | [
"def __init__(self):\n print(\"Initializing OddEven()...\")",
"def BuildNumber(self) -> int:",
"def test_five_code_wars():\n from get_nth_even_number import nth_even\n assert nth_even(1298734) == 2597466",
"def __new__(cls, *args, **kwargs):\n return BuiltInClass.get_instance(cls, 'NUMBER'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests push operation on linked list. | def test_push(self):
list = LinkedList([2, 3, 4])
pushedNode = list.push(1)
self.assertEqual(pushedNode, list.head) | [
"def test_linked_list_push_adds_new_item():\n from linked_list import LinkedList\n l = LinkedList()\n l.push('val')\n assert l.head.data == 'val'",
"def test_linked_list_push_moves_old_head_to_new_head_next():\n from linked_list import LinkedList\n l = LinkedList()\n l.push('val')\n l.push... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests append operation on linked list. | def test_append(self):
list = LinkedList([1, 2, 3])
appendedNode = list.append(4)
self.assertEqual(appendedNode, list.tail) | [
"def test_append_test_non_empty_list(self):\n ll = LinkedList()\n some_string = \"holis\"\n some_value = 15\n ll.append(some_string)\n ll.append(some_value)\n self.assertEqual(ll.tail.previous.next.data, some_value)\n self.assertEqual(ll.tail.previous.data, some_stri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests nth_node operation on linked list. | def test_nth_node(self):
list = LinkedList()
node = list.append(50)
firstNode = list.nthNode(0)
self.assertEqual(node, firstNode) | [
"def test_negative_nth_node(self):\n list = LinkedList([1, 2, 3])\n nthNode = list.nthNode(-1)\n self.assertIsNone(nthNode, \"The nth node should be None\")",
"def test_out_of_bounds_nth_node(self):",
"def test_linked_list_search_in_many_returns_proper_node(n):\n from linked_list import ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests edge case on linked list's nth_node operation where the nth is a negative integer. | def test_negative_nth_node(self):
list = LinkedList([1, 2, 3])
nthNode = list.nthNode(-1)
self.assertIsNone(nthNode, "The nth node should be None") | [
"def test_out_of_bounds_nth_node(self):",
"def test_nth_node(self):\n list = LinkedList()\n node = list.append(50)\n firstNode = list.nthNode(0)\n self.assertEqual(node, firstNode)",
"def _assert_node_index(i, size):\n if i >= size:\n # Error message must be a compile-time ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests edge case on linked list's nth_node operation where the nth is a integer greater than the length of the list. | def test_out_of_bounds_nth_node(self): | [
"def test_nth_node(self):\n list = LinkedList()\n node = list.append(50)\n firstNode = list.nthNode(0)\n self.assertEqual(node, firstNode)",
"def test_negative_nth_node(self):\n list = LinkedList([1, 2, 3])\n nthNode = list.nthNode(-1)\n self.assertIsNone(nthNode, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the length operation on linked list. | def test_length(self):
list = LinkedList([1, 2, 3, 4, 5])
listLength = list.getLength()
self.assertEqual(5, listLength) | [
"def test_len():\n l = LinkedList()\n l.insert(8)\n l.insert(9)\n l.insert(10)\n assert l.__len__() == 3",
"def len_test(list_):\n correct_length = 241\n if len(list_) == correct_length:\n return(print('test passed'))\n else:\n return(print('test failed'))",
"def get_LL_len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the deleteKey operation on linked list. | def test_key_deletion(self):
pass | [
"def test_delete_key(client):\n resp = client.delete_key(PROJECT_ID, 48855760)\n assert resp['project_id'] == PROJECT_ID\n assert resp['key_removed']",
"def test_delete_by_key(self):\n for i in range(200):\n item = {\n 'UserId': '123',\n 'CartName': f'a{i}'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the delete position operation on linked list, deleting the first position. | def test_delete_first_position(self):
list = LinkedList([1, 2, 3, 4])
list.deletePosition(0)
self.assertEqual(list.head.data, 2) | [
"def test_delete_last_position(self):\n list = LinkedList([1, 2, 3, 4])\n list.deletePosition(3)\n self.assertEqual(list.tail.data, 3)",
"def delete(self, position=0):\n if not isinstance(position, int):\n raise TypeError\n if self.head is None:\n return No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the delete position operation on linked list, deleting the last position. | def test_delete_last_position(self):
list = LinkedList([1, 2, 3, 4])
list.deletePosition(3)
self.assertEqual(list.tail.data, 3) | [
"def test_delete_first_position(self):\n list = LinkedList([1, 2, 3, 4])\n list.deletePosition(0)\n self.assertEqual(list.head.data, 2)",
"def delete(self, position=0):\n if not isinstance(position, int):\n raise TypeError\n if self.head is None:\n return N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the names of all imported snp sets | def getSNPSetsList() :
import rabaDB.filters as rfilt
f = rfilt.RabaQuery(SNPMaster)
names = []
for g in f.iterRun() :
names.append(g.setName)
return names | [
"def listDatasets():\n return ee_extra.STAC.core.listDatasets()",
"def sys_names(self):\n names = []\n for sample in self.samples:\n names.extend(sample.sys_names())\n return list(set(names))",
"def names(self, pubs=EmptyI):\n\n base = self.get_part(self.__BASE_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1. Get Ideas takes board object | def get_ideas(board):
# 1a query database for all ideas with colour
ideas = Idea.get_colour_ideas_by_board(board)
# 1c extract colours into dictionary with weighting
data = dict()
if len(ideas) == 0:
add_colour_to_dictionary(data, '#ffffff') # add white if there are no colour tags
els... | [
"def find_in_board(x, y, board):\n item_list = [] # temp list\n for item in board: # go through each object in level\n if x == item[1] and y == item[2]: #if object matches the x and y coordinates\n item_list.append(item) #add the item to the temp list.\n\n return item_list #returns a list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sorts a given dictionary in descending order of value | def sort_dictionary_by_desc_value(dictionary):
return {k: v for k, v in sorted(dictionary.items(), key=lambda item: item[1], reverse=True)} | [
"def sort_by_value(d):\n return sorted(d.iteritems(), key=lambda (k, v): (v, k), reverse=True)",
"def sort_by_value(dct, reverse=True):\n return sorted(dct.items(), key=operator.itemgetter(1), reverse=reverse)",
"def sort_dictionary_descending(self):\r\n sorted_descending_dict = dict(sorted(self.ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
uses algorithm to add unique colours to dictionary or update weighting takes dictionary and colour | def add_colour_to_dictionary(dictionary, colour, initial_value=0.2):
if colour in dictionary:
"""Update value using equation ans * (0.8 + ((1 / ans) / 5))"""
value = dictionary.get(colour, None)
value = value * (0.8 + ((1 / value) / 5))
dictionary[colour] = value
else:
di... | [
"def _update_cmap(cmap: Dict, values: Dict) -> None:\n for i, color in values.items():\n if len(color) == 3:\n color += [255]\n cmap[i] = color",
"def greedy_coloring(self):\n vertex_id_color = {}\n\n # TODO: Fill in the dictionary by visiting each vertex and checking the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve, update or delete win. | def win_detail(request, pk):
try:
win = Win.objects.get(pk=pk)
if win.owner != request.user:
return Response(status=status.HTTP_403_FORBIDDEN)
except Win.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WinS... | [
"def window(args):\n uid = args.get(\"win\", get_new_window_id())\n version = args.get(\"version\", 1)\n if uid is None:\n uid = get_new_window_id()\n opts = args.get(\"opts\", {})\n\n ptype = args[\"data\"][0][\"type\"]\n\n p = {\n \"command\": \"window\",\n \"version\": vers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve, update or delete goal. | def goal_detail(request, pk):
try:
goal = Goal.objects.get(pk=pk)
if goal.owner != request.user:
return Response(status=status.HTTP_403_FORBIDDEN)
except Goal.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer =... | [
"def get_one(self, goal):\n if self.from_goals:\n raise exception.OperationNotPermitted\n\n context = pecan.request.context\n rpc_goal = api_utils.get_resource('Goal', goal)\n policy.enforce(context, 'goal:get', rpc_goal, action='goal:get')\n\n return Goal.convert_with_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cls._rest_search_columns = [cls.name, cls.description] list of columns for search filtering | def rest_get_list(cls, query_params):
def apply_search(query):
search_columns = getattr(cls, '_rest_search_columns', None)
if not search_columns or not 'search' in query_params:
return query
search = query_params['search'].lower()
if len(search_... | [
"def list_search_fields(self):",
"def filter_by_search_fields(self, search_fields, operator='and'):\n where_clause, parameters = self._build_where_clause(search_fields, operator=operator)\n sql = f'select * from {self.get_table()} where {where_clause}'\n cursor = self._execute(sql, parameters... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
There's a better timing function available in Python 3.3+ Otherwise use the old one. | def timing_function():
if sys.version_info[0] >= 3 and sys.version_info[1] >= 3:
return time.monotonic()
else:
return time.time() | [
"def timing(func, *args, **kw):\r\n return timings_out(1, func, *args, **kw)[0]",
"def clock2():\r\n return time.clock(), 0.0",
"def time(state):",
"def secondSinceStart():\n elapsed = time.time() - timer\n if hasattr(config,'hardwareSpeedup'):\n speed = config.hardwareSpeedup\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prompt for the file to output data into | def prompt_for_output_file(original_file_name):
print 'Origin file: {}'.format(original_file_name)
choice = io.binary_choice('Output file (s)ame/(n)ew file? ', 's', 'n')
if choice == 'n':
new_file_name = io.get_and_confirm_input('New file name: ')
return new_file_name
return original_fil... | [
"def prompt_file():\n data_file = input(\"Please enter the data file: \")\n print()\n return data_file",
"def prompt_filepath():\n file_path = input('Please enter the data file: ')\n return file_path",
"def assign_output_file(self):\r\n\t\t#Makes sure that the user has provided a text file that w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads numerical values from a file a displays them to a user. | def read_file(file_path):
numbers = io.read_numbers_from_file(file_path)
for each in numbers:
print each | [
"def _numerical_value(filename):\n return int(filename[:filename.index('.')])",
"def read_ints(file_name):\n with open(file_name) as f:\n return [int(x) for x in f.readlines()]",
"def parse_nrg(file):\n nrg = 0.0\n for line in open(file,'r'):\n split = line.rstrip().split('\\t')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" an interface for update params | def update_params(self) -> None: | [
"def _param_updated(self, name, value):\n\n logger.debug(\"Updated {0} to {1}\".format(name, value))",
"def update_params(self, params):\n updated_params = {}\n for arg, value in params.items():\n # ThreatConnect secure/AOT params could be updated in the future to proper JSON forma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a deepcopy of dict, then del dict[key] if exist. | def remove_key(dic, key):
dict_copy = deepcopy(dic)
if key in dict_copy:
del dict_copy[key]
return dict_copy | [
"def safe_delete(mydict, key):\n if key in mydict:\n del(mydict[key])\n\n return mydict",
"def create_deepcopy(old_dict):\n new_dict = {}\n for key in old_dict:\n try:\n new_dict[key] = copy.deepcopy(old_dict[key])\n except TypeError: # the item its self is a dict\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
finds and opens a seek thermal camera | def find_camera(self):
# get available camera
#try:
self.cam_api.find_cam()
#except :# PySeekError:
# rospy.logerr("No camera found")
# return False
rospy.loginfo("Found camera")
return True | [
"def open(self): #opens the camera and returns the handle\n if not self.isOpen: \n a = self.call(lib.OpenCamera, self.name, lib.Handle())\n self.isOpen = True\n #self.call(lib.SetStreaming, a[1], 1)\n return a[1]",
"def viewHeadOn(camera):\n pass",
"def came... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
publishes thermal images at thermalview | def pub_thermalview(self):
# publisher setup
pub = rospy.Publisher('thermalview/compressed', CompressedImage, queue_size=10)
rospy.loginfo("Beginning thermalview")
img_msg = CompressedImage() # message to publish
while not rospy.is_shutdown():
... | [
"def publish(self):\n if topic_visualization == '/robot/xdisplay':\n xsize = (1024, 600)\n if any([(a > b) for a, b in zip(self.img.shape[:2], xsize)]):\n self.img = cv2.resize(src=self.img, dsize=xsize)\n self.pub.publish(img_to_imgmsg(img=self.img))",
"def send... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns an array of URLs from the google results for a search string | def google_results_urls(search_term, number_results, language_code, site):
# make sure the inputs have the right types
assert isinstance(search_term, str), 'Search term must be a string'
assert isinstance(number_results, int), 'Number of results must be an integer'
assert isinstance(site, str), 'Site must be a stri... | [
"def google_search(search_term, num_results=1):\r\n results = []\r\n for url in googlesearch.search(search_term, start=1, stop=1+num_results, num=1):\r\n results.append(url)\r\n return results",
"def scrape_google(dom):\n results = []\n filtered = []\n searches = [\"100\", \"200\", \"300\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
grab the text content of each link in an array, then spit out a new array that contains strings with the text of each link | def get_text(search_result_links, sleep_time):
output = []
# grab the contents of each link
def get_results(search_result_links, sleep_time=30):
results = []
for l in search_result_links:
results.append(requests.get(l, headers=USER_AGENT))
# wait N seconds then scrape next link
time.sleep(sleep_time)
... | [
"def extract_links(text):\n if not text: # handle None\n return []\n return uniquify(match.group() for match in _LINK_RE.finditer(text))",
"def get_links(self, text_html: str, text: str) -> List[Dict[str, str]]:\n soup = BeautifulSoup(text_html, 'html.parser')\n hrefs = [(href.text, href['href... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add processors in a uniform format to the chain | def _add_processors(self, processors: [Tuple[callable, dict], callable]):
for element in processors:
if type(element) == tuple:
processor, params = element
else:
processor = element
params = {}
self.processors.append((processor... | [
"def register_processors(self) -> None:\n self.add_processor(RStudioServerCodeProcessor())\n self.add_processor(GenericFileChangeProcessor())\n self.add_processor(RStudioServerPlaintextProcessor())\n self.add_processor(RStudioServerImageExtractorProcessor())\n self.add_processor(A... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Publish a frame to PubSub | def _publish(self, channel: str, image: np.ndarray):
self.pubsub.publish(channel, Frame.from_cv2_bgr(image).to_bytes()) | [
"def publish_img(self, side: str) -> None:\n b, img = self.cap[side].read()\n if not b:\n self.logger.warning('Failed to grab frame!')\n return\n img = np.rot90(img, self.rot[side])\n img_msg = self.bridge.cv2_to_compressed_imgmsg(img)\n self.publisher[side].... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Periodically publish last processed frame | def _publish_loop(self):
while True:
with self.image_lock:
for channel in self.image_cache:
self._publish(channel, self.image_cache[channel])
time.sleep(Processor.FRAME_DELAY) | [
"def frame_callback(self, frame):\n # Publish at the reduced rate.\n if not self.count % self.period:\n self.image_publisher.publish(frame)\n self.count += 1",
"def process_frames_from_stream(self):\n while True:\n logging.debug('Checking Frame')\n fram... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |