query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Exit or return to DB_Main. If going to DB_Main, make sure that we save the primer_dict in the Database. Make sure that we close the primer database window.
def quit(self,event=None): #Make sure that we close the primer database window if open if self.pDB_open: self.pDB_open.close_pDB() self.pDB_open=None if self.sequ_win: self.sequ_win.close() self.sequ_win=None # Close the design_mutagenic ...
[ "def restore():\n init_db(dbs[active_db])", "def reload_database(self):\n self.db = self.load_database()", "def recover(self):\n if not hasattr(g, 'db'):\n g.db = pymysql.connect(user=self.app.config[\"DB_USER\"], db=self.app.config[\"DB_DB\"], password=self.app.config[\"DB_PWD\"], h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dialog to change sequence display settings
def seq_display_settings(self): # Open a new window for setting the restriction enzymes self.seq_display_setupwin=Toplevel() self.seq_display_setupwin.geometry('+300+450') self.seq_display_setupwin.title('Sequence Display Setup') # Spacing between bases row=1 lb...
[ "def Show_Sequences( self ):\r\n self.system.Change_Seq( \"Sequence\" )", "def setDisplayChoice(self, settings: ghidra.docking.settings.Settings, choice: unicode) -> None:\n ...", "def update_window_formatting(self):\n self.update_sequence_window()\n if self.pDB_open:\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the sequence display settings to prefs file
def save_preferences(self): print 'Saving DNAtool preferences' self.preferences.set('seqfont',self.seqfont.get()) self.preferences.set('seqfontsize',self.seqfontsize.get()) self.preferences.set('fontstyle',self.fontstyle.get()) self.preferences.set('base_scale',self.base_scale.g...
[ "def save_settings(self):\n self._click_button('save_settings')", "def save_config(self):\n self.glade.dump_gtk_state(self.config)\n self.config.write(open(os.path.expanduser('~/.apertium-simple-viewer.cfg'), 'w'))", "def settings_save(self):\n save_msg = MsgSettingsSave()\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the sequence display settings from prefs file, if present
def load_preferences(self): print 'Loading current DNAtool preferences' self.preferences = Preferences('DNAtool',{'canvas_height':600}) for key in self.defaultprefs: if key in self.preferences.prefs: self.__dict__[key].set(self.preferences.get(key)) else...
[ "def load(self):\n try:\n if os.path.isfile(self.filename):\n with open(self.filename, 'r' + self.openmode()) as f:\n self.prefs = self.loader(f)\n except Exception:\n if self.onloaderror:\n self.onloaderror(*sys.exc_info())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do this only when display setup changes are applied. Ensures all objects, including applied primers are updated with the new formatting.
def update_window_formatting(self): self.update_sequence_window() if self.pDB_open: self.pDB_open.refresh_primer() if self.show_comp_sequence.get==1: self.sequ_win.refresh_DNAseq() return
[ "def update_qc_properties(self):\n self.add_non_display_properties()\n self.add_display_properties()", "def prepare_to_visualize(self):\n self.system.hold_structure_changes()\n for surface in self.inactive_surfaces:\n surface.activate_constraint()\n self.system.resume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turn the over view window on and off
def overview_on_off(self): if self.overview_win: self.overview_button.deselect() self.overview_win.destroy() self.overview_win=None else: self.overview_button.select() if not self.data.has_key('AA_seqs1'): self.warning('No DNA ...
[ "def on_window_ontop_toggled(self, chk):\n self.client.set_bool(KEY('/general/window_ontop'), chk.get_active())", "def OnWindowMove(self):", "def toggleWindowVisibility(*args, **kwargs)->None:\n pass", "def TurnLightOn(self):\n self.isOn = True\n self.mainWin.settings_general_tip_of_th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the entropy of a distribution. Its default unit is 'bit'.
def entropy(distribution, unit=2): frequencies = distribution.frequencies(normalised=True) # check to see if it is a deterministic case (all but one are zero) zeros_size = frequencies[frequencies == 0].size if zeros_size + 1 == frequencies.size: return 0 else: return np.sum(-frequenc...
[ "def _entropy(cls, distribution):\n h = 0\n denominator = sum(distribution)\n if denominator:\n for freq in distribution:\n probability = float(freq) / denominator\n if probability:\n h += (probability * math.log(probability, cls.LOG_B...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
...Test serialization of solvers
def test_serializing_solvers(self): ratio = 0.5 l_enet = 1e-2 sd = ratio * l_enet proxes = [ ProxZero(), ProxTV(2), ProxL1(2), ProxGroupL1(strength=1, blocks_start=[0, 3, 8], blocks_length=[3, 5, 2]) ] so...
[ "def test_serializer(inout):\n from aiida_wannier90_workflows.utils.workflows.builder.serializer import serialize\n\n assert serialize(inout[0]) == inout[1], inout", "def test_serialization(valid_data):\n project: Project = Project.build(valid_data)\n serialized = project.dump()\n assert serialized...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return True if the operation is an ORM statement. This indicates that the select(), insert(), update(), or delete() being invoked contains ORM entities as subjects. For a statement that does not have ORM entities and instead refers only to
def is_orm_statement(self) -> bool: return self._compile_state_cls is not None
[ "def isDML(self):\n return self.script_java.isDML()", "def _is_should(self, operation):\n return (\n isinstance(operation, OrOperation) or\n isinstance(operation, UnknownOperation) and\n self.default_operator == ElasticsearchQueryBuilder.SHOULD\n )", "def is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return True if this is a SELECT operation.
def is_select(self) -> bool: return self.statement.is_select
[ "def is_select_query(cls, parsed_query: ParsedQuery) -> bool:\n return parsed_query.is_select()", "def test_is_select_query():\n client = Client()\n assert client._is_select_query('select 1')\n assert client._is_select_query(' SELECT 1')\n assert client._is_select_query('SELECT `insert`, `upda...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return True if this is an INSERT operation.
def is_insert(self) -> bool: return self.statement.is_dml and self.statement.is_insert
[ "def can_insert(data):\n return False", "def has_insert(self, shape):\n for insert in self.inserts:\n if insert.shape == shape:\n return True\n return False", "def can_insert(self):\r\n return self.query._sort == [desc('_date')]", "def can_insert(data):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return True if this is an UPDATE operation.
def is_update(self) -> bool: return self.statement.is_dml and self.statement.is_update
[ "def is_update(self):\n return self.action in [\"update\", \"partial_update\"]", "def can_update(self):\n return self.unique_id is not None", "def can_batch_update(self):\n # type: () -> bool\n return self.batch_flags & BatchFlags.BATCH_UPDATE", "def _is_valid_update_operation(sess...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return True if this is a DELETE operation.
def is_delete(self) -> bool: return self.statement.is_dml and self.statement.is_delete
[ "def can_delete(self):\n return self.unique_id is not None", "def has_delete(self) -> bool:\n return \"delete_item\" not in self.__abstractmethods__", "def can_delete(self):\n return self._can_delete", "def delete_instruction(self) -> bool:\n delete_key = \"Delete\"\n val = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the local execution options with new values.
def update_execution_options(self, **opts: Any) -> None: self.local_execution_options = self.local_execution_options.union(opts)
[ "def update_options(options):\n global opts\n opts = options", "def _run_options(self, **kwargs):\n import copy\n self.run_options = copy.deepcopy(self._global_options)\n self.run_options.update(kwargs)", "def update_execution_options(self, **opt: Any) -> None:\n self.dispatch....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the operation is refreshing columnoriented attributes on an existing ORM object.
def is_column_load(self) -> bool: opts = self._orm_compile_options() return opts is not None and opts._for_refresh_state
[ "def is_update(self) -> bool:\n return self.statement.is_dml and self.statement.is_update", "def _IsModified(self, name):\r\n return self._columns[name].IsModified()", "def is_modified(row, dialect):\n ins = inspect(row)\n modified_cols = set(get_column_keys(ins.mapper)) - ins.unmodified\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if this load is loading objects on behalf of a relationship. This means, the loader in effect is either a LazyLoader, SelectInLoader, SubqueryLoader, or similar, and the entire SELECT statement being emitted is on behalf of a relationship load. Handlers will very likely not want to add any options to querie...
def is_relationship_load(self) -> bool: opts = self._orm_compile_options() if opts is None: return False path = self.loader_strategy_path return path is not None and not path.is_root
[ "def requires_model_loading(self):\n return self.requires_loaded_models", "def is_load_manager(self):\n return self._is_load_manager", "def has_relationships(self):\n return len(self.relationships) > 0", "def allow_relation(self, obj1, obj2, **hints):\n is_segments = obj1._meta.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the update_delete_options that will be used for this execution.
def update_delete_options( self, ) -> Union[ bulk_persistence.BulkUDCompileState.default_update_options, Type[bulk_persistence.BulkUDCompileState.default_update_options], ]: if not self._is_crud: raise sa_exc.InvalidRequestError( "This ORM execution i...
[ "def configure_deletes(conf):\n print()\n if conf.get('purge', None) is None:\n conf['purge'] = yes_no(\n 'Would you like the sync to be able to delete files between devices?', default=False)\n if conf['purge'] and conf.get('purge_limit') is None:\n conf['purge_limit'] = numeric_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the current root transaction in progress, if any.
def get_transaction(self) -> Optional[SessionTransaction]: trans = self._transaction while trans is not None and trans._parent is not None: trans = trans._parent return trans
[ "def get_transaction(self) -> Optional[RootTransaction]:\n\n return self._transaction", "def transaction():\n return _transactions.get(_thread_id())", "def getProgressParent():\n return _progressParent", "def get_nested_transaction(self) -> Optional[SessionTransaction]:\n\n return self._ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the current nested transaction in progress, if any.
def get_nested_transaction(self) -> Optional[SessionTransaction]: return self._nested_transaction
[ "def get_nested_transaction(self) -> Optional[NestedTransaction]:\n return self._nested_transaction", "def transaction():\n return _transactions.get(_thread_id())", "def get_transaction(self) -> Optional[SessionTransaction]:\n trans = self._transaction\n while trans is not None and trans...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rollback the current transaction in progress. If no transaction is in progress, this method is a passthrough. The method always rolls back the topmost database transaction, discarding any nested transactions that may be in progress.
def rollback(self) -> None: if self._transaction is None: pass else: self._transaction.rollback(_to_root=True)
[ "def rollback(self):\n #pylint: disable-msg=W0212\n if self.isClosed():\n raise TransactionError(\"Cannot roll back a closed transaction.\")\n else:\n self.db()._txn_rollback(self)", "def rollback(self):\n if self.closed():\n raise TransactionError(\"Ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare the current transaction in progress for two phase commit. If no transaction is in progress, this method raises an
def prepare(self) -> None: trans = self._transaction if trans is None: trans = self._autobegin_t() trans.prepare()
[ "def commit(self):\n\t\tif not self.inTransac: \n\t\t\tsys.stdout.write(\"NO TRANSACTION\\n\")\n\t\telse: \n\t\t\tself.xcts = [self.currXct.copy()]\n\t\t\tself.valueCounts = [self.currValCount.copy()]\n\n\t\tself.inTransac = False", "def commit(self) -> None:\n if self._transaction:\n self._tran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a statement and return a scalar result. Usage and parameters are the same as that of
def scalar( self, statement: Executable, params: Optional[_CoreSingleExecuteParams] = None, *, execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT, bind_arguments: Optional[_BindArguments] = None, **kw: Any, ) -> Any: return self._execute_...
[ "def exec_scalar_query(self, sql_statement):\n conn = connect(**self.db_conn)\n cursor = conn.cursor()\n try:\n cursor.execute(sql_statement)\n result = cursor.fetchone()[0]\n conn.commit\n return result\n except Exception as e:\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a statement and return the results as scalars. Usage and parameters are the same as that of
def scalars( self, statement: Executable, params: Optional[_CoreAnyExecuteParams] = None, *, execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT, bind_arguments: Optional[_BindArguments] = None, **kw: Any, ) -> ScalarResult[Any]: return se...
[ "def execute(self, statement):\n return self._engine.connect().execute(statement)", "def scalar(\n self,\n statement: Executable,\n params: Optional[_CoreSingleExecuteParams] = None,\n *,\n execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,\n bind_arg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Locate an object in the identity map. Given a primary key identity, constructs an identity key and then looks in the session's identity map. If present, the object may be run through unexpiration rules (e.g. load unloaded attributes, check if was deleted).
def _identity_lookup( self, mapper: Mapper[_O], primary_key_identity: Union[Any, Tuple[Any, ...]], identity_token: Any = None, passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, lazy_loaded_from: Optional[InstanceState[Any]] = None, execution_options: OrmExecuteOptio...
[ "def lookup_id(cls, id_=None, key=None):\n if key:\n if cls != Incident:\n return None\n\n if key.startswith(KEY_FTPLOGIN):\n cls = IncidentFTPLogin\n elif key.startswith(KEY_HTTP_LOGIN):\n cls = IncidentHTTPLogin\n elif...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a context manager that disables autoflush.
def no_autoflush(self) -> Iterator[Session]: autoflush = self.autoflush self.autoflush = False try: yield self finally: self.autoflush = autoflush
[ "def no_autoflush(scoped_session=None):\n if scoped_session is None:\n scoped_session = Session\n def decorate(fn):\n def wrap(*args, **kw):\n session = scoped_session()\n autoflush = session.autoflush\n session.autoflush = False\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expires all persistent instances within this Session. When any attributes on a persistent instance is next accessed, a query will be issued using the
def expire_all(self) -> None: for state in self.identity_map.all_states(): state._expire(state.dict, self.identity_map._modified)
[ "def end_session(self):\n del self.is_managed[-1]\n if not self.is_managed[-1]:\n for key in self.reversed_delete_keys:\n cache.delete(key)\n del self.local_mem_cached\n del self.reversed_delete_keys", "def expire(\n self, instance: object, attr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expire the attributes on an instance. Marks the attributes of an instance as out of date. When an expired attribute is next accessed, a query will be issued to the
def expire( self, instance: object, attribute_names: Optional[Iterable[str]] = None ) -> None: try: state = attributes.instance_state(instance) except exc.NO_STATE as err: raise exc.UnmappedInstanceError(instance) from err self._expire_state(state, attribute_n...
[ "def expire(self):\n self.expired = True", "def expire(self, *args, **kw):\n self.metadb.expire(*args, **kw)", "def expire_accommodation(self):\n self.write({'state':'expired'})\n return True", "def expire_membership(self):\n\n if self.date_end < timezone.now(): # if simple...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expire a state if persistent, else expunge if pending
def _conditional_expire( self, state: InstanceState[Any], autoflush: Optional[bool] = None ) -> None: if state.key: state._expire(state.dict, self.identity_map._modified) elif state in self._new: self._new.pop(state) state._detach(self)
[ "def _do_expire(self):\n t = time.time()\n\n # Expire probes\n for ip, expire_at in self.outstanding_probes.items():\n if t > expire_at:\n self.outstanding_probes.pop(ip, None)\n if ip in self.live_servers:\n self.log.warn(\"Server %s ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the instance is associated with this session. The instance may be pending or persistent within the Session for a result of True.
def __contains__(self, instance: object) -> bool: try: state = attributes.instance_state(instance) except exc.NO_STATE as err: raise exc.UnmappedInstanceError(instance) from err return self._contains_state(state)
[ "def instance_exists(self, instance):\n pass", "def is_instance_okay(self):\n\n return self.instance_okay", "def valid(self):\r\n return self.resumable and self.sessionID", "def is_active(self):\n result = self.state in {EventTypes.RUNTIME_STATE.value, EventTypes.DATACOLLECT_STATE....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a bulk insert of the given list of mapping dictionaries.
def bulk_insert_mappings( self, mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]], return_defaults: bool = False, render_nulls: bool = False, ) -> None: self._bulk_save_mappings( mapper, mappings, False, False, ...
[ "def bulk_insert(engine, model, entries):\n with session_scope(engine) as session:\n session.bulk_insert_mappings(model, entries)\n session.commit()", "def insertmany(cls, *args):\n return InsertQuery(cls).bulk(True).set(*args)", "async def bulk_mongo_insert(db, collection_name, bulk_lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a bulk update of the given list of mapping dictionaries.
def bulk_update_mappings( self, mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]] ) -> None: self._bulk_save_mappings( mapper, mappings, True, False, False, False, False )
[ "def set_many(self, update_dict):\n for key, value in update_dict.items():\n self.set(key, value)", "def batch_update(self, values, w=1):\n for x in values:\n self.update(x, w)\n self.compress()\n return", "def update_many(self, rows, keys, chunk_size=1000, ensu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Return ``True`` if the given instance has locally modified attributes. This method retrieves the history for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value, if any. It is in effect a more expensive and accurate version of checking for the...
def is_modified( self, instance: object, include_collections: bool = True ) -> bool: state = object_state(instance) if not state.modified: return False dict_ = state.dict for attr in state.manager.attributes: if ( not include_collect...
[ "def is_modified(self):\n if self.__modified_data__ is not None:\n return True\n for value in self.__original_data__:\n try:\n if value.is_modified():\n return True\n except AttributeError:\n pass\n\n return False...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The set of all persistent states considered dirty. This method returns all states that were modified including those that were possibly deleted.
def _dirty_states(self) -> Iterable[InstanceState[Any]]: return self.identity_map._dirty_states()
[ "def dirty(self) -> IdentitySet:\n return IdentitySet(\n [\n state.obj()\n for state in self._dirty_states\n if state not in self._deleted\n ]\n )", "def states(self):\n return set(self._valid_states)", "def get_final_states...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The set of all persistent instances considered dirty.
def dirty(self) -> IdentitySet: return IdentitySet( [ state.obj() for state in self._dirty_states if state not in self._deleted ] )
[ "def _dirty_states(self) -> Iterable[InstanceState[Any]]:\n return self.identity_map._dirty_states()", "def all(cls):\n return [instance for instance in cls._instances.values()\n if instance.active]", "def save(self):\n count = 0\n for entity in self._entities.values()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produce a context manager that both provides a new
def begin(self) -> contextlib.AbstractContextManager[_S]: session = self() return session._maker_context_manager()
[ "def __enter__(self):\n for c in self._context_managers:\n c.__enter__()\n return self", "def as_contextmanager(self, *context):\n self.setup(*context)\n yield self\n self.teardown()", "def contextmanager(func):\n @wraps(func)\n def helper(*args, **kwds):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close all sessions in memory.
def close_all_sessions() -> None: for sess in _sessions.values(): sess.close()
[ "def close_all(cls):\n for sess in cls._session_registry.values():\n sess.close()", "def closeAllSessions(self):\n self.ormSessionCreator() # Ensure we have a session maker and session\n self._ScopedSession.close_all()", "def close_sessions(self):\n if self._session_manag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a scattering file with a, b and c coefficients in the columns provided.
def load_scattering_file(filename, a_inds, b_inds, c_ind): import numpy as np with open(filename, "r", encoding="utf-8") as f: flines = [line for line in f.readlines() if not line.startswith("#")] atomic_scattering_coeffs = {} for line in flines: x = line.split() label = x[0]...
[ "def load_two_column_data(file, rows_to_skip=0):\n\n data = loadtxt(file, skiprows = rows_to_skip)\n\n\n\n data_q = data[:,0]\n data_i = data[:,1]\n return ExpSasData(data_q, data_i)", "def load_scatter_table(self, fn):\n with open(fn, 'rb') as f:\n data = pickle.load(f)\n\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
使用maxValue来修剪梯度 参数: gradients 字典类型,包含了以下参数:"dWaa", "dWax", "dWya", "db", "dby" maxValue 阈值,把梯度值限制在[maxValue, maxValue]内 返回: gradients 修剪后的梯度
def clip(gradients, maxValue): # 获取参数 dWaa, dWax, dWya, db, dby = gradients['dWaa'], gradients['dWax'], gradients['dWya'], gradients['db'], gradients[ 'dby'] # 梯度修剪 for gradient in [dWaa, dWax, dWya, db, dby]: np.clip(gradient, -maxValue, maxValue, out=gradient) gradients ...
[ "def apply_gradients(self, gradients: ParamDictType) -> None:", "def scale_grads(gradients):\n return np.sign(gradients) * minmax_scale(np.abs(gradients), axis = 1)", "def max_gradient(self, value):\n if value <= 0 :\n raise ValueError('The `max_gradient` must be > 0.')\n\n self._int...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
根据RNN输出的概率分布序列对字符序列进行采样 参数: parameters 包含了Waa, Wax, Wya, by, b的字典 char_to_ix 字符映射到索引的字典 seed 随机种子 返回: indices 包含采样字符索引的长度为n的列表。
def sample(parameters, char_to_ix, seed): Wax = parameters["Wax"] Waa = parameters["Waa"] Wya = parameters["Wya"] b = parameters["b"] #ba by = parameters["by"] n_y = by.shape[0] n_a = Waa.shape[0] # initialize the value x = np.zeros((n_y, 1)) a_prev = np.zeros((n_...
[ "def sample(parameters, char_to_ix, seed):\n\n # Retrieve parameters and relevant shapes from \"parameters\" dictionary\n Waa, Wax, Wya, by, ba = parameters['Waa'], parameters['Wax'], parameters['Wya'], parameters['by'], parameters['ba']\n vocab_size = by.shape[0]\n n_a = Waa.shape[1]\n\n # Step 1: C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
执行训练模型的单步优化。 参数: X 整数列表,其中每个整数映射到词汇表中的字符。 Y 整数列表,与X完全相同,但向左移动了一个索引。 a_prev 上一个隐藏状态 parameters 字典,包含了以下参数: Wax 权重矩阵乘以输入,维度为(n_a, n_x) Waa 权重矩阵乘以隐藏状态,维度为(n_a, n_a) Wya 隐藏状态与输出相关的权重矩阵,维度为(n_y, n_a) b 偏置,维度为(n_a, 1) by 隐藏状态与输出相关的权重偏置,维度为(n_y, 1) learning_rate 模型学习的速率 返回: loss 损失函数的值(交叉熵损失) gradients 字典,包含了以下参数: dWax 输入到隐藏的...
def optimize(X, Y, a_prev, parameters, learning_rate=0.01): # 前向传播 loss, cache = cllm_utils.rnn_forward(X, Y, a_prev, parameters) # 反向传播 gradients, a = cllm_utils.rnn_backward(X, Y, parameters, cache) # 梯度修剪,[-5 , 5] gradients = clip(gradients, 5) # 更新参数 parameters = cllm...
[ "def optimize(X, Y, a_prev, parameters, learning_rate = 0.01): \n\t# 前向传播 \n\tloss, cache = cllm_utils.rnn_forward(X, Y, a_prev, parameters) \n\n\t# 反向传播 \n\tgradients, a = cllm_utils.rnn_backward(X, Y, parameters, cache) \n\n\t# 梯度修剪,[-5 , 5] \n\tgradients = clip(gradients,5) \n\n\t# 更新参数 \n\tparameters = cllm_uti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
训练模型并生成恐龙名字 参数: data 语料库 ix_to_char 索引映射字符字典 char_to_ix 字符映射索引字典 num_iterations 迭代次数 n_a RNN单元数量 dino_names 每次迭代中采样的数量 vocab_size 在文本中的唯一字符的数量 返回: parameters 学习后了的参数
def model(data, ix_to_char, char_to_ix, num_iterations = 3500, n_a = 50, dino_names = 7, vocab_size = 27): n_x, n_y = vocab_size, vocab_size parameters = cllm_utils.initialize_parameters(n_a, n_x, n_y) loss = cllm_utils.get_initial_loss(vocab_size, dino_names) # 构建恐龙名称列表 with open("../din...
[ "def train_model(self):\n for language, tweets in self.data.items():\n for tweet in tweets:\n if self.ngram == '1':\n for i in range(len(tweet) - 1):\n first = tweet[i] # get the first character\n if not first.isspace(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests initialisation of Aquarius objects.
def test_init(): aqua = Aquarius("http://something/api/v1/aquarius/assets") assert ( aqua.url == "http://something/api/v1/aquarius/assets/ddo" ), "Different URL from the specified one." assert ( aqua.root_url == "http://something" ), "Different root URL from the specified one."
[ "def test_init():\n aqua = Aquarius(\"http://something/api/v1/aquarius/assets\")\n assert (\n aqua.base_url == \"http://something/api/v1/aquarius/assets\"\n ), \"Different URL from the specified one.\"", "def test_init(self):\n pass", "def setUp(self):\n self.amenity = Amenity()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests against singleddo functions of Aquarius.
def test_aqua_functions_for_single_ddo( publisher_ocean_instance, metadata, aquarius_instance ): publisher = get_publisher_wallet() metadata_copy = metadata.copy() ddo = publisher_ocean_instance.assets.create(metadata_copy, publisher) wait_for_ddo(publisher_ocean_instance, ddo.did) aqua_metadat...
[ "def test_aqua_functions_for_single_ddo(\n publisher_ocean_instance, metadata, aquarius_instance\n):\n publisher = get_publisher_wallet()\n metadata_copy = metadata.copy()\n\n ddo = publisher_ocean_instance.assets.create(metadata_copy, publisher)\n wait_for_ddo(publisher_ocean_instance, ddo.did)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests against multipleddo functions of Aquarius.
def test_aqua_function_for_multiple_ddos(aquarius_instance): assert aquarius_instance.list_assets() assert aquarius_instance.list_assets_ddo()
[ "def test_aqua_functions_for_single_ddo(\n publisher_ocean_instance, metadata, aquarius_instance\n):\n publisher = get_publisher_wallet()\n metadata_copy = metadata.copy()\n\n ddo = publisher_ocean_instance.assets.create(metadata_copy, publisher)\n wait_for_ddo(publisher_ocean_instance, ddo.did)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests metadata validation failure.
def test_metadata_invalid(aquarius_instance): result, errors = aquarius_instance.validate_metadata( {"some_dict": "that is invalid"} ) assert result is False assert errors[0]["message"] == "'main' is a required property"
[ "def _validate(self):\n if not self._contents.has_key('type'):\n raise ValidationFailed(\"Metadata file %s contains no type field\" % (self._filename))\n \n if not self._contents.has_key('version'):\n raise ValidationFailed(\"Metadata file %s contains no version field\" %\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests text search with an invalid text.
def test_invalid_text_search(aquarius_instance): text = "foo_text" with pytest.raises(ValueError): aquarius_instance.text_search(text=text, sort="foo_sort")
[ "def test_search_unknown_term(self):\n\n random_string = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(32))\n self.assertFalse(len(search.collect(random_string)))", "def assertNoMatch(self, text):\r\n self.assertRaises(NoMatch, self.template.extract, text)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests query search with an invalid query.
def test_invalid_search_query(aquarius_instance): search_query = dict() search_query["sort"] = "foo_sort" with pytest.raises(ValueError): aquarius_instance.query_search(search_query=search_query, sort="foo_sort")
[ "def test_get_search_result_with_invalid_query_type(self):\n with self.assertRaises(CloudantArgumentError) as cm:\n self.db.get_search_result(\n 'searchddoc001', 'searchindex001', query=['blah']\n )\n err = cm.exception\n self.assertTrue(str(err).startswith(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method to make a `ValidationError` with an error message from ``self.error_messages``.
def make_error(self, key: str, **kwargs) -> ValidationError: try: msg = self.error_messages[key] except KeyError as error: class_name = self.__class__.__name__ message = ( "ValidationError raised by `{class_name}`, but error key `{key}` does " ...
[ "def message_error_validator():\n\n return validator.MessageErrorSchema()", "def __init__(self, message, code=None, params=None):\n\n # PY2 can't pickle naive exception: http://bugs.python.org/issue1692335.\n super(ValidationError, self).__init__(message, code, params)\n\n if isinstance(me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update field with values from its parent schema. Called by
def _bind_to_schema(self, field_name, schema): self.parent = self.parent or schema self.name = self.name or field_name self.root = self.root or ( self.parent.root if isinstance(self.parent, FieldABC) else self.parent )
[ "def updateField(field):", "def _populate(self, fields):\n schema = self.schema\n for k, v in fields.items():\n fields[k] = schema.fields[k].iget(self, v)\n\n self.modify(fields)\n self.reset_modified()", "def __modify_schema__(cls, field_schema):\n field_schema.upd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The nested Schema object.
def schema(self): if not self._schema: # Inherit context from parent. context = getattr(self.parent, "context", {}) if callable(self.nested) and not isinstance(self.nested, type): nested = self.nested() else: nested = self.nested ...
[ "def schema(self):\n if not self.__schema:\n # Ensure that only parameter is a tuple\n if isinstance(self.only, basestring):\n only = (self.only,)\n else:\n only = self.only\n\n # Inherit context from parent.\n context = get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the number value for value, given this field's `num_type`.
def _format_num(self, value) -> typing.Any: return self.num_type(value)
[ "def number_value(self) -> typing.Optional[jsii.Number]:\n return self._values.get('number_value')", "def _get_as_num(value):\n\n if isinstance(value, JSWrapper):\n value = value.get_literal_value()\n if value is None:\n return 0\n\n try:\n if isinstance(value, types.StringTyp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the signed difference between two ticks values assuming that they are within 228 ticks
def ticks_diff(ticks1: int, ticks2: int) -> int: diff = (ticks1 - ticks2) & _TICKS_MAX diff = ((diff + _TICKS_HALFPERIOD) & _TICKS_MAX) - _TICKS_HALFPERIOD return diff
[ "def tickDiff(t1, t2):\n tDiff = t2 - t1\n if tDiff < 0:\n tDiff += (1 << 32)\n return tDiff", "def ticks_diff(end: int, start: int) -> int:\n return end - start", "def _diff(rankx, ranky):\n shift = int64(32)\n mask = int64((1 << 32) - 1)\n scale = float64(mask + 1)\n hi = ranky >> sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set preamp boost if needed.
def set_boost(self, setting: int) -> None: if self._tx_power >= 18: self._write_u8(_REG_TEST_PA1, setting) self._write_u8(_REG_TEST_PA2, setting)
[ "def set_boost(self, boost=1.0):\n return self.set_param('boost', float(boost))", "def set_boost(self, boost):\r\n self._boost = float(boost)\r\n return self", "def set_boost(self, audio_boost):\n self.audio_boost = audio_boost", "def start_boosting(self):\n if not self._boo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transmit a packet which is queued in the FIFO. This is a low level function for entering transmit mode and more. For generating and transmitting a packet of data use
def transmit(self) -> None: # Like RadioHead library, turn on high power boost if enabled. self.set_boost(_TEST_PA1_BOOST) # Enable packet sent interrupt for D0 line. self.dio_0_mapping = 0b00 # Enter TX mode (will clear FIFO!). self.operation_mode = TX_MODE
[ "def enqueue(self, packet):\n\t\tdef send():\n\t\t\tself.__log('queue-start %d', packet.id)\n\t\t\tself.__mutex.lock()\n\t\t\tself.__log('queue-end %d', packet.id)\n\t\t\t\n\t\t\tself.__log('transmit-start %d', packet.id)\n\t\t\tsim.sleep(packet.size / self.bandwidth)\n\t\t\tself.__log('transmit-end %d', packet.id)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The operation mode value. Unless you're manually controlling the chip you shouldn't change the operation_mode with this property as other sideeffects are required for
def operation_mode(self) -> int: op_mode = self._read_u8(_REG_OP_MODE) return (op_mode >> 2) & 0b111
[ "def operation_mode(self):\n return self._operation_mode", "def operation_mode(self) -> int:\n return self._operation_mode", "def set_operation_mode(self, operation_mode):", "def GetOperationMode(self):\n result = self.SerialSendReceive(self.CMD_GET_OPERATION_MODE,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The synchronization word value. This is a byte string up to 8 bytes long (64 bits) which indicates the synchronization word for transmitted and received packets. Any received packet which does not include this sync word will be ignored. The default value is 0x2D, 0xD4 which matches the RadioHead RFM69 library. Setting ...
def sync_word(self) -> bytearray: # Handle when sync word is disabled.. if not self.sync_on: return None # Sync word is not disabled so read the current value. sync_word_length = self.sync_size + 1 # Sync word size is offset by 1 # according to datasheet. syn...
[ "def set_sync_word(self, value):\n # Check format\n if value > 0xFFFF:\n raise StationException(\"Synchronization words must be 2-byte length\")\n # Switch to command mode if necessary\n if self._sermode == SerialModem.Mode.DATA:\n self.enter_command_mode()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The length of the preamble for sent and received packets, an unsigned 16bit value. Received packets must match this length or they are ignored! Set to 4 to match the RadioHead RFM69 library.
def preamble_length(self) -> int: msb = self._read_u8(_REG_PREAMBLE_MSB) lsb = self._read_u8(_REG_PREAMBLE_LSB) return ((msb << 8) | lsb) & 0xFFFF
[ "def get_payload_length(packet):\n adaptation_field_len = TS.get_adaptation_field_length(packet)\n return 188 - 4 - adaptation_field_len", "def setPacketLength(self):\n self.packetLength = len(self) - PRIMARY_HEADER_BYTE_SIZE - 1", "def min_pkt_size(self):\n return 64", "def get_video_preamble...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The AES encryption key used to encrypt and decrypt packets by the chip. This can be set to None to disable encryption (the default), otherwise it must be a 16 byte long byte string which defines the key (both the transmitter and receiver must use the same key value).
def encryption_key(self) -> bytearray: # Handle if encryption is disabled. if self.aes_on == 0: return None # Encryption is enabled so read the key and return it. key = bytearray(16) self._read_into(_REG_AES_KEY1, key) return key
[ "def _encrypt_aes_key(aes_key: bytes, receiver_public_key: RsaKey) -> bytes:\n cipher_rsa = PKCS1_OAEP.new(receiver_public_key)\n return cipher_rsa.encrypt(aes_key)", "def encryption_key(self) -> typing.Optional[aws_cdk.aws_kms.IKey]:\n return jsii.get(self, \"encryptionKey\")", "def get_key(self):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The transmit power in dBm. Can be set to a value from 2 to 20 for high power devices (RFM69HCW, high_power=True) or 18 to 13 for low power devices. Only integer power levels are actually set (i.e. 12.5 will result in a value of 12 dBm).
def tx_power(self) -> int: # Follow table 10 truth table from the datasheet for determining power # level from the individual PA level bits and output power register. pa0 = self.pa_0_on pa1 = self.pa_1_on pa2 = self.pa_2_on current_output_power = self.output_power ...
[ "def dBm_to_watts(dbm):\n if type(dbm) == float or type(dbm) == int:\n return math.pow(10.,dbm/10.)/1000.\n else:\n return numpy.power(10.,dbm/10.)/1000.", "def get_power(self):\r\n return self._api.get_power()", "def power_configuration(self):\n\t\tPOWER_CONFIG = (ITG3200_CLOCK_PLL_XGYRO | ITG32...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The received strength indicator (in dBm). May be inaccuate if not read immediatey. last_rssi contains the value read immediately receipt of the last packet.
def rssi(self) -> float: # Read RSSI register and convert to value using formula in datasheet. return -self._read_u8(_REG_RSSI_VALUE) / 2.0
[ "def rssi(self):\n return self._zigpy_device.rssi", "def get_signal_level_from_rssi(rssi):\n dBm = -113 + (rssi * 2)\n \n if dBm < -95 or dBm >= 85:\n return 0\n elif dBm >= -95 and dBm < -85:\n return 25\n elif dBm >= -85 and dBm < -75:\n return 50\n elif dBm >= -75 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The modulation bitrate in bits/second (or chip rate if Manchester encoding is enabled). Can be a value from ~489 to 32mbit/s, but see the datasheet for the exact supported values.
def bitrate(self) -> float: msb = self._read_u8(_REG_BITRATE_MSB) lsb = self._read_u8(_REG_BITRATE_LSB) return _FXOSC / ((msb << 8) | lsb)
[ "def bitrate(self) -> int:\n return self.properties[DBUS_ATTR_BITRATE]", "def audio_bitrate(self):\n # type: () -> int\n return self._audio_bitrate", "def target_bitrate(self) -> int:\n return self.__target_bitrate", "def video_bitrate(self):\n # type: () -> int\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The frequency deviation in Hertz.
def frequency_deviation(self) -> float: msb = self._read_u8(_REG_FDEV_MSB) lsb = self._read_u8(_REG_FDEV_LSB) return _FSTEP * ((msb << 8) | lsb)
[ "def main_frequency(self):\n fft_length, _ = self.check_params()\n n_freq = fft_length // 2 + 1\n freq = np.linspace(0, self.fs / 2, n_freq)\n psd = self.psd[-1][0, :]\n return freq[np.argmax(psd[1:]) + 1]", "def Fs(self) -> int:\n return self.daq_sample_frequency", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wait to receive a packet from the receiver. If a packet is found the payload bytes are returned, otherwise None is returned (which indicates the timeout elapsed with no reception). If keep_listening is True (the default) the chip will immediately enter listening mode after reception of a packet, otherwise it will fall ...
def receive( self, *, keep_listening: bool = True, with_ack: bool = False, timeout: Optional[float] = None, with_header: bool = False ) -> int: timed_out = False if timeout is None: timeout = self.receive_timeout if timeout is not N...
[ "def wait_for_packet(self) -> dict:\n\n packet = {'len':0, 'cmd':0, 'data':0, 'crc':1, 'timeout':1}\n\n n = self.ser.read(2) # get the length bytes\n if(len(n) < 2):\n #self.addMessage(\"\\tpacket length < 2\")\n return packet\n\n packet['len'] = int.from_bytes(n, b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
e = svpice(t) Calculates the water vapor mixing ratio
def svpice(t): A0=0.7859063157e0 A1=0.357924232e-1 A2=-0.1292820828e-3 A3=0.5937519208e-6 A4=0.4482949133e-9 A5=0.2176664827e-10 T = t - 273.16 e = pow(10.0,A0+T*(A1 + T*(A2 + T*(A3 + T*(A4 + T*A5))))) return e
[ "def mixing_ratio(vp, p) :\r\n return EPSILON * (vp / (p - vp))", "def p(party, vote_count, s):\n return t(party, vote_count) / d(s)", "def vapor_pressure(pressure, mixing):\n epsilon = 0.622\n return pressure * mixing / (epsilon + mixing)", "def sound_velocity_wilson(s: float, t: float, p: float)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps iTunes product names to Subscription attributes. An iTunes "product" also includes information about the billing cycle; by convention we name our products with a suffix of "_month" or "_year" (etc).
def _GetITunesProductInfo(cls, verify_response): product_id = verify_response.GetProductId() base_product, billing_cycle = product_id.rsplit('_', 1) assert billing_cycle in ('month', 'year'), billing_cycle return Subscription._ITUNES_PRODUCTS[base_product]
[ "def _get_products_in_subscription(self, subscription):\n path = 'katello/api/v2/subscriptions/{}'.format(subscription.id)\n subscription_json = satellite_get_response(path)\n name_dict = dict(\n (\n prod_json['name'],\n satellite_json_to_entity(prod_jso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the subscription id for an iTunes transaction. THe returned id will be the same for all transactions in a series of renewals.
def GetITunesSubscriptionId(cls, verify_response): return kITunesPrefix + verify_response.GetOriginalTransactionId()
[ "def subscription_id(self) -> str:\n return pulumi.get(self, \"subscription_id\")", "def GetITunesSubscriptionId(cls, verify_response):\r\n return kITunesPrefix + verify_response.GetOriginalTransactionId()", "def subscription_id(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"subscripti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a subscription object for an iTunes transaction. The verify_response argument is a response from viewfinder.backend.services.itunes_store.ITunesStoreClient.VerifyReceipt. The new object is returned but not saved to the database.
def CreateFromITunes(cls, user_id, verify_response): assert verify_response.IsValid() sub_dict = dict( user_id=user_id, transaction_id=Subscription.GetITunesTransactionId(verify_response), subscription_id=Subscription.GetITunesSubscriptionId(verify_response), timestamp=verify_response.Ge...
[ "def RecordITunesTransaction(cls, client, callback, user_id, verify_response):\r\n sub = Subscription.CreateFromITunes(user_id, verify_response)\r\n sub.Update(client, callback)", "def RecordITunesTransaction(cls, client, callback, user_id, verify_response):\n sub = Subscription.CreateFromITunes(user_id,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a subscription record for an iTunes transaction and saves it to the database. The verify_response argument is a response from viewfinder.backend.services.itunes_store.ITunesStoreClient.VerifyReceipt.
def RecordITunesTransaction(cls, client, callback, user_id, verify_response): sub = Subscription.CreateFromITunes(user_id, verify_response) sub.Update(client, callback)
[ "def RecordITunesTransaction(cls, client, callback, user_id, verify_response):\r\n sub = Subscription.CreateFromITunes(user_id, verify_response)\r\n sub.Update(client, callback)", "def testValidReceipt(self):\r\n self.mock_http.map('.*', itunes_store_test.MakeNewResponse())\r\n response = self._Record...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Project a subset of subscription attributes that can be provided to the user.
def MakeMetadataDict(self): sub_dict = {} for attr_name in Subscription._JSON_ATTRIBUTES: util.SetIfNotNone(sub_dict, attr_name, getattr(self, attr_name, None)) if self.extra_info: sub_dict['extra_info'] = deepcopy(self.extra_info) return sub_dict
[ "def strip_praw_subscription(subscription):\n\n data = {}\n data['object'] = subscription\n if isinstance(subscription, praw.objects.Multireddit):\n data['type'] = 'Multireddit'\n data['name'] = subscription.path\n data['title'] = subscription.description_md\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function adds a node to the new SQLite db and appends it's new last_row_id to a dictionary
def add_node(old_node_dict, old_to_new_node_ids_dict, new_accession, new_db_api, aliases): # getting the old node id, and the old node's properties old_node_id = old_node_dict["id"] old_node_alt_accession = old_node_dict["alt_accession"] old_node_name = old_node_dict["name"] tax_id = old_node_dict[...
[ "def post_database_node_create(self, resource_dict):\n pass", "def add_node(row: list, main_data_list: list) -> None:\n log.info('add node')\n sub_data = get_node_with_level(row)\n level = sub_data['level']\n sub_data.popitem()\n sub_data['children'] = []\n log.debug('sub_data : %s', sub_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Migrate resource to a node in the cluster.
def migrate_resource_to_node(self, resource_name, node_name, lifetime): try: if not os.path.exists('/usr/sbin/crm'): return False # Lifetime follows the duration format specified in ISO_8601 os.system("/usr/sbin/crm resource migrate %s %s P%sS" ...
[ "def convert(self, node):\n # get the conversion lut\n node_type = self.get_node_type(node)\n conversion_specs = self.conversion_spec_sheet.get(node_type)\n if not conversion_specs:\n print('No conversion_specs for: %s' % node_type)\n return\n\n # call any ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes res_summary of current run (in json format) and appends to main results frame (in csv format)
def save_results_to_csv(save_file_path, append=True, tmp_file_path=tmp_file_path, datefmt='%d/%m/%Y %H:%M:%S'): # load tmp results res_summary = open_json(tmp_file_path, data_format=pd.DataFrame) # calculate average scores combis = list(product( ['CV', 'Val'], ['precision', 'recall', '...
[ "def write_results_to_overview(overview, config, run_id, gs_id, duration, best_fitness, stopped_early):\n tmp_add = pd.DataFrame({\n 'user_id': USER,\n 'comments': [None]\n })\n\n # save results to csv\n tmp_results = pd.DataFrame({\n 'run_id': [run_id],\n 'gs_id': [int(gs_id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve all the YouTube IDs (including translations) from KA.org. This will fetch all the publiclyvisible YouTube IDs on the site in all languages and return them as a big, flat list.
def get_youtube_ids(): global _id_list if _id_list is None: all_videos_in = urllib2.urlopen("http://www.khanacademy.org/api/internal/videos/localized/all") try: all_videos = simplejson.load(all_videos_in) finally: all_videos_in.close() # Now get our CS vi...
[ "def get_course_youtube_ids(self):\n\n with ProgressBar() as pb:\n for i, unit_url in zip(\n pb(range(len(self.course_unit_urls)), label=\"Collecting Youtube IDs:\"),\n self.course_unit_urls,\n ):\n unit_url = ROOT_URL + unit_url\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify ID token with Google.
def verify_token(token): try: idinfo = client.verify_id_token(token, app.config['GOOGLE_CLIENT_ID']) if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise crypt.AppIdentityError("Wrong issuer.") except crypt.AppIdentit...
[ "def verify_google_id_token(id_token):\n\n try:\n # id_info = client.verify_id_token(id_token, CLIENT_ID)\n\n # Or, if multiple clients access the backend server:\n id_info = client.verify_id_token(id_token, None)\n # if id_info['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the mode`mode` unfolding of `tensor`.
def unfold(tensor, mode): return np.moveaxis(tensor, mode, 0).reshape((tensor.shape[mode], -1))
[ "def tensorUnfold(self, tensor, mode):\n \n n_dim = tensor.ndim\n indices = np.arange(n_dim).tolist()\n element = indices.pop(mode)\n sample_index = indices.pop(0)\n new_indices = ([sample_index] + [element] + indices) \n \n samples = tensor.shape[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rescales factors across modes so that all norms match.
def rebalance(self): # Compute norms along columns for each factor matrix norms = [np.linalg.norm(f, axis=0) for f in self.factors] # Multiply norms across all modes lam = np.prod(norms, axis=0) ** (1/self.ndim) # Update factors self.factors = [f * (lam / fn) for f, fn...
[ "def _set_scale_factors_to_one(self):\n self.wnorm = 1.0\n self.hnorm = 1.0\n self.xnorm = 0.0\n self.ynorm = 0.0\n self.scale = 1.0", "def renormZeroModes(self):\n\t\tfor z in range(self.nZero):\n\t\t\tfor i in range(self.totalBins):\n\t\t\t\tself.zeroModes[z][i] *= self.norms[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds n more factors holding zeros.
def pad_zeros_(self, n): if n == 0: return self.factors = [np.column_stack((f, np.zeros((f.shape[0], n)))) for f in self.factors] self.rank += n
[ "def sum_factors(n):\n\treturn sum(filter(lambda i: n % i == 0, range(1,n//2+1)))", "def factor_naive(n):\n factors = []\n\n for factor in range(2, n // 2):\n q, r = divmod(n, factor)\n power = 0\n while r == 0:\n power += 1\n n = q\n q, r = divmod(q, fa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Permutes the columns of the factor matrices inplace.
def permute(self, idx): # Check that input is a true permutation if set(idx) != set(range(self.rank)): raise ValueError('Invalid permutation specified.') # Update factors self.factors = [f[:, idx] for f in self.factors] return self.factors
[ "def permuteFwd(self, perm):\n copy = self[:,:]\n for i in range(len(perm)):\n copy.row_swap(perm[i][0], perm[i][1])\n return copy", "def permuteBkwd(self, perm):\n copy = self[:,:]\n for i in range(len(perm)-1, -1, -1):\n copy.row_swap(perm[i][0], perm[i][...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a random Nway tensor with rank R, where the factors are generated from the standard normal distribution.
def randn_ktensor(shape, rank, norm=None, random_state=None): # Check input. rns = _check_random_state(random_state) # Draw low-rank factor matrices with i.i.d. Gaussian elements. factors = KTensor([rns.standard_normal((i, rank)) for i in shape]) return _rescale_tensor(factors, norm)
[ "def rand_ktensor(shape, rank, norm=None, random_state=None):\n\n # Check input.\n rns = _check_random_state(random_state)\n\n # Randomize low-rank factor matrices i.i.d. uniform random elements.\n factors = KTensor([rns.uniform(0.0, 1.0, size=(i, rank)) for i in shape])\n return _rescale_tensor(fact...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a random Nway tensor with rank R, where the factors are generated from the standard uniform distribution in the interval [0.0,1].
def rand_ktensor(shape, rank, norm=None, random_state=None): # Check input. rns = _check_random_state(random_state) # Randomize low-rank factor matrices i.i.d. uniform random elements. factors = KTensor([rns.uniform(0.0, 1.0, size=(i, rank)) for i in shape]) return _rescale_tensor(factors, norm)
[ "def randn_ktensor(shape, rank, norm=None, random_state=None):\n\n # Check input.\n rns = _check_random_state(random_state)\n\n # Draw low-rank factor matrices with i.i.d. Gaussian elements.\n factors = KTensor([rns.standard_normal((i, rank)) for i in shape])\n return _rescale_tensor(factors, norm)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrive a proxy if it exists
def get_proxy(self, proxy_name): proxies = self.proxies() if proxy_name in proxies: return proxies[proxy_name] else: return None
[ "async def get_proxy():\n await cond.acquire()\n proxy = ''\n try:\n await cond.wait()\n if len(proxies) > 0:\n proxy = proxies.popleft()\n proxies_used.add(proxy)\n finally:\n cond.release()\n return proxy", "def get_proxy():\n global proxy_list, opts\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a toxiproxy proxy
def create(self, upstream, name, listen=None, enabled=None): if name in self.proxies(): raise_with_traceback(ProxyExists("This proxy already exists.")) # Lets build a dictionary to send the data to the Toxiproxy server json = { "upstream": upstream, "name": ...
[ "def tp_create_proxy(self, data):\n return self.tp_post(uri=\"/proxies\", data=data)", "def mutate_toxiproxy(self, body, spec):\n # 1. Precompute the ports that need to be proxied\n # for every port specified in the containers' definitions\n containers_ports = []\n for container in body.spec.te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the APIConsumer host and port
def update_api_consumer(self, host, port): APIConsumer.host = host APIConsumer.port = port APIConsumer.base_url = "http://%s:%s" % (host, port)
[ "def update_api_endpoints(self):\n self.marketplace_api.host = self.settings['marketplace_url']\n self.producer_api.host = self.settings['producer_url']", "def api_port(self, api_port):\n\n self._api_port = api_port", "def set_service_host(self, host):\n self._api_host = f\"https://{...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the path of the inputfile to the outputdir folder
def create_path(inputfile, outputdir): pathdata = '/'.join(inputfile.split('/')[-3:]) newpath = join(outputdir, pathdata) dirout = dirname(newpath) if not isdir(dirout): os.makedirs(dirout) return newpath
[ "def _map_to_output_dir(input_path, output_dir):\n # type: (str, str) -> (str)\n output_file = input_path\n scheme = filesystems.FileSystems.get_scheme(input_path)\n if scheme:\n if not input_path.startswith(scheme + _FILE_SYSTEM_SCHEME_SEPARATOR):\n raise ValueError('Expected {}{} at the beginning of i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resize images from `fileinput` to `size` by `size`, saving the output images in `output` folder.
def main(inputfile, output, size): if not output: output = join(dirname(inputfile), str(size)) if not isdir(output): os.mkdir(output) logger.info('Resizing images from: %s' % inputfile) inputfile = realpath(inputfile) #/usr/share/datasets/KSCGR_Original/data1/boild-egg/0.jpg...
[ "def resize( input_file, output_file, size ):\n\tif __debug__:\n\t\tprint (\"Resizing image: %s (size:%ix%i)\" % (input_file, size[0], size[1]))\n\tim = Image.open(input_file)\n\tresult = im.resize(size, Image.ANTIALIAS)\n\tresult.save(output_file)", "def resize_and_save(filename, output_dir, size=SIZE):\n ima...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle step to setup using device WiFi information.
async def async_step_wifi(self, info: Optional[dict] = None): errors = {} if info is not None: try: serial, credential, device_type = get_mqtt_info_from_wifi_info( info[CONF_SSID], info[CONF_PASSWORD] ) except DysonFailedToParse...
[ "def setup_class(self):\n self.dut = self.android_devices[0]\n req_params = dir(VPN_PARAMS)\n req_params = [\n x for x in req_params if not x.startswith(\"__\")\n ]\n opt_params = [\"wifi_network\", \"vpn_cert_country\", \"vpn_cert_org\"]\n self.unpack_userparams...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds the audio bar controls
def build_controls(self): controlSizer = wx.BoxSizer(wx.HORIZONTAL) btnData = [{'bitmap':'player_pause.png', 'handler':self.on_pause, 'name':'pause'}, {'bitmap':'player_stop.png', 'handler':self.on_stop, 'name':'stop'}] for btn...
[ "def build_controls(self, controlSizer):\r\n self.buttons['prev'] = self.build_btn(\r\n png='player_prev.png',\r\n handler=self.on_prev,\r\n title=_(\"Previous phrase\"),\r\n name='prev',\r\n builder=buttons.GenBitmapButton,\r\n sizer=controlS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates playback slider and track counter
def on_update_playback(self, event): try: offset = self.mplayer.GetTimePos() except: return print offset mod_off = str(offset)[-1] if mod_off == '0': print "mod_off" offset = int(offset) self.playbackSlider.SetValue(offs...
[ "def on_update_playback(self, event):\r\n\r\n if not self.playbackTimer.IsRunning():\r\n return\r\n\r\n try:\r\n offset = self.mplayer.GetTimePos()\r\n except:\r\n return\r\n\r\n if offset is None:\r\n return\r\n\r\n mod_off = str(offset...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Waits for process to be finished asynchronously and times out if process not returns within given time
async def async_wait_for_process(loop, process: psutil.Process, timeout): try: await asyncio.wait_for(loop.run_in_executor(None, process.wait), timeout=timeout) except asyncio.exceptions.TimeoutError as e: raise e
[ "def timeout_wait(self, process, timeout = 0):\n if timeout is 0:\n if 'timeout' in self.info:\n timeout = self.info['timeout']\n else:\n timeout = 3\n t0 = time.time()\n delay = min(0.1, timeout)\n while True:\n time.sleep(delay)\n returncode = process.poll()\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the given logServer as an xmlrpc server (forever).
def startServer(logServer, host="localhost", ports=(globalconst.DEFAULTPORT_XMLRPC,), readyMsg=True): # v0.3.0: The order of host,ports has changed for consistency # warn: if type(host) in (tuple,list) or type(ports) in (str,str): msg = "Unexpected host or ports type. Note: The argument order in startServer has ch...
[ "def run_server():\n\n server = socketserver.UDPServer(('0.0.0.0', port), SyslogHandler)\n server.serve_forever()", "def _start_logserver(self):\n\n self._logserver_httpd = HTTPServer(\n (self._logserver_ip, int(self._logserver_port)), LogServer\n )\n self._lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The OpenJDK download URL appropriate for the current machine.
def OpenJDK_download_url(self): system_arch = self.tools.host_arch # use a 32bit JDK if using 32bit Python on 64bit hardware if self.tools.is_32bit_python and self.tools.host_arch == "aarch64": system_arch = "armv7l" try: platform, arch, extension = { ...
[ "def resolved_download_url(self) -> str:\n arch = machine()\n return self.download_url.format(\n Arch=arch, Architecture=arch, Name=self.name,\n System=system_name(), Version=self.version)", "def download_url(self) -> str:\n return pulumi.get(self, \"download_url\")", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a JDK's version from a path by running ``/bin/javac``. This will fail if the path contains a JRE instead of a JDK.
def version_from_path(cls, tools: ToolCache, java_path: str | Path) -> str: output = tools.subprocess.check_output( [ os.fsdecode(Path(java_path) / "bin" / "javac"), "-version", ], ) # javac's output should look like "javac 17.0.X\n" ...
[ "def get_jdk_in_path():\n return get_java_binary_version('javac')", "def get_jre_in_path():\n return get_java_binary_version('java')", "def get_jdk(prefs, version):\n jdk_java_home = get_pref(prefs, 'jdk%d' % version, lambda: sanitize_input(\"Enter the path for JAVA_HOME for a JDK%d compiler (blank to ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify that a Java JDK exists. If ``JAVA_HOME`` is set, try that version. If it is a JRE, or its not a Java JDK, download one. On macOS, also try invoking /usr/libexec/java_home. If that location points to a Java JDK, use it. Otherwise, download a JDK from OpenJDK and unpack it into the briefcase data directory.
def verify_install(cls, tools: ToolCache, install: bool = True, **kwargs) -> JDK: # short circuit since already verified and available if hasattr(tools, "java"): return tools.java java = None install_message = None if java_home := tools.os.environ.get("JAVA_HOME", "...
[ "def checkAndInstallJavaSDK():\n\tcheckOS()\n\ttry:\n\t\tstatus = os.system(\"java -version\")\n\texcept OSError as e:\n\t\tprint >>sys.stderr, \"Error with the command\", e\n\n\tif (status == NOT_INSTALLED or status == NOT_INSTALLED_WINDOWS or status == REQUESTING_INSTALL):\n\t\tprint \"Java SDK is not installed o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download and install a JDK.
def install(self): jdk_zip_path = self.tools.download.file( url=self.OpenJDK_download_url, download_path=self.tools.base_path, role=f"Java {self.JDK_MAJOR_VER} JDK", ) with self.tools.input.wait_bar("Installing OpenJDK..."): try: s...
[ "def downloadAndInstallJavaSDK():\n\tprint \"Downloading Java SDK...\"\n\tif sys.platform=='win32':\n\t\turl = \"http://download.oracle.com/otn-pub/java/jdk/8u102-b14/jdk-8u102-windows-i586.exe\"\n\t\texeFile = wget.download(url)\n\t\tprint \"Download complete.\"\n\t\tfolder = extractWindowsFolder(exeFile)\n\t\tpri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the words of a string.
def words(s): return (normalize(w) for w in _words_re.findall(s))
[ "def allWordsFromString(str):\n return set(re.findall(\"\\w+\", str.lower()))", "def words(self, text):\n return re.findall(r'\\w+', text)", "def extract_words(string):\n l = []\n word = ''\n for c in string+' ':\n if c.isalpha():\n word += c\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The frames contained in this sequence. This is on ordered set for fast lookup
def frames(self) -> Set[int]: return self._frames
[ "def getFrames(self):\r\n frames = self.frames\r\n self.frames = []\r\n return frames", "def _get_frames(self):\n return [img.frame for img in self if img.frame is not None]", "def frames(self):\n if self._frames is None:\n self.load()\n return self._frames",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The order representaion of frames
def ordered(self) -> Tuple[int]: return tuple(sorted(self.frames))
[ "def frame(self):\n return self.head", "def _current_frames(): # real signature unknown; restored from __doc__\n return {}", "def frames(self) -> Optional[Tuple[int, ...]]:\n return self._frames", "def shape_elements_order(self) -> List[str]:\n return [\"channels\", \"height\", \"width...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is the composition nondecreasing in argument idx?
def is_incr(self, idx): return self.args[0].is_positive()
[ "def is_incr(self, idx):\n return False", "def mask_unique_of_sorted(idx):\n duplicates = idx == np.roll(idx, 1)\n duplicates |= idx == np.roll(idx, -1)\n return duplicates", "def is_nondecreasing_vec(x):\n return jnp.all(jnp.diff(x) >= 0)", "def cyclic_index_i_minus_1(i):\n return i - ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the function rejects an idx_col parameter that is not a string or None
def test_stochatreat_input_idx_col_str(correct_params): idx_col_not_str = 0 with pytest.raises(TypeError): stochatreat( data=correct_params["data"], block_cols=["block"], treats=correct_params["treat"], idx_col=idx_col_not_str, probs=correct_pa...
[ "def is_valid_index(idx, axis):\n if not (isinstance(idx, int) or isinstance(idx, str) or isinstance(idx, slice)):\n raise Exception(\n \"Only string, slice, or integer indices are supported, depending on whether your DataFrame is in row or column mode!\"\n )\n if axis == Axis.row:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the function's output contains the `treat` column
def test_stochatreat_output_treat_col(treatments_dict): treatments_df = treatments_dict["treatments"] assert "treat" in treatments_df.columns, "Treatment column is missing"
[ "def test_stochatreat_output_treat_col_dtype(treatments_dict):\n treatments_df = treatments_dict[\"treatments\"]\n assert treatments_df[\"treat\"].dtype == np.int64, \"Treatment column is missing\"", "def test_stochatreat_output_idx_col(treatments_dict):\n treatments_df = treatments_dict[\"treatments\"]\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }