query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Get the inputs to this recipe.
def get_recipe_inputs(self): return self.recipe_settings.get('inputs')
[ "def inputs(self):\n return self.node.inputs", "def __inputs__(self):\n\n if self.project_level:\n return []\n\n workflow_metadata = self.__metadata__()\n input_fields = self.optimus_input_fields if self.pipeline_type.lower() == \"optimus\" else self.ss2_input_fields\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the outputs of this recipe.
def get_recipe_outputs(self): return self.recipe_settings.get('outputs')
[ "def get(cls) -> typing.List[Output]:\n return cls._outputs", "def outputs(self) -> List[Node]:\n return self._outputs", "def get_outputs(self):\r\n return []", "def get_outputs(self):\n while True:\n try:\n yield self.get_output()\n except ValueErr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The "payload" of the recipe, parsed from JSON.
def get_json_payload(self): self._payload_to_obj() return self._obj_payload
[ "def _get_post_data(self):\n last_request = httpretty.last_request()\n return json.loads(last_request.body)", "def get_payload(self) -> bytes:\n return self.payload", "def serialised_payload(self, payload):\n return json.dumps(payload)", "def extract_body(payload):\n if isinstan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether a ref is part of the recipe's inputs.
def has_input(self, input_ref): inputs = self.get_recipe_inputs() for (input_role_name, input_role) in inputs.items(): for item in input_role.get("items", []): if item.get("ref", None) == input_ref: return True return False
[ "def HasREF(self):\n return self.__has('REF')", "def are_all_inputs_in_use(self, inputs_in_use: set, inputs_in_section: set) -> bool:\n\n inputs_not_in_use = inputs_in_section.difference(inputs_in_use)\n\n if inputs_not_in_use:\n playbook_name = self.current_file.get(\"name\", \"\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether a ref is part of the recipe's outputs.
def has_output(self, output_ref): outputs = self.get_recipe_outputs() for (output_role_name, output_role) in outputs.items(): for item in output_role.get("items", []): if item.get("ref", None) == output_ref: return True return False
[ "def HasREF(self):\n return self.__has('REF')", "def is_output_decorated(obj: object) -> bool:\n return hasattr(obj, \"__checked_output_specs__\")", "def has_output(self) -> bool:\n return len(self.pseudo_stdout) > 0", "def _check_evaled(self, refs):\n bools = []\n for ref in refs:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces an input of this recipe by another. If the current_input_ref isn't part of the recipe's inputs, this method has no effect.
def replace_input(self, current_input_ref, new_input_ref): inputs = self.get_recipe_inputs() for (input_role_name, input_role) in inputs.items(): for item in input_role.get("items", []): if item.get("ref", None) == current_input_ref: item["ref"] = new_inpu...
[ "def refresh_input(self, new_input):\n \n if(len(new_input) != len(self.layers[INPUT])):\n raise ValueError(\"Attempted to refresh input layer with the wrong number of values.\")\n\n for (i, node) in self.layers[INPUT]:\n self.layers[INPUT][i] = input_node(new_input[i])", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces an output of this recipe by another. If the current_output_ref isn't part of the recipe's outputs, this method has no effect.
def replace_output(self, current_output_ref, new_output_ref): outputs = self.get_recipe_outputs() for (output_role_name, output_role) in outputs.items(): for item in output_role.get("items", []): if item.get("ref", None) == current_output_ref: item["ref"] ...
[ "def _add_output(self, out):\n self._outputs += [out]\n out.node = self\n out._set_as_output_of(self)", "def replace_input(self, current_input_ref, new_input_ref):\n inputs = self.get_recipe_inputs()\n for (input_role_name, input_role) in inputs.items():\n for item in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an input to the recipe. For most recipes, there is only one role, named "main". Some few recipes have additional roles, like scoring recipes which have a "model" role. Check the roles known to the recipe with
def add_input(self, role, ref, partition_deps=None): if partition_deps is None: partition_deps = [] self._get_or_create_input_role(role)["items"].append({"ref": ref, "deps": partition_deps})
[ "def _add_roles():\n slab_logger.log(15, 'Determining Anisble roles')\n if not self.interactive:\n self.play_roles.append(str(self.name))\n return\n\n if not self.play_roles:\n while True:\n role = click.prompt(\"role\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an output to the recipe. For most recipes, there is only one role, named "main". Some few recipes have additional roles, like evaluation recipes which have a "metrics" role. Check the roles known to the recipe with
def add_output(self, role, ref, append_mode=False): self._get_or_create_output_role(role)["items"].append({"ref": ref, "appendMode": append_mode})
[ "def _add_roles():\n slab_logger.log(15, 'Determining Anisble roles')\n if not self.interactive:\n self.play_roles.append(str(self.name))\n return\n\n if not self.play_roles:\n while True:\n role = click.prompt(\"role\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all input refs of this recipe, regardless of the input role.
def get_flat_input_refs(self): ret = [] for role_key, role_obj in self.get_recipe_inputs().items(): for item in role_obj["items"]: ret.append(item["ref"]) return ret
[ "def list_input_artifacts(\n self) -> List[materialized_artifact.MaterializedArtifact]:\n return list(self.inputs.values())", "def inputs(self) -> List[Node]:\n return self._inputs", "def get_recipe_inputs(self):\n return self.recipe_settings.get('inputs')", "def inputs(self):\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all output refs of this recipe, regardless of the input role.
def get_flat_output_refs(self): ret = [] for role_key, role_obj in self.get_recipe_outputs().items(): for item in role_obj["items"]: ret.append(item["ref"]) return ret
[ "def list_output_artifacts(\n self) -> List[materialized_artifact.MaterializedArtifact]:\n return list(self.outputs.values())", "def outputs(self) -> List[Node]:\n return self._outputs", "def get_outputs(self):\r\n return []", "def cls_list_outputs(cls):\n return [k for k, v in cls.__clas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the name of the recipetobecreated.
def set_name(self, name): self.recipe_proto["name"] = name
[ "def set_name(self, new_name):\n self.name = new_name", "def set_name_item(self, item_name):\n self.name_item = item_name", "def set_name(self, new_name):\n\n self.img.attrib['Name'] = new_name", "def setName(self, name):\n self.setAttribute('NAME', name)", "def recipe_names(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the new recipe in the project, and return a handle to interact with it.
def create(self): self._finish_creation_settings() return self.project.create_recipe(self.recipe_proto, self.creation_settings)
[ "def create(self, recipe_name: str):\n recipe = self.recipes.get(recipe_name)\n if recipe is None:\n raise BuildException(f\"No recipe for {recipe_name}\")\n if not self.inventory.subtract(recipe.ingridients):\n raise BuildException(f\"No resources for recipe {recipe}\")\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activate raw creation mode.
def set_raw_mode(self): self.creation_settings["rawCreation"] = True
[ "def creation_mode(self):\n ret = self._get_attr(\"creationMode\")\n return ret", "def create(self):\n ret = self._get_attr(\"create\")\n return ret", "def createTrueCryptVolume(self, mode=\"VeraCrypt\"):\n if mode == \"VeraCrypt\":\n self.truecrypt = truecrypthelpe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear all grouping keys.
def clear_grouping_keys(self): self.obj_payload["keys"] = []
[ "def clearAllKeys(self):\n self._overlay = {}\n self.setBaseColor(self._basecolor)", "def ClearFlags(self):\n self.flag_groups = defaultdict(list)\n self.flags = {}", "def clear_all(self):\n data = self.Entries\n del data[:]", "def Clear(self, *args):\n return _Graphic3d.Graph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds grouping on a column.
def add_grouping_key(self, column): self.obj_payload["keys"].append({"column":column})
[ "def add_groupby(self):\n if self.query_model.groupBy_columns is not None and len(self.query_model.groupBy_columns) > 0:\n groupby_clause = \" GROUP BY \"\n for col_name in self.query_model.groupBy_columns:\n groupby_clause += \"?\" + col_name + \" \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the basic aggregations on a column.
def set_column_aggregations(self, column, type=None, min=False, max=False, count=False, count_distinct=False, sum=False,concat=False,stddev=False,avg=False): cs = self.get_or_create_column_settings(column) if type is not None: cs["type"] = type cs["min...
[ "def aggregation(data, column, group_list=[]):\n aggregation={\n column:\n {\n \"MIN\": lambda x: x.min(skipna=True),\n \"MAX\":lambda x: x.max(skipna=True),\n \"MEDIAN\":lambda x: x.median(skipna=True),\n \"MEAN\":lambda x:x....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the list of virtual inputs. This method returns a reference to the list of inputs, not a copy. Modifying the list
def raw_virtual_inputs(self): return self.obj_payload["virtualInputs"]
[ "def get_input_vec(self):\n return self.input_vec", "def inputs(self) -> List[Node]:\n return self._inputs", "def inputs(self):\n return self.node.inputs", "def getTransactionInputList(self) -> list:\n return self.__transactionInputList", "def update_model_input(self) -> List[Lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a virtual input pointing to the specified input dataset of the recipe.
def add_virtual_input(self, input_dataset_index): self.raw_virtual_inputs.append({"index": input_dataset_index})
[ "def add_input_arg(self, inp):\n self.add_arg(inp._dax_repr())\n self._add_input(inp)", "def make_input(self, *args, **kwargs):\r\n self.add(input.Input(*args, **kwargs))", "def add_input_opt(self, opt, inp):\n self.add_opt(opt, inp._dax_repr())\n self._add_input(inp)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a computed column to a virtual input.
def add_pre_join_computed_column(self, virtual_input_index, computed_column): self.raw_virtual_inputs[virtual_input_index]["computedColumns"].append(computed_column)
[ "def add_virtual_column(self, name, expression):\n\t\ttype = \"change\" if name in self.virtual_columns else \"add\"\n\t\tself.virtual_columns[name] = expression\n\t\tself.signal_column_changed.emit(self, name, \"add\")\n\t\tself.write_virtual_meta()", "def add_calculated_column(self, condition, on_column, new_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a join between two virtual inputs. The join is initialized with no condition.
def add_join(self, join_type="LEFT", input1=0, input2=1): jp = self.obj_payload if not "joins" in jp: jp["joins"] = [] join = { "conditionsMode": "AND", "on": [], "table1": input1, "table2": input2, "type": join_type ...
[ "def join(self, other):\n raise NotImplementedError(\"Joins are not implemented for cubical complexes.\")", "def join(leftkey, leftseq, rightkey, rightseq, left_default='__no__default__', right_default='__no__default__'): # real signature unknown; restored from __doc__\n pass", "def join(self, other):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a condition to a join.
def add_condition_to_join(self, join, type="EQ", column1=None, column2=None): cond = { "type" : type, "column1": {"name": column1, "table": join["table1"]}, "column2": {"name": column2, "table": join["table2"]}, } join["on"].append(cond) return cond
[ "def join_condition(join):\n name = join.alias_or_name\n on = (join.args.get(\"on\") or exp.true()).copy()\n source_key = []\n join_key = []\n\n def extract_condition(condition):\n left, right = condition.unnest_operands()\n left_tables = exp.column_table_names(left)\n right_tabl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a postjoin computed column.
def add_post_join_computed_column(self, computed_column): self.obj_payload["computedColumns"].append(computed_column)
[ "def add_calculated_column(self, condition, on_column, new_column_name):\n columns = self._inner_data.columns\n self._inner_data[new_column_name] = self._inner_data[on_column].map(eval('lambda x:' + condition))\n new_columns = columns.insert(self.max_x_column, new_column_name)\n self._in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a post filter on the join.
def set_post_filter(self, postfilter): self.obj_payload["postFilter"] = postfilter
[ "def add_filter(self,fltr):\n self.mutex.lock()\n self.filters.append(fltr)\n self.mutex.unlock()", "def filter_postings(self, pred):\r\n inset = frozenset(filter(pred, self.postings))\r\n if len(inset) == 0:\r\n logging.error(\"No postings selected by predicates.\")\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an unmatched join output
def set_unmatched_output(self, ref, side='right', append_mode=False): if side not in ['right', 'left']: raise ValueError("Unknown side : " + side) if len(self.obj_payload["joins"]) != 1: raise DataikuException("Unmatched output can only be set on recipe that have a single join") ...
[ "def _generate_join(self, join_op: Join):\n\n if not self.config.use_leaky_ops:\n template = open(\n \"{0}/join.tmpl\".format(self.template_directory), 'r').read()\n else:\n template = open(\n \"{0}/join_leaky.tmpl\".format(self.template_directory), ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the code env settings for this recipe.
def get_code_env_settings(self): rp = self.get_recipe_params() if not "envSelection" in rp: raise ValueError("This recipe kind does not seem to take a code env selection") return rp["envSelection"]
[ "def get_environment(py_src):\n env_src = \".\".join((os.path.splitext(py_src)[0], 'env', 'yml'))\n return read_configuration_file(env_src)", "def marker_environment(self) -> Dict[str, Any]:\n return get_pep508_environment(self.python_executable)", "def _get_env(self, config):\n for option, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set which code env this recipe uses. Exactly one of `code_env`, `inherit` or `use_builtin` must be passed.
def set_code_env(self, code_env=None, inherit=False, use_builtin=False): rp = self.get_recipe_params() if not "envSelection" in rp: raise ValueError("This recipe kind does not seem to take a code env selection") if code_env is not None: rp["envSelection"] = {"envMode": "...
[ "def set_env():\n from kolibri import dist as kolibri_dist # noqa\n\n monkey_patch_collections()\n\n monkey_patch_translation()\n\n sys.path = [os.path.realpath(os.path.dirname(kolibri_dist.__file__))] + sys.path\n\n # Add path for c extensions to sys.path\n prepend_cext_path(os.path.realpath(os....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new managed streaming endpoint as output to the recipetobecreated. The streaming endpoint is created immediately.
def with_new_output_streaming_endpoint(self, name, connection, format=None, overwrite=False, **kwargs): for k in kwargs: # for backward compat if k == "format_option_id": format = kwargs.get("format_option_id") else: raise Exception("Unknown argument '{}'...
[ "def create_stream(self, ):\n self.stream = self.p.open(format=self.format,\n channels=int(self.device['maxInputChannels']),\n rate=int(self.device['defaultSampleRate']),\n input=True,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the output model evaluation store.
def with_output_evaluation_store(self, mes_id): return self._with_output(mes_id, role="evaluationStore")
[ "def with_output_evaluation_store(self, mes_id):\n return self._with_output(mes_id, role=\"main\")", "def _set_eval(self):\n if self.opt.get('evaluation_report_file'):\n fname = self.opt['evaluation_report_file']\n else:\n # read in report made by `gen` mode\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the output model evaluation store.
def with_output_evaluation_store(self, mes_id): return self._with_output(mes_id, role="main")
[ "def with_output_evaluation_store(self, mes_id):\n return self._with_output(mes_id, role=\"evaluationStore\")", "def _set_eval(self):\n if self.opt.get('evaluation_report_file'):\n fname = self.opt['evaluation_report_file']\n else:\n # read in report made by `gen` mode\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the audio file into a format that can be handled by the transcribe function
def load_audio(self, path): pass
[ "def handle_audio(self, chat_id, file_id):\n\n self.bot.getFile(file_id)\n cur_dir = os.curdir\n for format in self.formats:\n path = os.path.join(cur_dir, \"audio\", str(chat_id) + \".\" + format)\n self.bot.download_file(file_id, path)\n\n self.bot.sendMessage(cha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update existence connection. Must contain 1 or more fields
def put(self, request): data = json.loads(request.body) for connection in self.get_connections_list(request): # TODO refactor this to loop by dict keys # + More generic solution # - Less readable code if data.get('id') == str(connection['id']): ...
[ "def update(self, conn: Conexao, comandoPersonalizado: ComandoPersonalizado):", "def update_accepted_connection(connection):\n\tconnection.visible = True\n\tconnection.created_at = timezone.now()\n\tconnection.save()", "def update_connection_with_http_info(self, connection_name, body, **kwargs):\n\n all_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Server object from archive. If the extract arguments is set to True, don't do the extraction.
def load_file(self, filename, extract=True): if filename is None: raise Exception("Filename is None") # Create Server object server = Server() if extract is False: # Folder is already uncompressed. Just initialize the dump dict self.logger.info("Do n...
[ "async def get_installer(self, archive, extract_dir=None):\n\n from skymodman.managers.installer import InstallManager\n\n # instantiate a new install manager\n installer = InstallManager(archive, mcp=self)\n\n\n if extract_dir is not None: # we're expecting a fomod\n\n # find...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read all or some bands from raster
def read_raster(path, band=None, block_size=1): if isinstance(band, int): return read_raster_band(path, band=band, block_size=block_size) else: if band is None: bands = range(1, get_band_count(path) + 1) else: bands = list(band) return da.stack([ ...
[ "def read_raster_band(path, band=1, block_size=1):\n\n def read_window(raster_path, window, band):\n with rasterio.open(raster_path) as src:\n return src.read(band, window=window)\n\n def resize_window(window, block_size):\n return Window(\n col_off=window.col_off * block_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a raster band and return a Dask array
def read_raster_band(path, band=1, block_size=1): def read_window(raster_path, window, band): with rasterio.open(raster_path) as src: return src.read(band, window=window) def resize_window(window, block_size): return Window( col_off=window.col_off * block_size, ...
[ "def read_raster(path, band=None, block_size=1):\n\n if isinstance(band, int):\n return read_raster_band(path, band=band, block_size=block_size)\n else:\n if band is None:\n bands = range(1, get_band_count(path) + 1)\n else:\n bands = list(band)\n return da.st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read raster band count
def get_band_count(raster_path): with rasterio.open(raster_path) as src: return src.count
[ "def bandCount(self):\n return self.dataset().RasterCount if self.dataset() is not None else 0", "def readbandsnum(basincod, cnxn, table, log_file):\r\n # queries the number of elevation bands of the basin\r\n sqlstr = 'SELECT COUNT(ID) FROM ' + table + ' WHERE IDBASIN = ?'\r\n curs = cnxn.cursor(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a dask array to a raster file If array is 2d, write array on band 1. If array is 3d, write data on each band
def write_raster(path, array, **kwargs): if len(array.shape) != 2 and len(array.shape) != 3: raise TypeError('invalid shape (must be either 2d or 3d)') if is_dask_collection(array): with RasterioDataset(path, 'w', **kwargs) as dst: da.store(array, dst, lock=True) else: w...
[ "def writeRaster(data, outpath_file, cols, rows, bands_num, geoTtansform, projection):\n\n # get band data type\n if bands_num == 1:\n data_tmp = data\n else:\n data_tmp = data[0, :, :]\n if 'int8' in data_tmp.dtype.name:\n datatype = gdal.GDT_Byte\n elif 'int16' in data_tmp.dtyp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fires up the relay process.
def run(self): # These form the connection to the Gateway daemon(s) upstream. context = zmq.Context() receiver = context.socket(zmq.SUB) receiver.setsockopt(zmq.SUBSCRIBE, '') for binding in Settings.RELAY_RECEIVER_BINDINGS: # Relays bind upstream to an Announcer, or...
[ "async def trigger_relay(self):\n self.relay_active = True\n GPIO.output(self.relay_output_pin, True)\n if self.verbosity > 1:\n print(f'{self.pin} starting relay on output pin {self.relay_output_pin}')\n\n await asyncio.sleep(self.relay_output_duration)\n\n GPIO.output...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a hierarchy of schema to try (merged/cached, config).
def merge_schemas(merge_cache: bool, config_schema: dict, cached_schema: dict) -> dict: if not merge_cache: _LOGGER.debug("A cached schema was not enabled (not recommended)") # cached_schema = {} # in case is None else: _LOGGER.debug("Loaded a cached schema: %s", cached_schema) if...
[ "def retrieve_model_parents_schema(schema: types.Schema) -> types.Schema:\n schemas = _retrieve_model_parents_schema(schema)\n schema = {\"allOf\": schemas}\n return all_of_helper.merge(schema=schema, schemas={})", "def schema(self):\n subschemas = (self.types[name].schema for name in self.subtype...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the path of the log and err file for the step corresponding to basename
def compute_reg_log_file_paths(self, basename): log_file_template = os.path.join(self.niftyreg_directory, "{}.log") error_file_template = os.path.join(self.niftyreg_directory, "{}.err") log_file_path = log_file_template.format(basename) error_file_path = error_file_template.format(basen...
[ "def error_file(self):\n h = self._get_builtin_handler(self.error_log, 'file')\n if h:\n return h.baseFilename\n return ''", "def get_completed_step_evaluation_file(self, step_name: str, basename: str):", "def _log_filename(self):\n #return self.config['logging']['filename...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtain a transformation from vol voxels > Freesurfer surf coords.
def vol_to_surf_xfm(vol_fname, reg_fname): # Load the Freesurfer "tkreg" style transform file # Confusingly, this file actually encodes the anat-to-func transform anat2func_xfm = np.genfromtxt(reg_fname, skip_header=4, skip_footer=1) func2anat_xfm = np.linalg.inv(anat2func_xfm) # Get a tkreg-compat...
[ "def compute_vertex_transform( node ):\r\n\r\n\t# Get the \"geometric\" transformation.\r\n\tgeometric_translation = FbxCommon.FbxVector4( )\r\n\tgeometric_rotation = FbxCommon.FbxVector4( )\r\n\tgeometric_scale = FbxCommon.FbxVector4( )\r\n\tgeometric_transform_fbx = FbxCommon.FbxMatrix( )\r\n\r\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to capture all the attributes of any element.
def gather_all_attributes_for_element(driver, element): return driver.execute_script( ''' var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items; ''', element...
[ "def attributes(self):\n # \"\"\" Returns a List of an element's attributes \"\"\"\n # try:\n # return [Attr(key.lstrip('_'), value) for key, value in self.kwargs.items()]\n # except Exception as e:\n # print('Error - no tag!', e)\n # return []\n # print(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns first cyrilic alternate name
def get_first_cyrilic_alternate_name(self): if not self.alternate_names: return None for name in self.alternate_names.split(','): if re.match(r'[А-яа-я\-\s]{2,}', name): return name return None
[ "def FirstName(self):\n return self.all_common_names[0]", "def firstName(self):\n others = self._otherNames.split()\n return others[0]", "def formatNameWithExtinct(name):\n\textinct = False\n\n\t# Extinct species.\n\tif \"†\" in name:\n\t\textinct = True\n\t\tname = name.replace(\"†\", \"\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
emitter function for SCons Builders, injected into the existing Object / SharedObject builders in the environment, to include and load the new dependency file with the object
def gcc_dep_emitter(target, source, env): getBool = base.BindCallArguments(base.getBool, target, source, env, lambda x: x) getString = base.BindCallArguments(base.getString, target, source, env, None) getList = base.BindCallArguments(base.getList, target, source, env, False) if len(target...
[ "def add_dependency(self, dataset):\n self.defFile.add_dependency(dataset)", "def task_mybinder():\n\n def action(targets):\n for filename in targets:\n with open(filename) as f:\n content = f.read()\n content = re.sub('cytoscape(?P<cmp>[^0-9]*)([0-9\\.].*)', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find unique named SAGA hosts in allspec. Sort names by nsats
def sort_saga_hosts(sagaspec): # FIND UNIQUE SAGA NAMES and CALCULATE NSATS unique_hosts = [] nsats = [] for s in sagaspec: if s['HOST_SAGA_NAME'] not in unique_hosts: unique_hosts.append(s['HOST_SAGA_NAME']) # CALCULATE NSATS FOR GIVEN HOST msk1 = sagaspec['HOST_SAGA_NAME'] == s['HOST_SAGA_N...
[ "def get_hostnames(self):\n hosts = set()\n for entry in self._config:\n hosts.update(entry['host'])\n return hosts", "def hosts_lists_parse(prefix, all_hosts):\n if prefix == 29:\n return [\n all_hosts[0:2], all_hosts[2:4], all_hosts[4:6]\n ]\n elif ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the fingerprint of a key.
def get_fingerprint(entirekey): t, keystring, comment = entirekey.split(" ", 2) return key_fingerprint(keystring)
[ "def fingerprint(self):\n public_key = self.key.publickey().exportKey('DER')\n return SHA256.new(public_key).hexdigest()", "def calculate_public_key_fingerprint(self, private_key: Any) -> str:\n # Get the raw bytes of public key.\n public_key_raw = private_key.public_key().public_bytes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the formatter and handler for logger.
def set_up_logger(self): self.config.logger.handlers.clear() self.config.logger.propagate = False ch = logging.StreamHandler() ch.setLevel(self.config.logging_level) # create formatter and add it to the handlers formatter = logging.Formatter('%(message)s') ch.setF...
[ "def setup_logger():\n formatter = ColoredFormatter(\n \"%(asctime)s.%(msecs)03d (%(threadName)-9s) %(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s\", # NOQA\n datefmt='%Y-%m-%d,%H:%M:%S',\n reset=True,\n log_colors={\n 'DEBUG': 'cyan',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the dual integral.
def get_dual_integral(self): dual_integral = 0 dual_bound_progress = self.dual_bound_progress.copy() # Initial dual bound is set to inf or -inf. To calculate dual integral, we set # initial_dual_bound to 10% greater or smaller than the first_found_dual_bound. # TODO: check if the...
[ "def integral(x):\n\n t = x - 1.0\n return t - (sqrt(1.0 - t ** 2) * t + asin(t)) / 2.0", "def dual(self):\n x = self.I\n return self * x * x * x", "def integral(self,time0,time1):\n return self.value*(time1-time0)", "def dual_basis(self):\n return self.realizatio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the primal integral.
def get_primal_integral(self): primal_integral = 0 primal_bound_progress = self.primal_bound_progress.copy() # Initial primal bound is set to inf or -inf. To calculate primal integral, we set # initial_primal_bound to 10% greater or smaller than the first_found_primal_bound. # TO...
[ "def integral(x):\n\n t = x - 1.0\n return t - (sqrt(1.0 - t ** 2) * t + asin(t)) / 2.0", "def g_prime(x: float) -> float:\r\n \r\n return 4*x**3 + 6*x**2 - 8*x - 8", "def summation_of_primes():\n\tresult = 0\n\tn = 2000000\n\t# n = 10\n\tfor i in range(n):\n\t\tif Helpers.is_prime(i):\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the relative gap and the absolute gap.
def update_gap(self): if self.objective_sense == minimize: self.abs_gap = self.primal_bound - self.dual_bound else: self.abs_gap = self.dual_bound - self.primal_bound self.rel_gap = self.abs_gap / (abs(self.primal_bound) + 1e-10)
[ "def gap(self) -> float:\n pass", "def updateGaps(self, gaps):\n for index, gap in enumerate(gaps):\n if gap > self.total_gaps[index]:\n self.total_gaps[index] = gap", "def _inc_spawn_gap(self):\n if (self.state == Editor.State.wave and\n self.wave_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the dual bound. Call after solving relaxed problem, including relaxed NLP and MIP main problem. Use the optimal primal bound of the relaxed problem to update the dual bound.
def update_dual_bound(self, bound_value): if math.isnan(bound_value): return if self.objective_sense == minimize: self.dual_bound = max(bound_value, self.dual_bound) self.dual_bound_improved = self.dual_bound > self.dual_bound_progress[-1] else: se...
[ "def update_suboptimal_dual_bound(self, results):\n if self.objective_sense == minimize:\n bound_value = results.problem.lower_bound\n else:\n bound_value = results.problem.upper_bound\n self.update_dual_bound(bound_value)", "def fix_dual_bound(self, config, last_iter_cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the relaxed problem is not solved to optimality, the dual bound is updated according to the dual bound of relaxed problem.
def update_suboptimal_dual_bound(self, results): if self.objective_sense == minimize: bound_value = results.problem.lower_bound else: bound_value = results.problem.upper_bound self.update_dual_bound(bound_value)
[ "def update_dual_bound(self, bound_value):\n if math.isnan(bound_value):\n return\n if self.objective_sense == minimize:\n self.dual_bound = max(bound_value, self.dual_bound)\n self.dual_bound_improved = self.dual_bound > self.dual_bound_progress[-1]\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the primal bound. Call after solve fixed NLP subproblem. Use the optimal primal bound of the relaxed problem to update the dual bound.
def update_primal_bound(self, bound_value): if math.isnan(bound_value): return if self.objective_sense == minimize: self.primal_bound = min(bound_value, self.primal_bound) self.primal_bound_improved = ( self.primal_bound < self.primal_bound_progress[-1...
[ "def update_suboptimal_dual_bound(self, results):\n if self.objective_sense == minimize:\n bound_value = results.problem.lower_bound\n else:\n bound_value = results.problem.upper_bound\n self.update_dual_bound(bound_value)", "def fix_dual_bound(self, config, last_iter_cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process model objective function. Check that the model has only 1 valid objective. If the objective is nonlinear, move it into the constraints. If no objective function exists, emit a warning and create a dummy objective.
def process_objective( self, config, move_objective=False, use_mcpp=False, update_var_con_list=True, partition_nonlinear_terms=True, obj_handleable_polynomial_degree={0, 1}, constr_handleable_polynomial_degree={0, 1}, ): m = self.working_model ...
[ "def add_objective_function(self, objective_function):\n objective_function = objective_function.sort_values('variable_id')\n objective_function = objective_function.set_index('variable_id')\n obj = minimize(xsum(objective_function['cost'][i] * self.variables[i] for i in\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the solve data.
def set_up_solve_data(self, model, config): # if the objective function is a constant, dual bound constraint is not added. obj = next(model.component_data_objects(ctype=Objective, active=True)) if obj.expr.polynomial_degree() == 0: config.logger.info( 'The model has a...
[ "def solve(self):\n self.freezeInitialValues()\n solved = self.solve_puzzle(self.serialize())", "def _set_up_model(self) -> None:\n self._add_vars_x_i_in_theta_i()\n self._add_vars_z_i()\n self._add_linear_cons()\n self._add_objective()", "def set_up_mip_solver(solve_da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the problem by solving the relaxed NLP and then store the optimal variable values obtained from solving the rNLP.
def init_rNLP(self, config, add_oa_cuts=True): m = self.working_model.clone() config.logger.debug('Relaxed NLP: Solve relaxed integrality') MindtPy = m.MindtPy_utils TransformationFactory('core.relax_integer_vars').apply_to(m) nlp_args = dict(config.nlp_solver_args) nlpop...
[ "def Initialize(self):\n\n NLPd = self.NLPdata\n NSENS = self.NEQ if self.NLPdata['PRC'] else 0\n \n if type(self.NLPdata['XMAX']) is np.ndarray: self.NLPdata['XMAX'] = self.NLPdata['XMAX'].tolist()\n if type(self.NLPdata['XMIN']) is np.ndarray: self.NLPdata['XMIN'] = self.NLP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modifies model by maximizing the number of activated binary variables. Note The user would usually want to call solve_subproblem after an invocation of this function.
def init_max_binaries(self, config): m = self.working_model.clone() if config.calculate_dual_at_solution: m.dual.deactivate() MindtPy = m.MindtPy_utils self.mip_subiter += 1 config.logger.debug('Initialization: maximize value of binaries') for c in MindtPy.non...
[ "def maximize(self):\n return Problem(-self.objective, self.constraints).minimize()", "def SubProblem(SubProblemObjectiveIndices,\r\n SubProblemVariablesIndices,\r\n #Bounds,\r\n lb,\r\n ub,\r\n FixedIndices,\r\n FixedValue...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves feasibility problem and adds cut according to the specified strategy. This function handles the result of the latest iteration of solving the NLP subproblem given an infeasible solution and copies the solution of the feasibility problem to the working model.
def handle_subproblem_infeasible(self, fixed_nlp, config, cb_opt=None): # TODO try something else? Reinitialize with different initial # value? config.logger.info('NLP subproblem was locally infeasible.') self.nlp_infeasible_counter += 1 if config.calculate_dual_at_solution: ...
[ "def solve_fp_subproblem(self, config):\n fp_nlp = self.working_model.clone()\n MindtPy = fp_nlp.MindtPy_utils\n\n # Set up NLP\n fp_nlp.MindtPy_utils.objective_list[-1].deactivate()\n if self.objective_sense == minimize:\n fp_nlp.improving_objective_cut = Constraint(\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the algorithm should terminate at the given point. This function determines whether the algorithm should terminate based on the solver options and progress. (Sets the self.results.solver.termination_condition to the appropriate condition, i.e. optimal, maxIterations, maxTimeLimit).
def algorithm_should_terminate(self, config, check_cycling): if self.should_terminate: # self.primal_bound_progress[0] can only be inf or -inf. # If the current primal bound equals inf or -inf, we can infer there is no solution. if self.primal_bound == self.primal_bound_progr...
[ "def check_termination(self):\n all_samples = self.sample_dataframe\n if (all_samples is not None) and (len(all_samples) > max_samples):\n logger.debug(f\"[session_id]:Termination condition is met due to enough number of samples = {len(df)}\")\n return True\n\n if not self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fix the dual bound when nogood cuts or tabu list is activated.
def fix_dual_bound(self, config, last_iter_cuts): # If no-good cuts or tabu list is activated, the dual bound is not valid for the final optimal solution. # Therefore, we need to correct it at the end. # In singletree implementation, the dual bound at one iteration before the optimal solution, i...
[ "def update_dual_bound(self, bound_value):\n if math.isnan(bound_value):\n return\n if self.objective_sense == minimize:\n self.dual_bound = max(bound_value, self.dual_bound)\n self.dual_bound_improved = self.dual_bound > self.dual_bound_progress[-1]\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the tabulist using IncumbentCallback
def set_up_tabulist_callback(self, mainopt): tabulist = mainopt._solver_model.register_callback( tabu_list.IncumbentCallback_cplex ) self.solve_data = MindtPySolveData() self.export_attributes() tabulist.solve_data = self.solve_data tabulist.opt = mainopt ...
[ "def __init__(self, *args, **kwargs):\n _aui.PyAuiTabArt_swiginit(self,_aui.new_PyAuiTabArt(*args, **kwargs))\n PyAuiTabArt._setCallbackInfo(self, self, PyAuiTabArt)", "def _init_tabs(self):\n\n # Loop over number of DUTs and create tmp setup and options for each DUT\n for i in range(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the lazy OA using LazyConstraintCallback
def set_up_lazy_OA_callback(self, mainopt): if self.config.mip_solver == 'cplex_persistent': lazyoa = mainopt._solver_model.register_callback( single_tree.LazyOACallback_cplex ) # pass necessary data and parameters to lazyoa lazyoa.main_mip = self....
[ "def patchLazy():\n Lazy._solr_original__add__ = Lazy.__add__\n Lazy.__add__ = lazyAdd\n if HAS_EXPCAT:\n lazy.Lazy._solr_original__add__ = lazy.Lazy.__add__\n lazy.Lazy.__add__ = lazyExpCatAdd", "def _init_objective(self) -> None:\n raise NotImplementedError(\"You should implement t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function solves the MIP main problem.
def solve_main(self, config): self.mip_iter += 1 # setup main problem self.setup_main(config) mainopt, mip_args = self.set_up_mip_solver(config) try: main_mip_results = mainopt.solve( self.mip, tee=config.mip_solver_tee, load_solutions=False, **mip_a...
[ "def handle_main_optimal(main_mip, solve_data, config, update_bound=True):\n # proceed. Just need integer values\n MindtPy = main_mip.MindtPy_utils\n # check if the value of binary variable is valid\n for var in MindtPy.discrete_variable_list:\n if var.value is None:\n config.logger.wa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the MIP solver.
def set_up_mip_solver(self, config, regularization_problem=False): # Deactivate extraneous IMPORT/EXPORT suffixes if config.nlp_solver in {'ipopt', 'cyipopt'}: getattr(self.mip, 'ipopt_zL_out', _DoNothing()).deactivate() getattr(self.mip, 'ipopt_zU_out', _DoNothing()).deactivate(...
[ "def set_up_mip_solver(solve_data, config, regularization_problem):\n # Deactivate extraneous IMPORT/EXPORT suffixes\n if config.nlp_solver in {'ipopt', 'cyipopt'}:\n getattr(solve_data.mip, 'ipopt_zL_out', _DoNothing()).deactivate()\n getattr(solve_data.mip, 'ipopt_zU_out', _DoNothing()).deacti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the result of the regularization main problem.
def handle_regularization_main_tc(self, main_mip, main_mip_results, config): if main_mip_results is None: config.logger.info( 'Failed to solve the regularization problem.' 'The solution of the OA main problem will be adopted.' ) elif main_mip_resul...
[ "def handle_regularization_main_tc(main_mip, main_mip_results, solve_data, config):\n if main_mip_results is None:\n config.logger.info(\n 'Failed to solve the regularization problem.'\n 'The solution of the OA main problem will be adopted.'\n )\n elif main_mip_results.solv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up main problem/main regularization problem for OA, ECP, Feasibility Pump and ROA methods.
def setup_regularization_main(self, config): MindtPy = self.mip.MindtPy_utils for c in MindtPy.constraint_list: if c.body.polynomial_degree() not in self.mip_constraint_polynomial_degree: c.deactivate() MindtPy.cuts.activate() sign_adjust = 1 if self.object...
[ "def setup_main(solve_data, config, fp, regularization_problem):\n MindtPy = solve_data.mip.MindtPy_utils\n\n for c in MindtPy.constraint_list:\n if (\n c.body.polynomial_degree()\n not in solve_data.mip_constraint_polynomial_degree\n ):\n c.deactivate()\n\n M...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves the feasibility pump NLP subproblem. This function sets up the 'fp_nlp' by relax integer variables. precomputes dual values, deactivates trivial constraints, and then solves NLP model.
def solve_fp_subproblem(self, config): fp_nlp = self.working_model.clone() MindtPy = fp_nlp.MindtPy_utils # Set up NLP fp_nlp.MindtPy_utils.objective_list[-1].deactivate() if self.objective_sense == minimize: fp_nlp.improving_objective_cut = Constraint( ...
[ "def solve_NLP_feas(solve_data, config):\n fixed_nlp = solve_data.working_model.clone()\n add_feas_slacks(fixed_nlp, config)\n MindtPy = fixed_nlp.MindtPy_utils\n next(fixed_nlp.component_data_objects(Objective, active=True)).deactivate()\n for constr in fixed_nlp.component_data_objects(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Feasibility pump loop. This is the outermost function for the Feasibility Pump algorithm in this package; this function controls the progression of solving the model.
def fp_loop(self, config): while self.fp_iter < config.fp_iteration_limit: # solve MILP main problem with time_code(self.timing, 'fp main'): fp_main, fp_main_results = self.solve_fp_main(config) fp_should_terminate = self.handle_fp_main_tc(fp_main_results, con...
[ "def go(self):\n self.check()\n self.domain.create_dofs()\n self.domain.set_dof_numbering()\n self.domain.create_material_statuses()\n self.solve(self)\n\n # loop time steps, for now only 1 step", "def main(self):\n \n \"initialise UKF\"\n self.init_u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main loop for MindtPy Algorithms. This is the outermost function for the Outer Approximation algorithm in this package; this function controls the progression of solving the model.
def MindtPy_iteration_loop(self, config): while self.mip_iter < config.iteration_limit: # solve MILP main problem with time_code(self.timing, 'main'): main_mip, main_mip_results = self.solve_main(config) if self.handle_main_mip_termination(main_mip, main_mip_r...
[ "def _do_outer_iteration_stage(self, **kwargs):\n self.solve(**kwargs)", "def main_monte_carlo_integration_loop(self):\r\n self.end_point_dic = {} # dictionary will used to store the number of counts for each endpoint\r\n self.expected_val = np.inf # this intial state ensures that integrati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete all loss history data on nn_id
def delete_train_loss(nn_id): try: models.TrainResultLoss.objects.filter(nn_id=nn_id).delete() return nn_id except Exception as e: raise Exception(e)
[ "def delete_history(id, data_id):\n api = rest.PreprocessingApi(configuration.get_api_client())\n api.delete_preprocessing_history(id, data_id)\n print('deleted ', id, '.', data_id, sep='')", "def delete_valuehistory(self):\n from stats.models import ValueHistory\n ValueHistory.objects.filt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns list of videos in directory. If any file that you want to color has different ending add it to the list. Different files may not be supported for later colorization.
def get_video_list(dir_path): image_list = os.listdir(dir_path) ext = [".avi", ".mp4"] return [im for im in image_list if im.endswith(tuple(ext))]
[ "def list_videos():\n\n videos = [f for f in listdir(HOST_VIDEOS_DIR) if path.isfile(path.join(HOST_VIDEOS_DIR, f))]\n\n return videos", "def videos():\n result = []\n for filename in ('talks.yml', 'recommended.yml'):\n result.extend(video_links(load_yaml(filename)))\n return result", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function finds all videos to colorize and call colorization on each
def color_videos(model): # find videos videos = get_video_list(get_abs_path(source_dir)) for video in videos: color_one_video(model, video)
[ "def pivprocess(filename,colorcode,stopframe,pixperm,fps,numpysaveto,graphsaveto,startframe=0,contouralpha=0,vertvelmin=-10,vertvelmax=10,hozvelmin=0,hozvelmax=5):\n\n\n\n #####Import the video#####\n vc = cv2.VideoCapture(filename)\n c=1\n\n\n ######Get frames for use in the PIV#####\n\n if vc.isOpe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure keyboard for user's role
def keyboard(kb, role, user): orig_kbd = getattr(kbd_list, kb) kbd = copy.deepcopy(orig_kbd) # TODO: Role lists for flags (not sure is need or not) if kb == 'main': if role in [0, 1, 3, 5, 7]: pass else: # Hide control page kbd['buttons'].pop() eli...
[ "def set_user_role(data):\n g.is_editor = data == \"editor\"", "def _add_roles():\n slab_logger.log(15, 'Determining Anisble roles')\n if not self.interactive:\n self.play_roles.append(str(self.name))\n return\n\n if not self.play_roles:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change preference or battle push
def toggle(**kwargs): preference = kwargs['payload'] if preference != 'push': users.change_preference(kwargs['chat'], preference) msg = 'You have successfully changed preference' page(msg=kwargs['msg'], payload='settings', chat=kwargs['chat'], role_id=kwargs['role_id'], flag=msg) els...
[ "def preferencesChanged(self):\n self.update()", "def on_set_status(self, status, pokemon, setter, battle):", "def on_after_set_status(self, status, pokemon, setter, battle):", "def setuserpref():\n\n user = User.current()\n if user is None:\n # We must have a logged-in user\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts an integer 'a' and returns the value mod 'm' with values (0,m1)
def zmod(_a: int, _m: int) -> int: return _a % _m
[ "def mod(_a: int, _m: int) -> int:\n return zmod(_a - 1, _m) + 1", "def modinv(a, m):\n g, x, y = egcd(a % m, m)\n if g != 1:\n raise Exception('modular inverse does not exist')\n else:\n return x % m", "def modinv(a, m):\r\n g, x, y = egcd(a, m)\r\n if g != 1:\r\n raise E...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts an integer 'a' and returns the value mod 'm' with values (1,m)
def mod(_a: int, _m: int) -> int: return zmod(_a - 1, _m) + 1
[ "def zmod(_a: int, _m: int) -> int:\n return _a % _m", "def modinv(a, m):\n g, x, y = egcd(a % m, m)\n if g != 1:\n raise Exception('modular inverse does not exist')\n else:\n return x % m", "def modinv(a, m):\r\n g, x, y = egcd(a, m)\r\n if g != 1:\r\n raise Exception('mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we get the correct suffix for a given exponent
def test_get_suffix(): from .divider import get_suffix # less than milliohms assert get_suffix(-20) == '* 10^-20 Ohm' assert get_suffix(-4) == '* 10^-4 Ohm' # milliohms assert get_suffix(-3) == 'mOhm' assert get_suffix(-2) == 'mOhm' assert get_suffix(-1) == 'mOhm' # ohms asser...
[ "def test_suffix_hybrid(self):\n assert bl.format_suffix(True, \"SUFFIX\", True) == \"_RSUFFIX_CORE\"", "def testConvertionWithExponent(unit_database_custom_conversion) -> None:\n unit_database = unit_database_custom_conversion\n assert approx(abs(100 - unit_database.Convert(\"length\", [(\"m\", 1)],...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that we get the actual closest resistors in the series
def test_get_closest_in_series(): from .divider import get_closest_in_series, SERIES assert get_closest_in_series(6.7e-3, SERIES.get('E24')) == (6.8, -3) assert get_closest_in_series(4.4e-2, SERIES.get('E24')) == (4.3, -2) assert get_closest_in_series(1.2e-1, SERIES.get('E6')) == (1.0, -1) assert g...
[ "def test_closest():\n lst = [0, 2, 1, 3, 4, 5, 6]\n # val is equidistant to two values in list, first one in list is chosen\n assert closest(lst, 1.5) == 2, 'closest value is incorrect'\n assert closest(lst, 3.5) == 3, 'closest value is incorrect'\n # val is equal to one value in list\n assert cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulates all games in population
def play(self): tmp_pop = [] for being in self.population: tmp_game = being['start'].copy() iteration = 0 begin_count = np.sum(tmp_game) while True in tmp_game and iteration < self.iter_limit: tmp_game = self.life(tmp_game) ...
[ "def simulate_games(self, game):\n times = self.rollout_iterations\n progress = ProgressBar(times, \"Choosing move:\")\n for i in range(times):\n sim_game = game.copy()\n self.simulate_game(sim_game)\n progress.show(i)\n possibilities = self.tree.get_norm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will merge two games. For use in 'mating'
def merge(self):
[ "def merge(self, r1, r2) -> None:\n ...", "def merge(self, other):\n if self._word != other.word():\n print self.word(), other.word()\n raise RuntimeError(\"Word is not a match for merge.\")\n\n for pos in other.pos():\n self.add_pos(pos)", "def merge(cluste...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply a decorator to all methods of a Class, excluding `__init__`.
def for_all_methods(decorator): def decorate(cls): for attr in cls.__dict__: if callable(getattr(cls, attr)) and attr != '__init__': setattr(cls, attr, decorator(getattr(cls, attr))) return cls return decorate
[ "def for_all_methods(decorator):\n\n @wraps(decorator)\n def decorate(cls):\n # Examine all class attributes.\n for attr in cls.__dict__:\n # Check if each class attribute is a callable method.\n if callable(getattr(cls, attr)):\n # Set the callables to be de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
capture_id = identifier for the capture used to store the files (e.g. .cfile) store_capture = boolean indicating if the capture should be stored on disk or not rec_length = capture time in seconds max_timeslot = timeslot 0...max_timeslot will be decoded udp_ports = a list of udp ports to send the captured GSMTap frames...
def __init__(self, gain=None, samp_rate=None, ppm=None, arfcn=None, capture_id=None, udp_ports=[], max_timeslot=0, store_capture=True, verbose=False, band=None, rec_length=None, test=False, args=""): gr.top_block.__init__(self, "Gr-gsm Capture") ################################################## ...
[ "def capture(self):\n self.camera = self.ids['camera']\n timestr = time.strftime(\"%Y%m%d_%H%M%S\")\n self.camera.export_to_png(\"IMG_{}.png\".format(timestr))\n print(\"Captured\")", "def capture(all_servers, server_id='all'):\n if server_id != 'all':\n servers = [find_serve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stops scanning but keeps serial connection alive.\nReturn True on success\nReturn False in case of exception.
def StopScanning(self): try: if(self.__is_connected and self.__is_scanning): self.__is_scanning = False self.__s.write(b'\xA5\x65') time.sleep(0.5) self.__s.reset_input_buffer() self.__stop_motor() return...
[ "def stop_scan(self):\r\n try:\r\n out = self.get_output(\"scan off\")\r\n except BluetoothctlError, e:\r\n print(e)\r\n return None", "def stop(self):\n self.is_alive = False\n if(self.port in serials_in_use):\n serials_in_use.remove(self.po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the list of clients for the log.
async def _update_client_list(self) -> None: # add all clients to list self.listClients.clear() for client_name in self.comm.clients: # create item item = QtWidgets.QListWidgetItem(client_name) item.setCheckState(QtCore.Qt.Checked) item.setForegro...
[ "def update_client_list(self):\r\n\r\n windows = [wid for wid, c in self.windowMap.iteritems() if c.group]\r\n self.root.set_property(\"_NET_CLIENT_LIST\", windows)\r\n # TODO: check stack order\r\n self.root.set_property(\"_NET_CLIENT_LIST_STACKING\", windows)", "def get_client_list(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process a new log entry.
async def process_log_entry(self, entry: Event, sender: str) -> bool: if not isinstance(entry, LogEvent): return False # date time = Time(entry.time, format="unix") # define new row and emit row = [ time.iso.split()[1], str(sender), ...
[ "def create_log_entry(self, log_entry_form):\n return # osid.logging.LogEntry", "def _log_entry(self, entry):\n def log_post(logbook,logentry):\n session = self._logbook_service(logbook)\n info = dict(logentry)\n\n #Load attachments\n if 'attachments' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resize log table to entries.
def _resize_log_table(self) -> None: # resize columns self.tableLog.horizontalHeader().resizeSections(QtWidgets.QHeaderView.ResizeToContents) self.tableLog.horizontalHeader().setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents) # this is a one-time shot, so unconnect signal ...
[ "def resize_table(self):\n nextPrime = self.get_next_prime()\n if nextPrime > -1:\n oldValues = self.values\n self.values = [None] * nextPrime\n self.count = 0\n for i in range(len(oldValues)):\n if oldValues[i] is not None and (not oldValues[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A naive implementation of the forward pass for a maxpooling layer.
def max_pool_forward_naive(x, pool_param): out = None ########################################################################### # TODO: Implement the max-pooling forward pass # ########################################################################### ...
[ "def max_pool_forward_naive(x, pool_param):\n out = None\n\n\n pool_width = pool_param['pool_width']\n pool_height = pool_param['pool_height']\n stride = pool_param['stride']\n\n sample_width = x.shape[3]\n sample_height = x.shape[2]\n N = x.shape[0]\n F = x.shape[1]\n\n outputSizeWidth = int((sample_width...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Averages the signal and performs simple frequency analysis to extract hr
def simple_average(self, lo_hr=50, hi_hr=200): ms = np.mean(self.signals, axis=1) if len(ms) < 30*20: warnings.warn("Your video is shorter than 30 seconds. Resolution of HR detection may be too low") freq, power = scipy.signal.welch(ms - ms[0], fs=30, nperseg=len(ms)) # po...
[ "def harmonicModelAnal(x, fs, window, fft_size, hop_size, min_fft_val, nSines, minf0, maxf0, f0et, harmDevSlope=0.01, minSineDur=.02):\n\n\tif (minSineDur <0): # raise exception if minSineDur is smaller than 0\n\t\traise ValueError(\"Minimum duration of sine tracks smaller than 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds an OSM graph based on a filename or filehandle. Projection is used for calculating lengths. Subclasses can override the is_valid_way and create_edgepayload methods to filter path types and create alternative payloads.
def __init__(self, filename_osmobject_or_stream, projection): super(OSMGraph, self).__init__() self.projection = projection t0 = time.time() if filename_osmobject_or_stream.__class__ == OSM: self.osm = filename_osmobject_or_stream osm = s...
[ "def map_to_graph(filename):\n arr = np.loadtxt(filename, dtype=object, comments=None, delimiter='\\n')\n nrows = len(arr) # Number rows in map\n ncols = len(arr[0]) # Number columns in map\n g = Graph() # Undirected grap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sanitize HTML to leave only the readable toplevel elements.
def sanitize(html, strip_whitespace=False): TreeBuilder = html5lib.treebuilders.getTreeBuilder("lxml") parser = html5lib.HTMLParser(tree=TreeBuilder, tokenizer=ReadableTokenizer) tree = parser.parse(html) walker = ReadableTreewalker(tree) serializer = HTMLSerializer(strip_whitespace=strip_whitespace...
[ "def sanitize_html(html):\r\n p = html5lib.HTMLParser(tokenizer=HTMLSanitizer,\r\n tree=treebuilders.getTreeBuilder(\"dom\"))\r\n dom_tree = p.parseFragment(html)\r\n walker = treewalkers.getTreeWalker(\"dom\")\r\n stream = walker(dom_tree)\r\n s = serializer.HTMLSerializer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
El bot elige un rol aleatorio de los que tiene y verifica el resultado del enfrentamiento
def show_rol(bot, update, job_queue, user_data, chat_data): global timeOut global botRoles # Guardamos el mensaje que envio el Jugador text = update.message.text # Verificamos la clase elegida anteriormente por el usuario clase = user_data['clase'] # Si no se ha acabado el tiempo y el mensaje del ju...
[ "def es_operador(self):\n for role in self.roles:\n if \"operador_centro_de_ayuda\" == role.name:\n return True\n return False", "def rest_rollen_uitrekenen(mes, totaal, aantal_per_rol):\n if totaal <= mes * aantal_per_rol:\n\n # print(f'aantal rest rollen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Muestra los roles que le quedan al Bot
def bot_roles(bot, update): global botRoles update.message.reply_text("Los roles que me quedan son: \n") string = "" for rol in botRoles: string += rol[0] + " (" + str(rol[1]) + ")\n" update.message.reply_text(string)
[ "async def roles(self, ctx):\n pass", "async def roles(self, context, *text):\n \n try:\n command = text[0]\n except IndexError:\n command = \"list\"\n \n if command == \"add\" or command == \"remove\":\n pass\n elif command == \"jo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtenemos el numero correspondiente a la fikla del excel donde se encuentra el rol indicado
def numberRol(rol): for k in range(3, 21): if tabla['B' + str(k)].value == rol: return str(k)
[ "def numero_pines(self, ruta_fichero_excel):\n pinesfichero = 0\n if ruta_fichero_excel[-3:] == \"xls\":\n libro = xlrd.open_workbook(ruta_fichero_excel)\n hojas = libro.sheets()\n hoja = hojas[0]\n pinesfichero = hoja.nrows\n if ruta_fichero_excel[-4...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads configuration from a file. The file type is automatically determined by its extension
def read(file_path): # Check if config file is present if not os.path.isfile(file_path): raise FileError('FileNotFound', 'Config file was not found at ' + file_path) root, ext = os.path.splitext(file_path) ext = ext.lower() if ext == '.json': return Conf...
[ "def load_file(self, path: Union[str, bytes, os.PathLike]):\n ext = os.path.splitext(path)[-1]\n ext = ext.lower()\n if ext in ('.yml', '.yaml'):\n self.load_yaml(path)\n elif ext in ('.json',):\n self.load_json(path)\n else:\n raise IOError(f'Unsu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if all template are created correctly.
def test_created_templates(self): # create skeleton draft and open it to compare it modules.io.create_entity() with open(self.draft_location) as draft_location_object: draft_template = draft_location_object.read() self.assertEqual(self.empty_template, draft_template) ...
[ "def test_templates(self):\n\t\tpass", "def test_already_created(self):\n create_auto_init_templates(self.user_home_directory)\n\n with self.assertRaises(GitHomeTemplatesExists):\n create_auto_init_templates(self.user_home_directory)", "def test_tema_template(self):\n self.maxDif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rotate elements in an array of integers n = number of i tegers in a k = number of left rotations to perform a = array of integers
def array_left_rotation(a, n, k): if (not a) or (k == 0) or (k%n == 0): return a k = k%n a = a[k:] + a[:k] return a
[ "def rotateK(A, K, res):\r\n if K < 2: # bug fixed: we should not rotate first 0 and first 1 elements\r\n return\r\n res.append(K)\r\n left, right = 0, K-1\r\n while left < right:\r\n A[left], A[right] = A[right], A[left]\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns model blob for the given model id and model version
def get_model_blob(self, model_id, model_version): pass
[ "def write_model_blob(self, model_blob, model_id, model_version):\n pass", "def get_version(model_id: int, version_id: int, **kwargs):\n api_key, project = config.get_config_variables(kwargs.get(\"api_key\"), kwargs.get(\"project\"))\n url = config.get_base_url() + \"/api/0.6/projects/{}/analytics/mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write model blob with the given model id and model version to Model Repository storage.
def write_model_blob(self, model_blob, model_id, model_version): pass
[ "def get_model_blob(self, model_id, model_version):\n pass", "def save_model(model_path, nbsvm_model):\n with open(model_path, 'wb') as fd:\n joblib.dump(nbsvm_model, fd)", "def save_model(model, model_filepath):\n# filename = 'model.pkl'\n pickle.dump(model,open(model_filepath,'wb'))", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a proper ProjectInfo object based on the information in this AutoProjectInfo
def create_project_info(self, project_path): return ProjectInfo(self.app, self._name, project_path, self._source_path, self._reference)
[ "def with_fields(self, **kwargs) -> \"ProjectInfo\":\n return ProjectInfo(**{**self._asdict(), **kwargs})", "def _get_project_and_base_dto(self):\n base_dto = ProjectDTO()\n base_dto.project_id = self.id\n base_dto.project_status = ProjectStatus(self.status).name\n base_dto.defa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores the project info by name for later extraction by the auto directives. Stored separately to the nonauto project info objects as they should never overlap.
def store_project_info_for_auto(self, name: str, project_info: AutoProjectInfo) -> None: self.project_info_for_auto_store[name] = project_info
[ "def retrieve_project_info_for_auto(self, options) -> AutoProjectInfo:\n\n name = options.get(\"project\", self.app.config.breathe_default_project)\n if name is None:\n raise NoDefaultProjectError(\n \"No breathe_default_project config setting to fall back on \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }