code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def time_limited(limit_seconds, iterable): """ Yield items from *iterable* until *limit_seconds* have passed. >>> from time import sleep >>> def generator(): ... yield 1 ... yield 2 ... sleep(0.2) ... yield 3 >>> iterable = generator() >>> list(time_limited(0.1, ...
Yield items from *iterable* until *limit_seconds* have passed. >>> from time import sleep >>> def generator(): ... yield 1 ... yield 2 ... sleep(0.2) ... yield 3 >>> iterable = generator() >>> list(time_limited(0.1, iterable)) [1, 2] Note that the time is checke...
Below is the the instruction that describes the task: ### Input: Yield items from *iterable* until *limit_seconds* have passed. >>> from time import sleep >>> def generator(): ... yield 1 ... yield 2 ... sleep(0.2) ... yield 3 >>> iterable = generator() >>> list(time...
def copy_channel(self, channel, owner, to_channel): ''' Tag all files in channel <channel> also as channel <to_channel> :param channel: channel to copy :param owner: Perform this operation on all packages of this user :param to_channel: Destination name (may be a channe...
Tag all files in channel <channel> also as channel <to_channel> :param channel: channel to copy :param owner: Perform this operation on all packages of this user :param to_channel: Destination name (may be a channel that already exists)
Below is the the instruction that describes the task: ### Input: Tag all files in channel <channel> also as channel <to_channel> :param channel: channel to copy :param owner: Perform this operation on all packages of this user :param to_channel: Destination name (may be a channel t...
def _diagram_canvas_default(self): """ Trait initialiser """ canvas = Canvas() for tool in self.tools: canvas.tools.append(tool(canvas)) return canvas
Trait initialiser
Below is the the instruction that describes the task: ### Input: Trait initialiser ### Response: def _diagram_canvas_default(self): """ Trait initialiser """ canvas = Canvas() for tool in self.tools: canvas.tools.append(tool(canvas)) return canvas
def gen_challenge(self, state): """returns the next challenge and increments the seed and index in the state. :param state: the state to use for generating the challenge. will verify the integrity of the state object before using it to generate a challenge. it will then modify...
returns the next challenge and increments the seed and index in the state. :param state: the state to use for generating the challenge. will verify the integrity of the state object before using it to generate a challenge. it will then modify the state by incrementing the seed ...
Below is the the instruction that describes the task: ### Input: returns the next challenge and increments the seed and index in the state. :param state: the state to use for generating the challenge. will verify the integrity of the state object before using it to generate a chall...
def evaluaterforces(Pot,R,z,phi=None,t=0.,v=None): """ NAME: evaluaterforces PURPOSE: convenience function to evaluate a possible sum of potentials INPUT: Pot - a potential or list of potentials R - cylindrical Galactocentric distance (can be Quantity) z - dista...
NAME: evaluaterforces PURPOSE: convenience function to evaluate a possible sum of potentials INPUT: Pot - a potential or list of potentials R - cylindrical Galactocentric distance (can be Quantity) z - distance above the plane (can be Quantity) phi - azimuth (op...
Below is the the instruction that describes the task: ### Input: NAME: evaluaterforces PURPOSE: convenience function to evaluate a possible sum of potentials INPUT: Pot - a potential or list of potentials R - cylindrical Galactocentric distance (can be Quantity) z -...
async def seen(self, tick, source=None): ''' Update the .seen interval and optionally a source specific seen node. ''' await self.set('.seen', tick) if source is not None: seen = await self.snap.addNode('meta:seen', (source, self.ndef)) await seen.set('.s...
Update the .seen interval and optionally a source specific seen node.
Below is the the instruction that describes the task: ### Input: Update the .seen interval and optionally a source specific seen node. ### Response: async def seen(self, tick, source=None): ''' Update the .seen interval and optionally a source specific seen node. ''' await self.set(...
def isbn(self, fmt: Optional[ISBNFormat] = None, locale: str = 'en') -> str: """Generate ISBN for current locale. To change ISBN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.ISBNFormat` :param fmt: ISBN format. :param l...
Generate ISBN for current locale. To change ISBN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.ISBNFormat` :param fmt: ISBN format. :param locale: Locale code. :return: ISBN. :raises NonEnumerableError: if fmt is not enum ISB...
Below is the the instruction that describes the task: ### Input: Generate ISBN for current locale. To change ISBN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.ISBNFormat` :param fmt: ISBN format. :param locale: Locale code. :ret...
def create_process(self, service, agent=None, title=None, mode=None, service_version=None, **kwargs): ''' create_process(self, service, agent=None, title=None, mode=None, service_version=None, **kwargs) Registers a new process or processes :Parameters: * *service* (`string`) --...
create_process(self, service, agent=None, title=None, mode=None, service_version=None, **kwargs) Registers a new process or processes :Parameters: * *service* (`string`) -- Service which process will be started * *agent* (`string`) -- The service identifier (e.g shell_command) ...
Below is the the instruction that describes the task: ### Input: create_process(self, service, agent=None, title=None, mode=None, service_version=None, **kwargs) Registers a new process or processes :Parameters: * *service* (`string`) -- Service which process will be started * *age...
def _shutdown(self, manual): """ Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown """ if self._ssl is None: return while True: result = libssl.SSL_s...
Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown
Below is the the instruction that describes the task: ### Input: Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown ### Response: def _shutdown(self, manual): """ Shuts down the TLS session and t...
def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() ...
Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures.
Below is the the instruction that describes the task: ### Input: Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. ### Response: def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: Windo...
async def start_all_linking(self, linkcode, group, address=None): """Start the All-Linking process with the IM and device.""" _LOGGING.info('Starting the All-Linking process') if address: linkdevice = self.plm.devices[Address(address).id] if not linkdevice: ...
Start the All-Linking process with the IM and device.
Below is the the instruction that describes the task: ### Input: Start the All-Linking process with the IM and device. ### Response: async def start_all_linking(self, linkcode, group, address=None): """Start the All-Linking process with the IM and device.""" _LOGGING.info('Starting the All-Linking ...
def get_messages(self, domain): """ Returns all valid messages after operation. @type domain: str @rtype: dict """ if domain not in self.domains: raise ValueError('Invalid domain: {0}'.format(domain)) if domain not in self.messages or 'all' not in sel...
Returns all valid messages after operation. @type domain: str @rtype: dict
Below is the the instruction that describes the task: ### Input: Returns all valid messages after operation. @type domain: str @rtype: dict ### Response: def get_messages(self, domain): """ Returns all valid messages after operation. @type domain: str @rtype: dict ...
async def evaluate(self): """Evaluate the query observer. :param return_emitted: True if the emitted diffs should be returned (testing only) """ @database_sync_to_async def remove_subscribers(): models.Observer.subscribers.through.objects.filter( obs...
Evaluate the query observer. :param return_emitted: True if the emitted diffs should be returned (testing only)
Below is the the instruction that describes the task: ### Input: Evaluate the query observer. :param return_emitted: True if the emitted diffs should be returned (testing only) ### Response: async def evaluate(self): """Evaluate the query observer. :param return_emitted: True if the emitt...
def use_plenary_asset_composition_view(self): """Pass through to provider AssetCompositionSession.use_plenary_asset_composition_view""" self._object_views['asset_composition'] = PLENARY # self._get_provider_session('asset_composition_session') # To make sure the session is tracked for se...
Pass through to provider AssetCompositionSession.use_plenary_asset_composition_view
Below is the the instruction that describes the task: ### Input: Pass through to provider AssetCompositionSession.use_plenary_asset_composition_view ### Response: def use_plenary_asset_composition_view(self): """Pass through to provider AssetCompositionSession.use_plenary_asset_composition_view""" ...
def check_webhook_secret(app_configs=None, **kwargs): """ Check that DJSTRIPE_WEBHOOK_SECRET looks correct """ from . import settings as djstripe_settings messages = [] secret = djstripe_settings.WEBHOOK_SECRET if secret and not secret.startswith("whsec_"): messages.append( checks.Warning( "DJSTRIPE_W...
Check that DJSTRIPE_WEBHOOK_SECRET looks correct
Below is the the instruction that describes the task: ### Input: Check that DJSTRIPE_WEBHOOK_SECRET looks correct ### Response: def check_webhook_secret(app_configs=None, **kwargs): """ Check that DJSTRIPE_WEBHOOK_SECRET looks correct """ from . import settings as djstripe_settings messages = [] secret = d...
async def _create_proxy_connection(self, req, *args, **kwargs): """ args, kwargs can contain different elements (traces, timeout,...) depending on aiohttp version """ if req.proxy.scheme == 'http': return await super()._create_proxy_connection(req, *args, **kwargs) ...
args, kwargs can contain different elements (traces, timeout,...) depending on aiohttp version
Below is the the instruction that describes the task: ### Input: args, kwargs can contain different elements (traces, timeout,...) depending on aiohttp version ### Response: async def _create_proxy_connection(self, req, *args, **kwargs): """ args, kwargs can contain different elements (trac...
def _invert(h): "Cheap function to invert a hash." i = {} for k,v in h.items(): i[v] = k return i
Cheap function to invert a hash.
Below is the the instruction that describes the task: ### Input: Cheap function to invert a hash. ### Response: def _invert(h): "Cheap function to invert a hash." i = {} for k,v in h.items(): i[v] = k return i
def slaves(self): '''The list of slave managers of this manager, if any. This information can also be found by listing the children of this node that are of type @ref Manager. ''' with self._mutex: if not self._slaves: self._slaves = [c for c in self...
The list of slave managers of this manager, if any. This information can also be found by listing the children of this node that are of type @ref Manager.
Below is the the instruction that describes the task: ### Input: The list of slave managers of this manager, if any. This information can also be found by listing the children of this node that are of type @ref Manager. ### Response: def slaves(self): '''The list of slave managers of this ...
def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit: """Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2) """ circ = Circuit() for qubits in args: circ += gate.relabel(qubits)...
Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2)
Below is the the instruction that describes the task: ### Input: Applies the same gate all input qubits in the argument list. >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]]) >>> print(circ) H(0) H(1) H(2) ### Response: def map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit: """Applies...
def gapfill(model, universal=None, lower_bound=0.05, penalties=None, demand_reactions=True, exchange_reactions=False, iterations=1): """Perform gapfilling on a model. See documentation for the class GapFiller. Parameters ---------- model : cobra.Model The model to p...
Perform gapfilling on a model. See documentation for the class GapFiller. Parameters ---------- model : cobra.Model The model to perform gap filling on. universal : cobra.Model, None A universal model with reactions that can be used to complete the model. Only gapfill consi...
Below is the the instruction that describes the task: ### Input: Perform gapfilling on a model. See documentation for the class GapFiller. Parameters ---------- model : cobra.Model The model to perform gap filling on. universal : cobra.Model, None A universal model with reactio...
def link(self, source, target): 'creates a hard link `target -> source` (e.g. ln source target)' return self.operations('link', target.decode(self.encoding), source.decode(self.encoding))
creates a hard link `target -> source` (e.g. ln source target)
Below is the the instruction that describes the task: ### Input: creates a hard link `target -> source` (e.g. ln source target) ### Response: def link(self, source, target): 'creates a hard link `target -> source` (e.g. ln source target)' return self.operations('link', target.decode(self.encoding)...
def run_edisgo_pool(ding0_file_list, run_args_opt, workers=mp.cpu_count(), worker_lifetime=1): """ Use python multiprocessing toolbox for parallelization Several grids are analyzed in parallel. Parameters ---------- ding0_file_list : list Ding0 grid data file names ...
Use python multiprocessing toolbox for parallelization Several grids are analyzed in parallel. Parameters ---------- ding0_file_list : list Ding0 grid data file names run_args_opt : list eDisGo options, see :func:`run_edisgo_basic` and :func:`run_edisgo_twice` workers: ...
Below is the the instruction that describes the task: ### Input: Use python multiprocessing toolbox for parallelization Several grids are analyzed in parallel. Parameters ---------- ding0_file_list : list Ding0 grid data file names run_args_opt : list eDisGo options, see :func:...
def postinit(self, expr=None, globals=None, locals=None): """Do some setup after initialisation. :param expr: The expression to be executed. :type expr: NodeNG or None :param globals:The globals dictionary to execute with. :type globals: NodeNG or None :param locals: T...
Do some setup after initialisation. :param expr: The expression to be executed. :type expr: NodeNG or None :param globals:The globals dictionary to execute with. :type globals: NodeNG or None :param locals: The locals dictionary to execute with. :type locals: NodeNG or...
Below is the the instruction that describes the task: ### Input: Do some setup after initialisation. :param expr: The expression to be executed. :type expr: NodeNG or None :param globals:The globals dictionary to execute with. :type globals: NodeNG or None :param locals: T...
def push_tx(self, crypto, tx_hex): """ This method is untested. """ url = "%s/pushtx" % self.base_url return self.post_url(url, {'hex': tx_hex}).content
This method is untested.
Below is the the instruction that describes the task: ### Input: This method is untested. ### Response: def push_tx(self, crypto, tx_hex): """ This method is untested. """ url = "%s/pushtx" % self.base_url return self.post_url(url, {'hex': tx_hex}).content
def calculate_input(self, buffer): """ Calculate how many keystrokes were used in triggering this phrase. """ # TODO: This function is unused? if TriggerMode.ABBREVIATION in self.modes: if self._should_trigger_abbreviation(buffer): if self.immediate: ...
Calculate how many keystrokes were used in triggering this phrase.
Below is the the instruction that describes the task: ### Input: Calculate how many keystrokes were used in triggering this phrase. ### Response: def calculate_input(self, buffer): """ Calculate how many keystrokes were used in triggering this phrase. """ # TODO: This function is un...
def quota(ip=None): """Check your quota.""" # TODO: Add arbitrary user defined IP check url = 'http://www.random.org/quota/?format=plain' data = urlopen(url) credit = int(data.read().strip()) if data.code == 200: return credit else: return "ERROR: Server responded with code %...
Check your quota.
Below is the the instruction that describes the task: ### Input: Check your quota. ### Response: def quota(ip=None): """Check your quota.""" # TODO: Add arbitrary user defined IP check url = 'http://www.random.org/quota/?format=plain' data = urlopen(url) credit = int(data.read().strip()) if...
def get_long_description(): """Grok the readme, turn it into whine (rst).""" root_path = get_root_path() readme_path = os.path.join(root_path, "README.md") try: import pypandoc return pypandoc.convert(readme_path, "rst").strip() except ImportError: return "Cloudsmith CLI"
Grok the readme, turn it into whine (rst).
Below is the the instruction that describes the task: ### Input: Grok the readme, turn it into whine (rst). ### Response: def get_long_description(): """Grok the readme, turn it into whine (rst).""" root_path = get_root_path() readme_path = os.path.join(root_path, "README.md") try: import ...
def HsvToRgb(h, s, v): '''Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as an (r, g, b) tuple in the range: r...
Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], ...
Below is the the instruction that describes the task: ### Input: Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as a...
def _setup_stats(self): ''' Sets up the stats collection ''' self.stats_dict = {} redis_conn = redis.Redis(host=self.settings['REDIS_HOST'], port=self.settings['REDIS_PORT'], db=self.settings.get('REDIS_DB')) ...
Sets up the stats collection
Below is the the instruction that describes the task: ### Input: Sets up the stats collection ### Response: def _setup_stats(self): ''' Sets up the stats collection ''' self.stats_dict = {} redis_conn = redis.Redis(host=self.settings['REDIS_HOST'], ...
def check_namespace(namespace_id): """ Verify that a namespace ID is well-formed >>> check_namespace(123) False >>> check_namespace(None) False >>> check_namespace('') False >>> check_namespace('abcd') True >>> check_namespace('Abcd') False >>> check_namespace('a+bcd...
Verify that a namespace ID is well-formed >>> check_namespace(123) False >>> check_namespace(None) False >>> check_namespace('') False >>> check_namespace('abcd') True >>> check_namespace('Abcd') False >>> check_namespace('a+bcd') False >>> check_namespace('.abcd') ...
Below is the the instruction that describes the task: ### Input: Verify that a namespace ID is well-formed >>> check_namespace(123) False >>> check_namespace(None) False >>> check_namespace('') False >>> check_namespace('abcd') True >>> check_namespace('Abcd') False >>> ...
def builds(self): """Instance depends on the API version: * 2018-02-01-preview: :class:`BuildsOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.BuildsOperations>` """ api_version = self._get_api_version('builds') if api_version == '2018-02-01-preview': ...
Instance depends on the API version: * 2018-02-01-preview: :class:`BuildsOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.BuildsOperations>`
Below is the the instruction that describes the task: ### Input: Instance depends on the API version: * 2018-02-01-preview: :class:`BuildsOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.BuildsOperations>` ### Response: def builds(self): """Instance depends on the API vers...
def deprecate_kwarg(old_arg_name, new_arg_name, mapping=None, stacklevel=2): """ Decorator to deprecate a keyword argument of a function. Parameters ---------- old_arg_name : str Name of argument in function to deprecate new_arg_name : str or None Name of preferred argument in f...
Decorator to deprecate a keyword argument of a function. Parameters ---------- old_arg_name : str Name of argument in function to deprecate new_arg_name : str or None Name of preferred argument in function. Use None to raise warning that ``old_arg_name`` keyword is deprecated. ...
Below is the the instruction that describes the task: ### Input: Decorator to deprecate a keyword argument of a function. Parameters ---------- old_arg_name : str Name of argument in function to deprecate new_arg_name : str or None Name of preferred argument in function. Use None to...
def set_power_state(self, desired_state): """Set power state of this node :param node: Ironic node one of :class:`ironic.db.models.Node` :raises: InvalidParameterValue if required seamicro parameters are missing. :raises: UcsOperationError on an error from U...
Set power state of this node :param node: Ironic node one of :class:`ironic.db.models.Node` :raises: InvalidParameterValue if required seamicro parameters are missing. :raises: UcsOperationError on an error from UcsHandle Client. :returns: Power state of...
Below is the the instruction that describes the task: ### Input: Set power state of this node :param node: Ironic node one of :class:`ironic.db.models.Node` :raises: InvalidParameterValue if required seamicro parameters are missing. :raises: UcsOperationError on...
def logs_update(self): """ Function updates logs. """ Gdk.threads_enter() if not self.debugging: self.debugging = True self.debug_btn.set_label('Info logs') else: self.debugging = False self.debug_btn.set_label('Debug logs')...
Function updates logs.
Below is the the instruction that describes the task: ### Input: Function updates logs. ### Response: def logs_update(self): """ Function updates logs. """ Gdk.threads_enter() if not self.debugging: self.debugging = True self.debug_btn.set_label('Info...
def check_positive(value, strict=False): """ Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed """ if not strict and value < 0: raise ValueError(...
Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed
Below is the the instruction that describes the task: ### Input: Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed ### Response: def check_positive(value, strict=Fa...
def dag_state(args): """ Returns the state of a DagRun at the command line. >>> airflow dag_state tutorial 2015-01-01T00:00:00.000000 running """ dag = get_dag(args) dr = DagRun.find(dag.dag_id, execution_date=args.execution_date) print(dr[0].state if len(dr) > 0 else None)
Returns the state of a DagRun at the command line. >>> airflow dag_state tutorial 2015-01-01T00:00:00.000000 running
Below is the the instruction that describes the task: ### Input: Returns the state of a DagRun at the command line. >>> airflow dag_state tutorial 2015-01-01T00:00:00.000000 running ### Response: def dag_state(args): """ Returns the state of a DagRun at the command line. >>> airflow dag_state t...
def calculate(self, T, P, zs, ws, method): r'''Method to calculate surface tension of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. ...
r'''Method to calculate surface tension of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : fl...
Below is the the instruction that describes the task: ### Input: r'''Method to calculate surface tension of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` ...
def _update_dprx(self): """Update `dprx`.""" if 'beta' in self.freeparams: for r in range(self.nsites): self.dprx['beta'][r] = self.prx[r] * (self.ln_pi_codon[r] - scipy.dot(self.ln_pi_codon[r], self.prx[r])) if 'eta' in self.freeparams: ...
Update `dprx`.
Below is the the instruction that describes the task: ### Input: Update `dprx`. ### Response: def _update_dprx(self): """Update `dprx`.""" if 'beta' in self.freeparams: for r in range(self.nsites): self.dprx['beta'][r] = self.prx[r] * (self.ln_pi_codon[r] ...
def __select (self, iwtd, owtd, ewtd, timeout=None): """This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). """ ...
This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize).
Below is the the instruction that describes the task: ### Input: This is a wrapper around select.select() that ignores signals. If select.select raises a select.error exception and errno is an EINTR error then it is ignored. Mainly this is used to ignore sigwinch (terminal resize). ### Respo...
def dimension(self, name, copy=True): """ Returns the requested :class:`~hypercube.dims.Dimension` object Parameters ---------- name : str Name of the :class:`~hypercube.dims.Dimension` object copy : boolean Returns a copy of the :class:`~hypercub...
Returns the requested :class:`~hypercube.dims.Dimension` object Parameters ---------- name : str Name of the :class:`~hypercube.dims.Dimension` object copy : boolean Returns a copy of the :class:`~hypercube.dims.Dimension` object if True (Default value = True) ...
Below is the the instruction that describes the task: ### Input: Returns the requested :class:`~hypercube.dims.Dimension` object Parameters ---------- name : str Name of the :class:`~hypercube.dims.Dimension` object copy : boolean Returns a copy of the :class...
def cause_info(self, mechanism, purview): """Return the cause information for a mechanism over a purview.""" return repertoire_distance( Direction.CAUSE, self.cause_repertoire(mechanism, purview), self.unconstrained_cause_repertoire(purview) )
Return the cause information for a mechanism over a purview.
Below is the the instruction that describes the task: ### Input: Return the cause information for a mechanism over a purview. ### Response: def cause_info(self, mechanism, purview): """Return the cause information for a mechanism over a purview.""" return repertoire_distance( Direction....
def calc_toa_gain_offset(meta): """ Compute (gain, offset) tuples for each band of the specified image metadata """ # Set satellite index to look up cal factors sat_index = meta['satid'].upper() + "_" + meta['bandid'].upper() # Set scale for at sensor radiance # Eq is: # L = GAIN * DN *...
Compute (gain, offset) tuples for each band of the specified image metadata
Below is the the instruction that describes the task: ### Input: Compute (gain, offset) tuples for each band of the specified image metadata ### Response: def calc_toa_gain_offset(meta): """ Compute (gain, offset) tuples for each band of the specified image metadata """ # Set satellite index to loo...
def create_system(self, new_machine_id=False): """ Create the machine via the API """ client_hostname = determine_hostname() machine_id = generate_machine_id(new_machine_id) branch_info = self.branch_info if not branch_info: return False remo...
Create the machine via the API
Below is the the instruction that describes the task: ### Input: Create the machine via the API ### Response: def create_system(self, new_machine_id=False): """ Create the machine via the API """ client_hostname = determine_hostname() machine_id = generate_machine_id(new_mac...
def officers(self, num, **kwargs): """Search for a company's registered officers by company number. Args: num (str): Company number to search on. kwargs (dict): additional keywords passed into requests.session.get *params* keyword. """ baseuri = self._BAS...
Search for a company's registered officers by company number. Args: num (str): Company number to search on. kwargs (dict): additional keywords passed into requests.session.get *params* keyword.
Below is the the instruction that describes the task: ### Input: Search for a company's registered officers by company number. Args: num (str): Company number to search on. kwargs (dict): additional keywords passed into requests.session.get *params* keyword. ### Response: d...
def line(x_fn, y_fn, *, options={}, **interact_params): """ Generates an interactive line chart that allows users to change the parameters of the inputs x_fn and y_fn. Args: x_fn (Array | (*args -> Array str | Array int | Array float)): If array, uses array values for x-coordinates....
Generates an interactive line chart that allows users to change the parameters of the inputs x_fn and y_fn. Args: x_fn (Array | (*args -> Array str | Array int | Array float)): If array, uses array values for x-coordinates. If function, must take parameters to interact with and...
Below is the the instruction that describes the task: ### Input: Generates an interactive line chart that allows users to change the parameters of the inputs x_fn and y_fn. Args: x_fn (Array | (*args -> Array str | Array int | Array float)): If array, uses array values for x-coordinates...
def serialize(self, serializable: Optional[Union[SerializableType, List[SerializableType]]]) \ -> PrimitiveJsonType: """ Serializes the given serializable object or collection of serializable objects. :param serializable: the object or objects to serialize :return: a serializ...
Serializes the given serializable object or collection of serializable objects. :param serializable: the object or objects to serialize :return: a serialization of the given object
Below is the the instruction that describes the task: ### Input: Serializes the given serializable object or collection of serializable objects. :param serializable: the object or objects to serialize :return: a serialization of the given object ### Response: def serialize(self, serializable: Optio...
def update(self): """Update object properties.""" current_time = int(time.time()) last_refresh = 0 if self._last_refresh is None else self._last_refresh if current_time >= (last_refresh + self._refresh_rate): self.get_cameras_properties() self.get_ambient_sensor_...
Update object properties.
Below is the the instruction that describes the task: ### Input: Update object properties. ### Response: def update(self): """Update object properties.""" current_time = int(time.time()) last_refresh = 0 if self._last_refresh is None else self._last_refresh if current_time >= (last...
def transformer_base_vq_ada_32ex_packed(): """Set of hyperparameters for lm1b packed following tpu params.""" hparams = transformer_base_v2() expert_utils.update_hparams_for_vq_gating(hparams) hparams.moe_num_experts = 32 hparams.gating_type = "vq" # this gives us a batch size of 16 because each seq is len ...
Set of hyperparameters for lm1b packed following tpu params.
Below is the the instruction that describes the task: ### Input: Set of hyperparameters for lm1b packed following tpu params. ### Response: def transformer_base_vq_ada_32ex_packed(): """Set of hyperparameters for lm1b packed following tpu params.""" hparams = transformer_base_v2() expert_utils.update_hparams...
def _append_national_number(self, national_number): """Combines the national number with any prefix (IDD/+ and country code or national prefix) that was collected. A space will be inserted between them if the current formatting template indicates this to be suitable. """ ...
Combines the national number with any prefix (IDD/+ and country code or national prefix) that was collected. A space will be inserted between them if the current formatting template indicates this to be suitable.
Below is the the instruction that describes the task: ### Input: Combines the national number with any prefix (IDD/+ and country code or national prefix) that was collected. A space will be inserted between them if the current formatting template indicates this to be suitable. ### Response: ...
def Verify(self, mempool): """ Verify the transaction. Args: mempool: Returns: bool: True if verified. False otherwise. """ if not super(ClaimTransaction, self).Verify(mempool): return False # wat does this do # get a...
Verify the transaction. Args: mempool: Returns: bool: True if verified. False otherwise.
Below is the the instruction that describes the task: ### Input: Verify the transaction. Args: mempool: Returns: bool: True if verified. False otherwise. ### Response: def Verify(self, mempool): """ Verify the transaction. Args: mempool...
def reintegrate(self, fullPointList): ''' Integrates the pitch values of the accent into a larger pitch contour ''' # Erase the original region of the accent fullPointList = _deletePoints(fullPointList, self.minT, self.maxT) # Erase the new region of the accent ...
Integrates the pitch values of the accent into a larger pitch contour
Below is the the instruction that describes the task: ### Input: Integrates the pitch values of the accent into a larger pitch contour ### Response: def reintegrate(self, fullPointList): ''' Integrates the pitch values of the accent into a larger pitch contour ''' # Erase the origin...
def pitch(times, frequencies, midi=False, unvoiced=False, ax=None, **kwargs): '''Visualize pitch contours Parameters ---------- times : np.ndarray, shape=(n,) Sample times of frequencies frequencies : np.ndarray, shape=(n,) frequencies (in Hz) of the pitch contours. Voicing...
Visualize pitch contours Parameters ---------- times : np.ndarray, shape=(n,) Sample times of frequencies frequencies : np.ndarray, shape=(n,) frequencies (in Hz) of the pitch contours. Voicing is indicated by sign (positive for voiced, non-positive for non-voiced). ...
Below is the the instruction that describes the task: ### Input: Visualize pitch contours Parameters ---------- times : np.ndarray, shape=(n,) Sample times of frequencies frequencies : np.ndarray, shape=(n,) frequencies (in Hz) of the pitch contours. Voicing is indicated by...
def on_doctree_read(app, document): """ Hooks into Sphinx's ``doctree-read`` event. """ literal_blocks = uqbar.book.sphinx.collect_literal_blocks(document) cache_mapping = uqbar.book.sphinx.group_literal_blocks_by_cache_path(literal_blocks) node_mapping = {} use_cache = bool(app.config["uqba...
Hooks into Sphinx's ``doctree-read`` event.
Below is the the instruction that describes the task: ### Input: Hooks into Sphinx's ``doctree-read`` event. ### Response: def on_doctree_read(app, document): """ Hooks into Sphinx's ``doctree-read`` event. """ literal_blocks = uqbar.book.sphinx.collect_literal_blocks(document) cache_mapping = ...
def list_storage_accounts_sub(access_token, subscription_id): '''List the storage accounts in the specified subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body list of storage ac...
List the storage accounts in the specified subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body list of storage accounts.
Below is the the instruction that describes the task: ### Input: List the storage accounts in the specified subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body list of storage ac...
def PilToRgb(pil): '''Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % Co...
Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % Color.PilToRgb(0x0080ff) ...
Below is the the instruction that describes the task: ### Input: Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] ...
def build(self, builder): """Build XML object, return the root, this is a copy for consistency and testing""" params = dict(ODMVersion="1.3", FileType=self.filetype, CreationDateTime=self.creationdatetime, Originator=self.originator, ...
Build XML object, return the root, this is a copy for consistency and testing
Below is the the instruction that describes the task: ### Input: Build XML object, return the root, this is a copy for consistency and testing ### Response: def build(self, builder): """Build XML object, return the root, this is a copy for consistency and testing""" params = dict(ODMVersion="1.3", ...
def checkOptions(options, parser): """ Check options, throw parser.error() if something goes wrong """ if options.jobStore == None: parser.error("Specify --jobStore") defaultCategories = ["time", "clock", "wait", "memory"] if options.categories is None: options.categories = defaultC...
Check options, throw parser.error() if something goes wrong
Below is the the instruction that describes the task: ### Input: Check options, throw parser.error() if something goes wrong ### Response: def checkOptions(options, parser): """ Check options, throw parser.error() if something goes wrong """ if options.jobStore == None: parser.error("Specify -...
def run_program(self, command, working_directory=os.getcwd(), environment=None, cleanup_files=True, native_spec="-l cputype=intel"): """ Run a program through the grid, capturing the standard output. """ try: s = drmaa.Session() ...
Run a program through the grid, capturing the standard output.
Below is the the instruction that describes the task: ### Input: Run a program through the grid, capturing the standard output. ### Response: def run_program(self, command, working_directory=os.getcwd(), environment=None, cleanup_files=True, native_spec="-l cputype=intel"): ...
def area(self): r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice th...
r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to ...
Below is the the instruction that describes the task: ### Input: r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-...
def extract_header(msg_or_header): """Given a message or header, return the header.""" if not msg_or_header: return {} try: # See if msg_or_header is the entire message. h = msg_or_header['header'] except KeyError: try: # See if msg_or_header is just the heade...
Given a message or header, return the header.
Below is the the instruction that describes the task: ### Input: Given a message or header, return the header. ### Response: def extract_header(msg_or_header): """Given a message or header, return the header.""" if not msg_or_header: return {} try: # See if msg_or_header is the entire m...
def readinto(self, buf, *, start=0, end=None): """ Read into ``buf`` from the device. The number of bytes read will be the length of ``buf``. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buf[start:end]``. This will not cause an allocation like ...
Read into ``buf`` from the device. The number of bytes read will be the length of ``buf``. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buf[start:end]``. This will not cause an allocation like ``buf[start:end]`` will so it saves memory. :param byt...
Below is the the instruction that describes the task: ### Input: Read into ``buf`` from the device. The number of bytes read will be the length of ``buf``. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buf[start:end]``. This will not cause an allocation like ...
def parcor_stable(filt): """ Tests whether the given filter is stable or not by using the partial correlation coefficients (reflection coefficients) of the given filter. Parameters ---------- filt : A LTI filter as a LinearFilter object. Returns ------- A boolean that is true only when all corre...
Tests whether the given filter is stable or not by using the partial correlation coefficients (reflection coefficients) of the given filter. Parameters ---------- filt : A LTI filter as a LinearFilter object. Returns ------- A boolean that is true only when all correlation coefficients are inside th...
Below is the the instruction that describes the task: ### Input: Tests whether the given filter is stable or not by using the partial correlation coefficients (reflection coefficients) of the given filter. Parameters ---------- filt : A LTI filter as a LinearFilter object. Returns ------- A bool...
def _get_converter_module(sk_obj): """ Returns the module holding the conversion functions for a particular model). """ try: cv_idx = _converter_lookup[sk_obj.__class__] except KeyError: raise ValueError( "Transformer '%s' not supported; supported transformers are...
Returns the module holding the conversion functions for a particular model).
Below is the the instruction that describes the task: ### Input: Returns the module holding the conversion functions for a particular model). ### Response: def _get_converter_module(sk_obj): """ Returns the module holding the conversion functions for a particular model). """ try: cv...
def set_intersection(self, division, intersection): """Set intersection percentage of intersecting divisions.""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
Set intersection percentage of intersecting divisions.
Below is the the instruction that describes the task: ### Input: Set intersection percentage of intersecting divisions. ### Response: def set_intersection(self, division, intersection): """Set intersection percentage of intersecting divisions.""" IntersectRelationship.objects.filter( fr...
def import_attr(path): """ transform a python dotted path to the attr :param path: A dotted path to a python object or a python object :type path: :obj:`unicode` or :obj:`str` or anything :return: The python object pointed by the dotted path or the python object unchanged """ ...
transform a python dotted path to the attr :param path: A dotted path to a python object or a python object :type path: :obj:`unicode` or :obj:`str` or anything :return: The python object pointed by the dotted path or the python object unchanged
Below is the the instruction that describes the task: ### Input: transform a python dotted path to the attr :param path: A dotted path to a python object or a python object :type path: :obj:`unicode` or :obj:`str` or anything :return: The python object pointed by the dotted path or the pyth...
def mapping_get(index, doc_type, hosts=None, profile=None): ''' Retrieve mapping definition of index or index/type index Index for the mapping doc_type Name of the document type CLI example:: salt myminion elasticsearch.mapping_get testindex user ''' es = _get_inst...
Retrieve mapping definition of index or index/type index Index for the mapping doc_type Name of the document type CLI example:: salt myminion elasticsearch.mapping_get testindex user
Below is the the instruction that describes the task: ### Input: Retrieve mapping definition of index or index/type index Index for the mapping doc_type Name of the document type CLI example:: salt myminion elasticsearch.mapping_get testindex user ### Response: def mapping_ge...
def update_exc(exc, msg, before=True, separator="\n"): """ Adds additional text to an exception's error message. The new text will be added before the existing text by default; to append it after the original text, pass False to the `before` parameter. By default the old and new text will be separ...
Adds additional text to an exception's error message. The new text will be added before the existing text by default; to append it after the original text, pass False to the `before` parameter. By default the old and new text will be separated by a newline. If you wish to use a different separator, pa...
Below is the the instruction that describes the task: ### Input: Adds additional text to an exception's error message. The new text will be added before the existing text by default; to append it after the original text, pass False to the `before` parameter. By default the old and new text will be sep...
def _with_inline(func, admin_site, metadata_class, inline_class): """ Decorator for register function that adds an appropriate inline.""" def register(model_or_iterable, admin_class=None, **options): # Call the (bound) function we were given. # We have to assume it will be bound to admin_sit...
Decorator for register function that adds an appropriate inline.
Below is the the instruction that describes the task: ### Input: Decorator for register function that adds an appropriate inline. ### Response: def _with_inline(func, admin_site, metadata_class, inline_class): """ Decorator for register function that adds an appropriate inline.""" def register(model_or...
def expand_alias(self, line): """ Expand an alias in the command line Returns the provided command line, possibly with the first word (command) translated according to alias expansion rules. [ipython]|16> _ip.expand_aliases("np myfile.txt") <16> 'q:/opt/np/notepad++.ex...
Expand an alias in the command line Returns the provided command line, possibly with the first word (command) translated according to alias expansion rules. [ipython]|16> _ip.expand_aliases("np myfile.txt") <16> 'q:/opt/np/notepad++.exe myfile.txt'
Below is the the instruction that describes the task: ### Input: Expand an alias in the command line Returns the provided command line, possibly with the first word (command) translated according to alias expansion rules. [ipython]|16> _ip.expand_aliases("np myfile.txt") <...
def write(self, label, index): """ Saves a new label, index mapping to the cache. Raises a RuntimeError on a conflict. """ if label in self.cache: if self.cache[label] != index: error_message = 'cache_conflict on label: {} with index: {}\ncache dump: {...
Saves a new label, index mapping to the cache. Raises a RuntimeError on a conflict.
Below is the the instruction that describes the task: ### Input: Saves a new label, index mapping to the cache. Raises a RuntimeError on a conflict. ### Response: def write(self, label, index): """ Saves a new label, index mapping to the cache. Raises a RuntimeError on a conflict. ...
def send_signal(self, s): """ Send a signal to the daemon process. The signal must have been enabled using the ``signals`` parameter of :py:meth:`Service.__init__`. Otherwise, a ``ValueError`` is raised. """ self._get_signal_event(s) # Check if signal has been e...
Send a signal to the daemon process. The signal must have been enabled using the ``signals`` parameter of :py:meth:`Service.__init__`. Otherwise, a ``ValueError`` is raised.
Below is the the instruction that describes the task: ### Input: Send a signal to the daemon process. The signal must have been enabled using the ``signals`` parameter of :py:meth:`Service.__init__`. Otherwise, a ``ValueError`` is raised. ### Response: def send_signal(self, s): """...
def catch_osd_errors(conn, logger, args): """ Look for possible issues when checking the status of an OSD and report them back to the user. """ logger.info('checking OSD status...') status = osd_status_check(conn, args.cluster) osds = int(status.get('num_osds', 0)) up_osds = int(status.g...
Look for possible issues when checking the status of an OSD and report them back to the user.
Below is the the instruction that describes the task: ### Input: Look for possible issues when checking the status of an OSD and report them back to the user. ### Response: def catch_osd_errors(conn, logger, args): """ Look for possible issues when checking the status of an OSD and report them back...
def run(self): """主函数""" # try: self.fenum.write('\n') self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiDataType.h'), 'r') for idx, line in enumerate(self.fcpp): l = self.process_line(idx, line) self.f_data_type.write(l) ...
主函数
Below is the the instruction that describes the task: ### Input: 主函数 ### Response: def run(self): """主函数""" # try: self.fenum.write('\n') self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiDataType.h'), 'r') for idx, line in enumerate(self.fcpp): ...
def show_vmatrix(vm): ''' d = {1: {2: {22: 222}}, 3: {'a': 'b'}} vm = [[[222]], ['b']] show_vmatrix(vm) ''' unhandled = vm while(unhandled.__len__()>0): next_unhandled = [] for i in range(0,unhandled.__len__()): ele = unhandled[i] print(ele...
d = {1: {2: {22: 222}}, 3: {'a': 'b'}} vm = [[[222]], ['b']] show_vmatrix(vm)
Below is the the instruction that describes the task: ### Input: d = {1: {2: {22: 222}}, 3: {'a': 'b'}} vm = [[[222]], ['b']] show_vmatrix(vm) ### Response: def show_vmatrix(vm): ''' d = {1: {2: {22: 222}}, 3: {'a': 'b'}} vm = [[[222]], ['b']] show_vmatrix(vm) ''' ...
def restore(self): """Restores the modules that the saver knows about into sys.modules. """ try: for modname, mod in self._saved.items(): if mod is not None: sys.modules[modname] = mod else: try: ...
Restores the modules that the saver knows about into sys.modules.
Below is the the instruction that describes the task: ### Input: Restores the modules that the saver knows about into sys.modules. ### Response: def restore(self): """Restores the modules that the saver knows about into sys.modules. """ try: for modname, mod in s...
def vrel(v1, v2): """ Return the relative difference between two 3-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrel_c.html :param v1: First vector :type v1: 3-Element Array of floats :param v2: Second vector :type v2: 3-Element Array of floats :return...
Return the relative difference between two 3-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrel_c.html :param v1: First vector :type v1: 3-Element Array of floats :param v2: Second vector :type v2: 3-Element Array of floats :return: the relative difference betw...
Below is the the instruction that describes the task: ### Input: Return the relative difference between two 3-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrel_c.html :param v1: First vector :type v1: 3-Element Array of floats :param v2: Second vector :type v2...
def Normalize(str_): """The Normalize(str) function. This one also accepts Unicode string input (in the RFC only UTF-8 strings are used). """ # pylint: disable=C0103 if isinstance(str_, bytes): str_ = str_.decode("utf-8") return SASLPREP.prepare(str_)...
The Normalize(str) function. This one also accepts Unicode string input (in the RFC only UTF-8 strings are used).
Below is the the instruction that describes the task: ### Input: The Normalize(str) function. This one also accepts Unicode string input (in the RFC only UTF-8 strings are used). ### Response: def Normalize(str_): """The Normalize(str) function. This one also accepts Unicode strin...
def set_errors(self): """Set errors markup. """ if not self.field.errors or self.attrs.get("_no_errors"): return self.values["class"].append("error") for error in self.field.errors: self.values["errors"] += ERROR_WRAPPER % {"message": error}
Set errors markup.
Below is the the instruction that describes the task: ### Input: Set errors markup. ### Response: def set_errors(self): """Set errors markup. """ if not self.field.errors or self.attrs.get("_no_errors"): return self.values["class"].append("error") for error in self.field.errors: self.v...
def _get_output_columns(nodes, context): """Get the output columns for a list of SqlNodes. Args: nodes: List[SqlNode], the nodes to get output columns from. context: CompilationContext, global compilation state and metadata. Returns: List[Column], list of SqlAlchemy Columns to outp...
Get the output columns for a list of SqlNodes. Args: nodes: List[SqlNode], the nodes to get output columns from. context: CompilationContext, global compilation state and metadata. Returns: List[Column], list of SqlAlchemy Columns to output for this query.
Below is the the instruction that describes the task: ### Input: Get the output columns for a list of SqlNodes. Args: nodes: List[SqlNode], the nodes to get output columns from. context: CompilationContext, global compilation state and metadata. Returns: List[Column], list of SqlAl...
def get_changeset(args): """Dump the changeset objects as JSON, reading the provided bundle YAML. The YAML can be provided either from stdin or by passing a file path as first argument. """ # Parse the arguments. parser = argparse.ArgumentParser(description=get_changeset.__doc__) parser.add...
Dump the changeset objects as JSON, reading the provided bundle YAML. The YAML can be provided either from stdin or by passing a file path as first argument.
Below is the the instruction that describes the task: ### Input: Dump the changeset objects as JSON, reading the provided bundle YAML. The YAML can be provided either from stdin or by passing a file path as first argument. ### Response: def get_changeset(args): """Dump the changeset objects as JSON, r...
def on_lxml_loads(self, lxml, config, content, **kwargs): """ The `lxml <https://pypi.org/project/lxml/>`_ loads method. :param module lxml: The ``lxml`` module :param class config: The loading config class :param str content: The content to deserialize :param str encoding: The ...
The `lxml <https://pypi.org/project/lxml/>`_ loads method. :param module lxml: The ``lxml`` module :param class config: The loading config class :param str content: The content to deserialize :param str encoding: The encoding to read the given xml document as, defaults to "u...
Below is the the instruction that describes the task: ### Input: The `lxml <https://pypi.org/project/lxml/>`_ loads method. :param module lxml: The ``lxml`` module :param class config: The loading config class :param str content: The content to deserialize :param str encoding: The e...
async def send_notification(self, title, message): """Send notification.""" query = gql( """ mutation{ sendPushNotification(input: { title: "%s", message: "%s", }){ successful pushedToNumberOfDevices } ...
Send notification.
Below is the the instruction that describes the task: ### Input: Send notification. ### Response: async def send_notification(self, title, message): """Send notification.""" query = gql( """ mutation{ sendPushNotification(input: { title: "%s", m...
def ProcessBlocks(self, block_limit=1000): """ Method called on a loop to check the current height of the blockchain. If the height of the blockchain is more than the current stored height in the wallet, we get the next block in line and processes it. In the case that the walle...
Method called on a loop to check the current height of the blockchain. If the height of the blockchain is more than the current stored height in the wallet, we get the next block in line and processes it. In the case that the wallet height is far behind the height of the blockchain, we do this...
Below is the the instruction that describes the task: ### Input: Method called on a loop to check the current height of the blockchain. If the height of the blockchain is more than the current stored height in the wallet, we get the next block in line and processes it. In the case that the...
def GetFormatterObject(cls, data_type): """Retrieves the formatter object for a specific data type. Args: data_type (str): data type. Returns: EventFormatter: corresponding formatter or the default formatter if not available. """ data_type = data_type.lower() if data_type...
Retrieves the formatter object for a specific data type. Args: data_type (str): data type. Returns: EventFormatter: corresponding formatter or the default formatter if not available.
Below is the the instruction that describes the task: ### Input: Retrieves the formatter object for a specific data type. Args: data_type (str): data type. Returns: EventFormatter: corresponding formatter or the default formatter if not available. ### Response: def GetFormatterObjec...
def _get_closest_matches(input_attributes, target_attributes): """ :param input_attributes: First dictionary of objects to attribute tuples. :param target_attributes: Second dictionary of blocks to attribute tuples. :returns: A dictionary of objects in the input_attributes to the ...
:param input_attributes: First dictionary of objects to attribute tuples. :param target_attributes: Second dictionary of blocks to attribute tuples. :returns: A dictionary of objects in the input_attributes to the closest objects in the target_attributes.
Below is the the instruction that describes the task: ### Input: :param input_attributes: First dictionary of objects to attribute tuples. :param target_attributes: Second dictionary of blocks to attribute tuples. :returns: A dictionary of objects in the input_attributes to the closes...
def _encode(self, data, algorithm, key=None): '''Encode data with specific algorithm''' if algorithm['type'] == 'hmac': return data + self._hmac_generate(data, algorithm, key) elif algorithm['type'] == 'aes': return self._aes_encrypt(data, algorithm, key) elif al...
Encode data with specific algorithm
Below is the the instruction that describes the task: ### Input: Encode data with specific algorithm ### Response: def _encode(self, data, algorithm, key=None): '''Encode data with specific algorithm''' if algorithm['type'] == 'hmac': return data + self._hmac_generate(data, algorithm, ...
def _html_to_img_tuples(html:str, format:str='jpg', n_images:int=10) -> list: "Parse the google images html to img tuples containining `(fname, url)`" bs = BeautifulSoup(html, 'html.parser') img_tags = bs.find_all('div', {'class': 'rg_meta'}) metadata_dicts = (json.loads(e.text) for e in img_tags) ...
Parse the google images html to img tuples containining `(fname, url)`
Below is the the instruction that describes the task: ### Input: Parse the google images html to img tuples containining `(fname, url)` ### Response: def _html_to_img_tuples(html:str, format:str='jpg', n_images:int=10) -> list: "Parse the google images html to img tuples containining `(fname, url)`" bs...
def set_default (feature, value): """ Sets the default value of the given feature, overriding any previous default. feature: the name of the feature value: the default value to assign """ f = __all_features[feature] bad_attribute = None if f.free: bad_attribute = "free" ...
Sets the default value of the given feature, overriding any previous default. feature: the name of the feature value: the default value to assign
Below is the the instruction that describes the task: ### Input: Sets the default value of the given feature, overriding any previous default. feature: the name of the feature value: the default value to assign ### Response: def set_default (feature, value): """ Sets the default value of the gi...
def clear_score_system(self): """Clears the score system. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource...
Clears the score system. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Clears the score system. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* ### Response: def clear_score_system(self): ...
async def disconnect(self): """Shut down the watcher task and close websockets. """ if not self._watch_stopped.is_set(): log.debug('Stopping watcher task') self._watch_stopping.set() await self._watch_stopped.wait() self._watch_stopping.clear() ...
Shut down the watcher task and close websockets.
Below is the the instruction that describes the task: ### Input: Shut down the watcher task and close websockets. ### Response: async def disconnect(self): """Shut down the watcher task and close websockets. """ if not self._watch_stopped.is_set(): log.debug('Stopping watcher t...
def image(self): """ Attempts to provide a representative image from a content_object based on the content object's get_image() method. If there is a another content.object, as in the case of comments and other GFKs, then it will follow to that content_object and then get the im...
Attempts to provide a representative image from a content_object based on the content object's get_image() method. If there is a another content.object, as in the case of comments and other GFKs, then it will follow to that content_object and then get the image. Requires get_image() to...
Below is the the instruction that describes the task: ### Input: Attempts to provide a representative image from a content_object based on the content object's get_image() method. If there is a another content.object, as in the case of comments and other GFKs, then it will follow to that co...
def set_data(self, data): """Set model data""" self._data = data keys = list(data.keys()) self.breakpoints = [] for key in keys: bp_list = data[key] if bp_list: for item in data[key]: self.breakpoints.append((ke...
Set model data
Below is the the instruction that describes the task: ### Input: Set model data ### Response: def set_data(self, data): """Set model data""" self._data = data keys = list(data.keys()) self.breakpoints = [] for key in keys: bp_list = data[key] i...
def build(self, signing_private_key): """ Validates the certificate information, constructs an X.509 certificate and then signs it :param signing_private_key: An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey object for the private key to sign t...
Validates the certificate information, constructs an X.509 certificate and then signs it :param signing_private_key: An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey object for the private key to sign the request with. This should be the private ke...
Below is the the instruction that describes the task: ### Input: Validates the certificate information, constructs an X.509 certificate and then signs it :param signing_private_key: An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey object for the private ke...
def conditional_write(strm, fmt, value, *args, **kwargs): """Write to stream using fmt and value if value is not None""" if value is not None: strm.write(fmt.format(value, *args, **kwargs))
Write to stream using fmt and value if value is not None
Below is the the instruction that describes the task: ### Input: Write to stream using fmt and value if value is not None ### Response: def conditional_write(strm, fmt, value, *args, **kwargs): """Write to stream using fmt and value if value is not None""" if value is not None: strm.write(fmt.forma...
def update_machine_group(self, project_name, group_detail): """ update machine group in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_detail: MachineGroupDetail :param g...
update machine group in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_detail: MachineGroupDetail :param group_detail: the machine group detail config :return: UpdateMa...
Below is the the instruction that describes the task: ### Input: update machine group in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_detail: MachineGroupDetail :param group...
def addFileHandler(self,filename='', dr='',lvl=1): """ This function will add a file handler to a log with the provided level. Args: lvl (int): The severity level of messages printed to the file with the file handler, default = 1. """ ...
This function will add a file handler to a log with the provided level. Args: lvl (int): The severity level of messages printed to the file with the file handler, default = 1.
Below is the the instruction that describes the task: ### Input: This function will add a file handler to a log with the provided level. Args: lvl (int): The severity level of messages printed to the file with the file handler, default = 1. ### Response: def ad...
def _dispatch_commands(self, from_state, to_state, smtp_command): """This method dispatches a SMTP command to the appropriate handler method. It is called after a new command was received and a valid transition was found.""" #print from_state, ' -> ', to_state, ':', smtp_command ...
This method dispatches a SMTP command to the appropriate handler method. It is called after a new command was received and a valid transition was found.
Below is the the instruction that describes the task: ### Input: This method dispatches a SMTP command to the appropriate handler method. It is called after a new command was received and a valid transition was found. ### Response: def _dispatch_commands(self, from_state, to_state, smtp_command): ...
def download_from_plugin(plugin: APlugin): """ Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. get download links 5. compare with savestate 6. download new/updated data 7. check downloads 8. update savestate 9....
Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. get download links 5. compare with savestate 6. download new/updated data 7. check downloads 8. update savestate 9. write new savestate :param plugin: plugin :ty...
Below is the the instruction that describes the task: ### Input: Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. get download links 5. compare with savestate 6. download new/updated data 7. check downloads 8. update sa...
def getaddrinfo_wrapper(host, port, family=socket.AF_INET, socktype=0, proto=0, flags=0): """Patched 'getaddrinfo' with default family IPv4 (enabled by settings IPV4_ONLY=True)""" return orig_getaddrinfo(host, port, family, socktype, proto, flags)
Patched 'getaddrinfo' with default family IPv4 (enabled by settings IPV4_ONLY=True)
Below is the the instruction that describes the task: ### Input: Patched 'getaddrinfo' with default family IPv4 (enabled by settings IPV4_ONLY=True) ### Response: def getaddrinfo_wrapper(host, port, family=socket.AF_INET, socktype=0, proto=0, flags=0): """Patched 'getaddrinfo' with default family IPv4 (enabled...
def summarize(self): """Convert all of the values to their max values. This form is used to represent the summary level""" s = str(self.allval()) return self.parse(s[:2]+ ''.join(['Z']*len(s[2:])))
Convert all of the values to their max values. This form is used to represent the summary level
Below is the the instruction that describes the task: ### Input: Convert all of the values to their max values. This form is used to represent the summary level ### Response: def summarize(self): """Convert all of the values to their max values. This form is used to represent the summary level""" ...