code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _find_image_ext(path, number=None): """Find an image, tolerant of different file extensions.""" if number is not None: path = path.format(number) path = os.path.splitext(path)[0] for ext in _KNOWN_IMG_EXTS: this_path = '%s.%s' % (path, ext) if os.path.isfile(this_path): ...
Find an image, tolerant of different file extensions.
Below is the the instruction that describes the task: ### Input: Find an image, tolerant of different file extensions. ### Response: def _find_image_ext(path, number=None): """Find an image, tolerant of different file extensions.""" if number is not None: path = path.format(number) path = os.pa...
def generate(topic, add_punctuation, character_count=None): """ Generate the text for a given topic """ corpus_cursor = db.markovify.find({'topic': topic}) if(corpus_cursor): corpus = '' for text in corpus_cursor: corpus = punctuate(corpus, text['text'], add_punctuation) ...
Generate the text for a given topic
Below is the the instruction that describes the task: ### Input: Generate the text for a given topic ### Response: def generate(topic, add_punctuation, character_count=None): """ Generate the text for a given topic """ corpus_cursor = db.markovify.find({'topic': topic}) if(corpus_cursor): corpu...
def combine_xml_points(l, units, handle_units): """Combine multiple Point tags into an array.""" ret = {} for item in l: for key, value in item.items(): ret.setdefault(key, []).append(value) for key, value in ret.items(): if key != 'date': ret[key] = handle_units...
Combine multiple Point tags into an array.
Below is the the instruction that describes the task: ### Input: Combine multiple Point tags into an array. ### Response: def combine_xml_points(l, units, handle_units): """Combine multiple Point tags into an array.""" ret = {} for item in l: for key, value in item.items(): ret.setd...
def _validate_controls(self, proposal): '''Validate controls list. Makes sure only one instance of any given layer can exist in the controls list. ''' self._control_ids = [c.model_id for c in proposal.value] if len(set(self._control_ids)) != len(self._control_ids): ...
Validate controls list. Makes sure only one instance of any given layer can exist in the controls list.
Below is the the instruction that describes the task: ### Input: Validate controls list. Makes sure only one instance of any given layer can exist in the controls list. ### Response: def _validate_controls(self, proposal): '''Validate controls list. Makes sure only one instance of...
def get_prime(bits): """Creates (probable) prime number of given size :param bits: size of number to generate :return: prime number of given size """ while True: num = random.randrange(2 ** (bits - 1), 2 ** bits) if Integer(str(num)).is_probably_prime(): return num
Creates (probable) prime number of given size :param bits: size of number to generate :return: prime number of given size
Below is the the instruction that describes the task: ### Input: Creates (probable) prime number of given size :param bits: size of number to generate :return: prime number of given size ### Response: def get_prime(bits): """Creates (probable) prime number of given size :param bits: size of numbe...
def _set_redist_static(self, v, load=False): """ Setter method for redist_static, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v6/redist_static (container) If this variable is read-only (config: false) in the source YANG file, then _set_redist_static is considered as a priv...
Setter method for redist_static, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v6/redist_static (container) If this variable is read-only (config: false) in the source YANG file, then _set_redist_static is considered as a private method. Backends looking to populate this variabl...
Below is the the instruction that describes the task: ### Input: Setter method for redist_static, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v6/redist_static (container) If this variable is read-only (config: false) in the source YANG file, then _set_redist_static is consider...
def _mass_from_knownmass_eta(known_mass, eta, known_is_secondary=False, force_real=True): r"""Returns the other component mass given one of the component masses and the symmetric mass ratio. This requires finding the roots of the quadratic equation: .. math:: \eta m...
r"""Returns the other component mass given one of the component masses and the symmetric mass ratio. This requires finding the roots of the quadratic equation: .. math:: \eta m_2^2 + (2\eta - 1)m_1 m_2 + \eta m_1^2 = 0. This has two solutions which correspond to :math:`m_1` being the heavier ...
Below is the the instruction that describes the task: ### Input: r"""Returns the other component mass given one of the component masses and the symmetric mass ratio. This requires finding the roots of the quadratic equation: .. math:: \eta m_2^2 + (2\eta - 1)m_1 m_2 + \eta m_1^2 = 0. This...
def describe_cache_clusters(name=None, conn=None, region=None, key=None, keyid=None, profile=None, **args): ''' Return details about all (or just one) Elasticache cache clusters. Example: .. code-block:: bash salt myminion boto3_elasticache.describe_cache_clusters ...
Return details about all (or just one) Elasticache cache clusters. Example: .. code-block:: bash salt myminion boto3_elasticache.describe_cache_clusters salt myminion boto3_elasticache.describe_cache_clusters myelasticache
Below is the the instruction that describes the task: ### Input: Return details about all (or just one) Elasticache cache clusters. Example: .. code-block:: bash salt myminion boto3_elasticache.describe_cache_clusters salt myminion boto3_elasticache.describe_cache_clusters myelasticache #...
def write(self)->None: "Writes model gradient statistics to Tensorboard." if len(self.gradients) == 0: return norms = [x.data.norm() for x in self.gradients] self._write_avg_norm(norms=norms) self._write_median_norm(norms=norms) self._write_max_norm(norms=norms) s...
Writes model gradient statistics to Tensorboard.
Below is the the instruction that describes the task: ### Input: Writes model gradient statistics to Tensorboard. ### Response: def write(self)->None: "Writes model gradient statistics to Tensorboard." if len(self.gradients) == 0: return norms = [x.data.norm() for x in self.gradients] ...
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by...
Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current i...
Below is the the instruction that describes the task: ### Input: Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the ob...
def sg_layer_func(func): r"""Decorates a function `func` as a sg_layer function. Args: func: function to decorate """ @wraps(func) def wrapper(tensor, **kwargs): r"""Manages arguments of `tf.sg_opt`. Args: tensor: A `tensor` (automatically passed by decorator). ...
r"""Decorates a function `func` as a sg_layer function. Args: func: function to decorate
Below is the the instruction that describes the task: ### Input: r"""Decorates a function `func` as a sg_layer function. Args: func: function to decorate ### Response: def sg_layer_func(func): r"""Decorates a function `func` as a sg_layer function. Args: func: function to decorate ...
def _make_tasks_unique(tasks): """If some tasks of the workflow are the same they are deep copied.""" unique_tasks = [] prev_tasks = set() for task in tasks: if task in prev_tasks: task = copy.deepcopy(task) unique_tasks.append(task) ...
If some tasks of the workflow are the same they are deep copied.
Below is the the instruction that describes the task: ### Input: If some tasks of the workflow are the same they are deep copied. ### Response: def _make_tasks_unique(tasks): """If some tasks of the workflow are the same they are deep copied.""" unique_tasks = [] prev_tasks = set() ...
def evaluations_scipy(ty, pv): """ evaluations_scipy(ty, pv) -> (ACC, MSE, SCC) ty, pv: ndarray Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv). """ if not (scipy != None and isinstance(ty, scipy.ndarray) and isinstance(pv, scipy.nd...
evaluations_scipy(ty, pv) -> (ACC, MSE, SCC) ty, pv: ndarray Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv).
Below is the the instruction that describes the task: ### Input: evaluations_scipy(ty, pv) -> (ACC, MSE, SCC) ty, pv: ndarray Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv). ### Response: def evaluations_scipy(ty, pv): """ evalu...
def getseed(myseed, i): """ Return a single seed from a long seed given by `genseeds`. Parameters ---------- myseed : bytes A long seed given by `genseeds(n)`. i : int An index less than n. Returns ------- rndseed : int A seed (less than (2 ** 31)) """ ...
Return a single seed from a long seed given by `genseeds`. Parameters ---------- myseed : bytes A long seed given by `genseeds(n)`. i : int An index less than n. Returns ------- rndseed : int A seed (less than (2 ** 31))
Below is the the instruction that describes the task: ### Input: Return a single seed from a long seed given by `genseeds`. Parameters ---------- myseed : bytes A long seed given by `genseeds(n)`. i : int An index less than n. Returns ------- rndseed : int A see...
def read(self, tid, length, offset, fh): """ Read from a file. Data is obtained from ``YTStor`` object (which is kept under `fh` descriptor) using its ``read`` method. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tup...
Read from a file. Data is obtained from ``YTStor`` object (which is kept under `fh` descriptor) using its ``read`` method. Parameters ---------- tid : str Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator. length : int ...
Below is the the instruction that describes the task: ### Input: Read from a file. Data is obtained from ``YTStor`` object (which is kept under `fh` descriptor) using its ``read`` method. Parameters ---------- tid : str Path to file. Original `path` argument is converted...
def rename_property(self, old, new): """Replace the name of a property by a new one.""" self._properties.replace(old, new) pairs = self._pairs pairs |= {(o, new) for o in self._objects if (o, old) in pairs and not pairs.remove((o, old))}
Replace the name of a property by a new one.
Below is the the instruction that describes the task: ### Input: Replace the name of a property by a new one. ### Response: def rename_property(self, old, new): """Replace the name of a property by a new one.""" self._properties.replace(old, new) pairs = self._pairs pairs |= {(o, ne...
def instance( dt, tz=UTC # type: _datetime.datetime # type: Union[str, _Timezone, None] ): # type: (...) -> DateTime """ Create a DateTime instance from a datetime one. """ if not isinstance(dt, _datetime.datetime): raise ValueError("instance() only accepts datetime objects.") if isi...
Create a DateTime instance from a datetime one.
Below is the the instruction that describes the task: ### Input: Create a DateTime instance from a datetime one. ### Response: def instance( dt, tz=UTC # type: _datetime.datetime # type: Union[str, _Timezone, None] ): # type: (...) -> DateTime """ Create a DateTime instance from a datetime one. ...
def delete_additional_charge(self, recurring_billing_id): """ Remove an extra charge from an invoice. Args: recurring_billing_id: Identifier of the additional charge. Returns: """ fmt = 'recurringBillItems/{}'.format(recurring_billing_id) return sel...
Remove an extra charge from an invoice. Args: recurring_billing_id: Identifier of the additional charge. Returns:
Below is the the instruction that describes the task: ### Input: Remove an extra charge from an invoice. Args: recurring_billing_id: Identifier of the additional charge. Returns: ### Response: def delete_additional_charge(self, recurring_billing_id): """ Remove an extr...
async def parse_tag_results(soup): """ Parse a page of tag or trait results. Same format. :param soup: BS4 Class Object :return: A list of tags, Nothing else really useful there """ soup = soup.find_all('td', class_='tc3') tags = [] for item in soup: tags.append(item.a.string) ...
Parse a page of tag or trait results. Same format. :param soup: BS4 Class Object :return: A list of tags, Nothing else really useful there
Below is the the instruction that describes the task: ### Input: Parse a page of tag or trait results. Same format. :param soup: BS4 Class Object :return: A list of tags, Nothing else really useful there ### Response: async def parse_tag_results(soup): """ Parse a page of tag or trait results. Sam...
def pack(self, out: IO): """ Write the Field to the file-like object `out`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when saving a ClassFile. :param out: Any file-like object providing `write(...
Write the Field to the file-like object `out`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when saving a ClassFile. :param out: Any file-like object providing `write()`
Below is the the instruction that describes the task: ### Input: Write the Field to the file-like object `out`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when saving a ClassFile. :param out: Any file-like ...
def dot(A, B): """Matrix multiplication between A and B This function is equivalent to ``A @ B``, which is unfortunately not possible under python 2.x. Args: A (sequence): B (sequence): Returns: sequence: """ try: result = A.__matmul__(B) if result ...
Matrix multiplication between A and B This function is equivalent to ``A @ B``, which is unfortunately not possible under python 2.x. Args: A (sequence): B (sequence): Returns: sequence:
Below is the the instruction that describes the task: ### Input: Matrix multiplication between A and B This function is equivalent to ``A @ B``, which is unfortunately not possible under python 2.x. Args: A (sequence): B (sequence): Returns: sequence: ### Response: def do...
def _sendMsg(self, msg): """Send a line to graphite. Retry with exponential backoff.""" if not self.sock: self.connect() if not isinstance(msg, binary_type): msg = msg.encode("UTF-8") backoff = 0.001 while True: try: self.sock.sendall(msg) break except socket...
Send a line to graphite. Retry with exponential backoff.
Below is the the instruction that describes the task: ### Input: Send a line to graphite. Retry with exponential backoff. ### Response: def _sendMsg(self, msg): """Send a line to graphite. Retry with exponential backoff.""" if not self.sock: self.connect() if not isinstance(msg, binary_type): ...
def cache(self, code, number=0): """Make a name for a block of code, and cache the code. Parameters ---------- code : str The Python source code to cache. number : int A number which forms part of the code's name. Used for the execution coun...
Make a name for a block of code, and cache the code. Parameters ---------- code : str The Python source code to cache. number : int A number which forms part of the code's name. Used for the execution counter. Returns ----...
Below is the the instruction that describes the task: ### Input: Make a name for a block of code, and cache the code. Parameters ---------- code : str The Python source code to cache. number : int A number which forms part of the code's name. Used for the...
async def reconnect(self): """断线重连.""" self.clean() try: self.writer.close() except: pass self.closed = True await self.connect() if self.debug: print("reconnect to {}".format((self.hostname, self.port)))
断线重连.
Below is the the instruction that describes the task: ### Input: 断线重连. ### Response: async def reconnect(self): """断线重连.""" self.clean() try: self.writer.close() except: pass self.closed = True await self.connect() if self.debug: ...
def set_action(self,action): """Set the action of the item. :Parameters: - `action`: the new action or `None`. :Types: - `action`: `unicode` """ if action is None: if self.xmlnode.hasProp("action"): self.xmlnode.unsetProp("acti...
Set the action of the item. :Parameters: - `action`: the new action or `None`. :Types: - `action`: `unicode`
Below is the the instruction that describes the task: ### Input: Set the action of the item. :Parameters: - `action`: the new action or `None`. :Types: - `action`: `unicode` ### Response: def set_action(self,action): """Set the action of the item. :Paramete...
def set_save_itrs_root(setting): """ Adjust the root timer save_itrs setting, such as for use in multiprocessing, when a root timer may become a parallel subdivision (see subdivide()). Args: setting (bool): Save individual iterations data, passed through bool() Returns: bool: I...
Adjust the root timer save_itrs setting, such as for use in multiprocessing, when a root timer may become a parallel subdivision (see subdivide()). Args: setting (bool): Save individual iterations data, passed through bool() Returns: bool: Implemented setting value.
Below is the the instruction that describes the task: ### Input: Adjust the root timer save_itrs setting, such as for use in multiprocessing, when a root timer may become a parallel subdivision (see subdivide()). Args: setting (bool): Save individual iterations data, passed through bool() ...
def combine(self, other): """An instance of lunr.MatchData will be created for every term that matches a document. However only one instance is required in a lunr.Index~Result. This method combines metadata from another instance of MatchData with this object's metadata. ...
An instance of lunr.MatchData will be created for every term that matches a document. However only one instance is required in a lunr.Index~Result. This method combines metadata from another instance of MatchData with this object's metadata.
Below is the the instruction that describes the task: ### Input: An instance of lunr.MatchData will be created for every term that matches a document. However only one instance is required in a lunr.Index~Result. This method combines metadata from another instance of MatchData with this ...
def iter_links_by_attrib(self, element): '''Iterate an element by looking at its attributes for links.''' for attrib_name in element.attrib.keys(): attrib_value = element.attrib.get(attrib_name) if attrib_name in self.LINK_ATTRIBUTES: if self.javascript_scraper a...
Iterate an element by looking at its attributes for links.
Below is the the instruction that describes the task: ### Input: Iterate an element by looking at its attributes for links. ### Response: def iter_links_by_attrib(self, element): '''Iterate an element by looking at its attributes for links.''' for attrib_name in element.attrib.keys(): a...
def lognorm(x, mu, sigma=1.0): """ Log-normal function from scipy """ return stats.lognorm(sigma, scale=mu).pdf(x)
Log-normal function from scipy
Below is the the instruction that describes the task: ### Input: Log-normal function from scipy ### Response: def lognorm(x, mu, sigma=1.0): """ Log-normal function from scipy """ return stats.lognorm(sigma, scale=mu).pdf(x)
def create_table_with_pk(self, table, fields, primary_keys): """ Responsys.createTableWithPK call Accepts: InteractObject table list fields list primary_keys Returns True on success """ table = table.get_soap_object(self.client) retur...
Responsys.createTableWithPK call Accepts: InteractObject table list fields list primary_keys Returns True on success
Below is the the instruction that describes the task: ### Input: Responsys.createTableWithPK call Accepts: InteractObject table list fields list primary_keys Returns True on success ### Response: def create_table_with_pk(self, table, fields, primary_keys): ...
def save_image(self, image_file): """ Saves the image file to disk. """ self.ensure_pyplot() command = 'plt.gcf().savefig("%s")'%image_file #print 'SAVEFIG', command # dbg self.process_input_line('bookmark ipy_thisdir', store_history=False) self.process_i...
Saves the image file to disk.
Below is the the instruction that describes the task: ### Input: Saves the image file to disk. ### Response: def save_image(self, image_file): """ Saves the image file to disk. """ self.ensure_pyplot() command = 'plt.gcf().savefig("%s")'%image_file #print 'SAVEFIG', ...
def _get_oath2_access_token(client_key, client_secret): ''' Query the vistara API and get an access_token ''' if not client_key and not client_secret: log.error( "client_key and client_secret have not been specified " "and are required parameters." ) retu...
Query the vistara API and get an access_token
Below is the the instruction that describes the task: ### Input: Query the vistara API and get an access_token ### Response: def _get_oath2_access_token(client_key, client_secret): ''' Query the vistara API and get an access_token ''' if not client_key and not client_secret: log.error( ...
def getValue(words): """Computes the sum of the values of the words.""" value = 0 for word in words: for letter in word: # shared.getConst will evaluate to the dictionary broadcasted by # the root Future value += shared.getConst('lettersValue')[letter] return ...
Computes the sum of the values of the words.
Below is the the instruction that describes the task: ### Input: Computes the sum of the values of the words. ### Response: def getValue(words): """Computes the sum of the values of the words.""" value = 0 for word in words: for letter in word: # shared.getConst will evaluate to the...
def html_output(cls, cs, score_dict, output_filename, ds_loc, limit): ''' Generates rendered HTML output for the compliance score(s) @param cs Compliance Checker Suite @param score_groups List of results @param output_filename The file path to output to @p...
Generates rendered HTML output for the compliance score(s) @param cs Compliance Checker Suite @param score_groups List of results @param output_filename The file path to output to @param ds_loc List of source datasets @param limit The degree of ...
Below is the the instruction that describes the task: ### Input: Generates rendered HTML output for the compliance score(s) @param cs Compliance Checker Suite @param score_groups List of results @param output_filename The file path to output to @param ds_loc ...
def load(self, fileobj): '''Load the dict from the file object''' # try formats from most restrictive to least restrictive for loader in (pickle.load, json.load, csv.reader): fileobj.seek(0) try: return self.initial_update(loader(fileobj)) exce...
Load the dict from the file object
Below is the the instruction that describes the task: ### Input: Load the dict from the file object ### Response: def load(self, fileobj): '''Load the dict from the file object''' # try formats from most restrictive to least restrictive for loader in (pickle.load, json.load, csv.reader): ...
def map(self, key, value): """ Args: key: Image name value: Image as jpeg byte data Yields: A tuple in the form of (key, value) key: Constant dummy value value: (l2sqr_dist, value) """ try: image = imfeat.re...
Args: key: Image name value: Image as jpeg byte data Yields: A tuple in the form of (key, value) key: Constant dummy value value: (l2sqr_dist, value)
Below is the the instruction that describes the task: ### Input: Args: key: Image name value: Image as jpeg byte data Yields: A tuple in the form of (key, value) key: Constant dummy value value: (l2sqr_dist, value) ### Response: def map(self, key...
def get_job_info(): """ Get information about the job from the PBS server """ jobid = get_job_id() if jobid == '': return None info = get_qstat_info('-ft {0}'.format(jobid), 'Job Id:') # Select the dict for this job (there should only be one entry in any case) info = info['Jo...
Get information about the job from the PBS server
Below is the the instruction that describes the task: ### Input: Get information about the job from the PBS server ### Response: def get_job_info(): """ Get information about the job from the PBS server """ jobid = get_job_id() if jobid == '': return None info = get_qstat_info('-...
def count(self, **kwargs): """Counts the number of non-NaN objects for each column or row. Return: A new QueryCompiler object containing counts of non-NaN objects from each column or row. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis",...
Counts the number of non-NaN objects for each column or row. Return: A new QueryCompiler object containing counts of non-NaN objects from each column or row.
Below is the the instruction that describes the task: ### Input: Counts the number of non-NaN objects for each column or row. Return: A new QueryCompiler object containing counts of non-NaN objects from each column or row. ### Response: def count(self, **kwargs): """Counts ...
def __get_menu_entries(self, kibiter_major): """ Get the menu entries from the panel definition """ menu_entries = [] for entry in self.panels_menu: if entry['source'] not in self.data_sources: continue parent_menu_item = { 'name': entry['n...
Get the menu entries from the panel definition
Below is the the instruction that describes the task: ### Input: Get the menu entries from the panel definition ### Response: def __get_menu_entries(self, kibiter_major): """ Get the menu entries from the panel definition """ menu_entries = [] for entry in self.panels_menu: if e...
def pause(): """ Pause the timer, preventing subsequent time from accumulating in the total. Renders the timer inactive, disabling other timing commands. Returns: float: The current time. Raises: PausedError: If timer already paused. StoppedError: If timer already stopped....
Pause the timer, preventing subsequent time from accumulating in the total. Renders the timer inactive, disabling other timing commands. Returns: float: The current time. Raises: PausedError: If timer already paused. StoppedError: If timer already stopped.
Below is the the instruction that describes the task: ### Input: Pause the timer, preventing subsequent time from accumulating in the total. Renders the timer inactive, disabling other timing commands. Returns: float: The current time. Raises: PausedError: If timer already paused. ...
def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ self.viewBox.sigRangeChangedManually.disconnect(self.setAutoRangeOff) self.viewBox.sigRangeChanged.disconnect(self.refreshMinMax)
Disconnects signals. Is called by self.finalize when the cti is deleted.
Below is the the instruction that describes the task: ### Input: Disconnects signals. Is called by self.finalize when the cti is deleted. ### Response: def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ self.vi...
def get_access_token( self, oauth_token, oauth_token_secret, oauth_verifier ): """ :param oauth_token: oauth_token retrieve by the API Twython get_authentication_tokens() :param oauth_token_secret: oauth_token_secret retrieve by the API Twython get_authentication_toke...
:param oauth_token: oauth_token retrieve by the API Twython get_authentication_tokens() :param oauth_token_secret: oauth_token_secret retrieve by the API Twython get_authentication_tokens() :param oauth_verifier: oauth_verifier retrieve from Twitter :type oauth_token: string ...
Below is the the instruction that describes the task: ### Input: :param oauth_token: oauth_token retrieve by the API Twython get_authentication_tokens() :param oauth_token_secret: oauth_token_secret retrieve by the API Twython get_authentication_tokens() :param oauth_verifier: oauth_...
def independent(repertoire): """Check whether the repertoire is independent.""" marginals = [marginal(repertoire, i) for i in range(repertoire.ndim)] # TODO: is there a way to do without an explicit iteration? joint = marginals[0] for m in marginals[1:]: joint = joint * m # TODO: shoul...
Check whether the repertoire is independent.
Below is the the instruction that describes the task: ### Input: Check whether the repertoire is independent. ### Response: def independent(repertoire): """Check whether the repertoire is independent.""" marginals = [marginal(repertoire, i) for i in range(repertoire.ndim)] # TODO: is there a way to do...
def list_rooms(api_key=None): ''' List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key:...
List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15
Below is the the instruction that describes the task: ### Input: List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ...
def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet ...
Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete...
Below is the the instruction that describes the task: ### Input: Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway...
def is_attr_selected(attr_name, # type: str include=None, # type: Union[str, Tuple[str]] exclude=None # type: Union[str, Tuple[str]] ): """decide whether an action has to be performed on the attribute or not, based on its name""" if include ...
decide whether an action has to be performed on the attribute or not, based on its name
Below is the the instruction that describes the task: ### Input: decide whether an action has to be performed on the attribute or not, based on its name ### Response: def is_attr_selected(attr_name, # type: str include=None, # type: Union[str, Tuple[str]] exclude=None...
def execute_update(args): """Execute the update based on command line args and returns a dictionary with 'execution result, ''response code', 'response info' and 'process friendly message'. """ provider_class = getattr(dnsupdater, dnsupdater.AVAILABLE_PLUGINS.get(args.p...
Execute the update based on command line args and returns a dictionary with 'execution result, ''response code', 'response info' and 'process friendly message'.
Below is the the instruction that describes the task: ### Input: Execute the update based on command line args and returns a dictionary with 'execution result, ''response code', 'response info' and 'process friendly message'. ### Response: def execute_update(args): """Execute the update based on comman...
def solve(self, angles0, target): """Calculate joint angles and returns it.""" return self.optimizer.optimize(np.array(angles0), target)
Calculate joint angles and returns it.
Below is the the instruction that describes the task: ### Input: Calculate joint angles and returns it. ### Response: def solve(self, angles0, target): """Calculate joint angles and returns it.""" return self.optimizer.optimize(np.array(angles0), target)
def repository(self, owner, repository): """Returns a Repository object for the specified combination of owner and repository :param str owner: (required) :param str repository: (required) :returns: :class:`Repository <github3.repos.Repository>` """ json = None ...
Returns a Repository object for the specified combination of owner and repository :param str owner: (required) :param str repository: (required) :returns: :class:`Repository <github3.repos.Repository>`
Below is the the instruction that describes the task: ### Input: Returns a Repository object for the specified combination of owner and repository :param str owner: (required) :param str repository: (required) :returns: :class:`Repository <github3.repos.Repository>` ### Response: d...
def get_dpi(): """Returns screen dpi resolution""" def pxmm_2_dpi((pixels, length_mm)): return pixels * 25.6 / length_mm return map(pxmm_2_dpi, zip(wx.GetDisplaySize(), wx.GetDisplaySizeMM()))
Returns screen dpi resolution
Below is the the instruction that describes the task: ### Input: Returns screen dpi resolution ### Response: def get_dpi(): """Returns screen dpi resolution""" def pxmm_2_dpi((pixels, length_mm)): return pixels * 25.6 / length_mm return map(pxmm_2_dpi, zip(wx.GetDisplaySize(), wx.GetDisplaySi...
def _create_dict(self, format, args): """Handle the case where the outermost type of format is a dict.""" builder = None if args is None or not args[0]: # empty value: we need to call _create() to parse the subtype, # and specify the element type precisely re...
Handle the case where the outermost type of format is a dict.
Below is the the instruction that describes the task: ### Input: Handle the case where the outermost type of format is a dict. ### Response: def _create_dict(self, format, args): """Handle the case where the outermost type of format is a dict.""" builder = None if args is None or not args[...
def resample(self, data, input_rate): """ Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio r...
Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio rate to resample from
Below is the the instruction that describes the task: ### Input: Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): In...
def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None: """ Print a plain table with the details of the given trainings. :param trainings: iterable of tuples (train_dir, configuration dict, trace) """ long_table = [] for train_dir, config, trace in trainings: ...
Print a plain table with the details of the given trainings. :param trainings: iterable of tuples (train_dir, configuration dict, trace)
Below is the the instruction that describes the task: ### Input: Print a plain table with the details of the given trainings. :param trainings: iterable of tuples (train_dir, configuration dict, trace) ### Response: def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None: "...
def get(key, adapter = MemoryAdapter): ''' get the cache value ''' try: return pickle.loads(adapter().get(key)) except CacheExpiredException: return None
get the cache value
Below is the the instruction that describes the task: ### Input: get the cache value ### Response: def get(key, adapter = MemoryAdapter): ''' get the cache value ''' try: return pickle.loads(adapter().get(key)) except CacheExpiredException: return None
def function(self, new_function): """Set the MonitorState of this Monitor.""" self._client.change_state( self._monitor_url, {'Monitor[Function]': new_function.value})
Set the MonitorState of this Monitor.
Below is the the instruction that describes the task: ### Input: Set the MonitorState of this Monitor. ### Response: def function(self, new_function): """Set the MonitorState of this Monitor.""" self._client.change_state( self._monitor_url, {'Monitor[Function]': new_function...
def hmset(self, **kwargs): """ This command on the model allow setting many instancehash fields with only one redis call. You must pass kwargs with field names as keys, with their value. """ if kwargs and not any(kwarg in self._instancehash_fields for kwarg in iterkeys(kw...
This command on the model allow setting many instancehash fields with only one redis call. You must pass kwargs with field names as keys, with their value.
Below is the the instruction that describes the task: ### Input: This command on the model allow setting many instancehash fields with only one redis call. You must pass kwargs with field names as keys, with their value. ### Response: def hmset(self, **kwargs): """ This command on t...
def add_topic(self, group_alias, title, content): """ 创建话题(小心验证码~) :param group_alias: 小组ID :param title: 标题 :param content: 内容 :return: bool """ xml = self.api.req(API_GROUP_ADD_TOPIC % group_alias, 'post', data={ 'ck': self.api.ck(),...
创建话题(小心验证码~) :param group_alias: 小组ID :param title: 标题 :param content: 内容 :return: bool
Below is the the instruction that describes the task: ### Input: 创建话题(小心验证码~) :param group_alias: 小组ID :param title: 标题 :param content: 内容 :return: bool ### Response: def add_topic(self, group_alias, title, content): """ 创建话题(小心验证码~) :param ...
def dumps(obj): """ Dumps a serializable object to JSON. This API maps to the Python built-in json dumps method, with a few differences: * The return value is always valid JSON according to RFC 7159. * The input can be any of the following types: - SFrame - SArray - SGraph ...
Dumps a serializable object to JSON. This API maps to the Python built-in json dumps method, with a few differences: * The return value is always valid JSON according to RFC 7159. * The input can be any of the following types: - SFrame - SArray - SGraph - single flexible_typ...
Below is the the instruction that describes the task: ### Input: Dumps a serializable object to JSON. This API maps to the Python built-in json dumps method, with a few differences: * The return value is always valid JSON according to RFC 7159. * The input can be any of the following types: - S...
def _get_tmp_account_id(cls, writer_spec): """Returns the account id to use with tmp bucket.""" # pick tmp id iff tmp bucket is set explicitly if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec.get(cls._TMP_ACCOUNT_ID_PARAM, None) return cls._get_account_id(writer_spec)
Returns the account id to use with tmp bucket.
Below is the the instruction that describes the task: ### Input: Returns the account id to use with tmp bucket. ### Response: def _get_tmp_account_id(cls, writer_spec): """Returns the account id to use with tmp bucket.""" # pick tmp id iff tmp bucket is set explicitly if cls.TMP_BUCKET_NAME_PARAM in wr...
def value_contains(self, value, attribute): """ Determine if any of the items in the value list for the given attribute contain value. """ for item in self[attribute]: if value in item: return True return False
Determine if any of the items in the value list for the given attribute contain value.
Below is the the instruction that describes the task: ### Input: Determine if any of the items in the value list for the given attribute contain value. ### Response: def value_contains(self, value, attribute): """ Determine if any of the items in the value list for the given attribu...
def install_default_formatters(self): """ Installs default formatters for the following tags: b, i, u, s, list (and \*), quote, code, center, color, url """ self.add_simple_formatter('b', '<strong>%(value)s</strong>') self.add_simple_formatter('i', '<em>%(value)s</em...
Installs default formatters for the following tags: b, i, u, s, list (and \*), quote, code, center, color, url
Below is the the instruction that describes the task: ### Input: Installs default formatters for the following tags: b, i, u, s, list (and \*), quote, code, center, color, url ### Response: def install_default_formatters(self): """ Installs default formatters for the following tags: ...
def __get_view_tmpl(tag_key): ''' 根据分类uid的4位编码来找模板。如果4位的存在,则使用4位的;不然找其父类;再不然则使用通用模板 只有View需要,edit, list使用通用模板 :return String. ''' the_view_file_4 = './templates/tmpl_{0}/tpl_view_{1}.html'.format( KIND_DICS['kind_' + tag_key.split('_')[-1]], tag_key.split('_')[1] ) the_vi...
根据分类uid的4位编码来找模板。如果4位的存在,则使用4位的;不然找其父类;再不然则使用通用模板 只有View需要,edit, list使用通用模板 :return String.
Below is the the instruction that describes the task: ### Input: 根据分类uid的4位编码来找模板。如果4位的存在,则使用4位的;不然找其父类;再不然则使用通用模板 只有View需要,edit, list使用通用模板 :return String. ### Response: def __get_view_tmpl(tag_key): ''' 根据分类uid的4位编码来找模板。如果4位的存在,则使用4位的;不然找其父类;再不然则使用通用模板 只有View需要,edit, list使用通用模板 :return St...
def configmap_install_id_plugin(scout, app, map_name=None, namespace="default"): """ Scout id_plugin that uses a Kubernetes configmap to store the install ID. :param scout: Scout instance that's calling the plugin :param app: Name of the application that's using Scout :param map...
Scout id_plugin that uses a Kubernetes configmap to store the install ID. :param scout: Scout instance that's calling the plugin :param app: Name of the application that's using Scout :param map_name: Optional ConfigMap name to use; defaults to "scout.config.$app" :param namespace: Opti...
Below is the the instruction that describes the task: ### Input: Scout id_plugin that uses a Kubernetes configmap to store the install ID. :param scout: Scout instance that's calling the plugin :param app: Name of the application that's using Scout :param map_name: Optional ConfigMap name t...
def core_periphery_dir(W, gamma=1, C0=None, seed=None): ''' The optimal core/periphery subdivision is a partition of the network into two nonoverlapping groups of nodes, a core group and a periphery group. The number of core-group edges is maximized, and the number of within periphery edges is min...
The optimal core/periphery subdivision is a partition of the network into two nonoverlapping groups of nodes, a core group and a periphery group. The number of core-group edges is maximized, and the number of within periphery edges is minimized. The core-ness is a statistic which quantifies the goodne...
Below is the the instruction that describes the task: ### Input: The optimal core/periphery subdivision is a partition of the network into two nonoverlapping groups of nodes, a core group and a periphery group. The number of core-group edges is maximized, and the number of within periphery edges is min...
def _get_numeric_status(self, key): """Extract the numeric value from the statuses object.""" value = self._get_status(key) if value and any(i.isdigit() for i in value): return float(re.sub("[^0-9.]", "", value)) return None
Extract the numeric value from the statuses object.
Below is the the instruction that describes the task: ### Input: Extract the numeric value from the statuses object. ### Response: def _get_numeric_status(self, key): """Extract the numeric value from the statuses object.""" value = self._get_status(key) if value and any(i.isdigit() for i ...
def _save_and_log_checkpoint(self, actor): """Save an actor checkpoint if necessary and log any errors. Args: actor: The actor to checkpoint. Returns: The result of the actor's user-defined `save_checkpoint` method. """ actor_id = self._worker.actor_id ...
Save an actor checkpoint if necessary and log any errors. Args: actor: The actor to checkpoint. Returns: The result of the actor's user-defined `save_checkpoint` method.
Below is the the instruction that describes the task: ### Input: Save an actor checkpoint if necessary and log any errors. Args: actor: The actor to checkpoint. Returns: The result of the actor's user-defined `save_checkpoint` method. ### Response: def _save_and_log_checkp...
def obbTree(self): """obbTree is an object to generate oriented bounding box (OBB) trees. An oriented bounding box is a bounding box that does not necessarily line up along coordinate axes. The OBB tree is a hierarchical tree structure of such boxes, where deeper levels of OBB co...
obbTree is an object to generate oriented bounding box (OBB) trees. An oriented bounding box is a bounding box that does not necessarily line up along coordinate axes. The OBB tree is a hierarchical tree structure of such boxes, where deeper levels of OBB confine smaller regions of space...
Below is the the instruction that describes the task: ### Input: obbTree is an object to generate oriented bounding box (OBB) trees. An oriented bounding box is a bounding box that does not necessarily line up along coordinate axes. The OBB tree is a hierarchical tree structure of such boxes...
def read_nanopubs(fn: str) -> Iterable[Mapping[str, Any]]: """Read file and generate nanopubs If filename has *.gz, will read as a gzip file If filename has *.jsonl*, will parsed as a JSONLines file IF filename has *.json*, will be parsed as a JSON file If filename has *.yaml* or *.yml*, will be p...
Read file and generate nanopubs If filename has *.gz, will read as a gzip file If filename has *.jsonl*, will parsed as a JSONLines file IF filename has *.json*, will be parsed as a JSON file If filename has *.yaml* or *.yml*, will be parsed as a YAML file Args: filename (str): filename t...
Below is the the instruction that describes the task: ### Input: Read file and generate nanopubs If filename has *.gz, will read as a gzip file If filename has *.jsonl*, will parsed as a JSONLines file IF filename has *.json*, will be parsed as a JSON file If filename has *.yaml* or *.yml*, will b...
def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning: """Construct binning schema compatible with numpy.histogram Parameters ---------- data: array_like, optional This is optional if both bins and range are set bins: int or array_like range: Optional[tuple] ...
Construct binning schema compatible with numpy.histogram Parameters ---------- data: array_like, optional This is optional if both bins and range are set bins: int or array_like range: Optional[tuple] (min, max) includes_right_edge: Optional[bool] default: True See ...
Below is the the instruction that describes the task: ### Input: Construct binning schema compatible with numpy.histogram Parameters ---------- data: array_like, optional This is optional if both bins and range are set bins: int or array_like range: Optional[tuple] (min, max) ...
def _hsig_input(self, index): ''' inputs for the hsig hash ''' hsig_input = z.ZcashByteData() hsig_input += self.tx_joinsplits[index].random_seed hsig_input += self.tx_joinsplits[index].nullifiers hsig_input += self.joinsplit_pubkey return hsig_input.to_by...
inputs for the hsig hash
Below is the the instruction that describes the task: ### Input: inputs for the hsig hash ### Response: def _hsig_input(self, index): ''' inputs for the hsig hash ''' hsig_input = z.ZcashByteData() hsig_input += self.tx_joinsplits[index].random_seed hsig_input += sel...
def cleanup_event_loop(self): """ Cleanup an event loop and close it down forever. """ for task in asyncio.Task.all_tasks(loop=self.loop): if self.debug: warnings.warn('Cancelling task: %s' % task) task._log_destroy_pending = False task.cancel() ...
Cleanup an event loop and close it down forever.
Below is the the instruction that describes the task: ### Input: Cleanup an event loop and close it down forever. ### Response: def cleanup_event_loop(self): """ Cleanup an event loop and close it down forever. """ for task in asyncio.Task.all_tasks(loop=self.loop): if self.debug: ...
def option(self, name, description=None, action=None, resolve=None): """ Add or get option. Here are some examples:: command.option('-v, --verbose', 'show more log') command.option('--tag <tag>', 'tag of the package') command.option('-s, --source <source>', ...
Add or get option. Here are some examples:: command.option('-v, --verbose', 'show more log') command.option('--tag <tag>', 'tag of the package') command.option('-s, --source <source>', 'the source repo') :param name: arguments of the option :param descripti...
Below is the the instruction that describes the task: ### Input: Add or get option. Here are some examples:: command.option('-v, --verbose', 'show more log') command.option('--tag <tag>', 'tag of the package') command.option('-s, --source <source>', 'the source repo') ...
def get_current_url(request, ignore_params=None): """ Giving a django request, return the current http url, possibly ignoring some GET parameters :param django.http.HttpRequest request: The current request object. :param set ignore_params: An optional set of GET parameters to ignore ...
Giving a django request, return the current http url, possibly ignoring some GET parameters :param django.http.HttpRequest request: The current request object. :param set ignore_params: An optional set of GET parameters to ignore :return: The URL of the current page, possibly omitting some para...
Below is the the instruction that describes the task: ### Input: Giving a django request, return the current http url, possibly ignoring some GET parameters :param django.http.HttpRequest request: The current request object. :param set ignore_params: An optional set of GET parameters to ignore ...
def stage_http_response1(self, conn_id, version, status, reason, headers): """Set response http info including headers, status, etc. conn_id unused here. Used in log""" # pylint: disable=attribute-defined-outside-init self._http_response_version = version self._http_response_s...
Set response http info including headers, status, etc. conn_id unused here. Used in log
Below is the the instruction that describes the task: ### Input: Set response http info including headers, status, etc. conn_id unused here. Used in log ### Response: def stage_http_response1(self, conn_id, version, status, reason, headers): """Set response http info including headers, status, e...
def corr_dw_v1(self): """Adjust the water stage drop to the highest value allowed and correct the associated fluxes. Note that method |corr_dw_v1| calls the method `interp_v` of the respective application model. Hence the requirements of the actual `interp_v` need to be considered additionally. ...
Adjust the water stage drop to the highest value allowed and correct the associated fluxes. Note that method |corr_dw_v1| calls the method `interp_v` of the respective application model. Hence the requirements of the actual `interp_v` need to be considered additionally. Required control parameter...
Below is the the instruction that describes the task: ### Input: Adjust the water stage drop to the highest value allowed and correct the associated fluxes. Note that method |corr_dw_v1| calls the method `interp_v` of the respective application model. Hence the requirements of the actual `interp_v...
def evaluate(dataset, predictions, output_folder, **kwargs): """evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the prediction results for one image. output_folder: outp...
evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the prediction results for one image. output_folder: output folder, to save evaluation files or results. **kwargs: ot...
Below is the the instruction that describes the task: ### Input: evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the prediction results for one image. output_folder: out...
def create_job(JobType=None, Resources=None, Description=None, AddressId=None, KmsKeyARN=None, RoleARN=None, SnowballCapacityPreference=None, ShippingOption=None, Notification=None, ClusterId=None, SnowballType=None, ForwardingAddressId=None): """ Creates a job to import or export data between Amazon S3 and you...
Creates a job to import or export data between Amazon S3 and your on-premises data center. Your AWS account must have the right trust policies and permissions in place to create a job for Snowball. If you're creating a job for a node in a cluster, you only need to provide the clusterId value; the other job attributes a...
Below is the the instruction that describes the task: ### Input: Creates a job to import or export data between Amazon S3 and your on-premises data center. Your AWS account must have the right trust policies and permissions in place to create a job for Snowball. If you're creating a job for a node in a cluster, you...
def form_adverb_from_adjective(adjective): """ Forms an adverb from the input adjective, f.ex. "happy" => "happily". Adverbs are generated using rules from: http://www.edufind.com/english-grammar/forming-adverbs-adjectives/ :param adjective: adjective :return: adverb form of the input adjective ...
Forms an adverb from the input adjective, f.ex. "happy" => "happily". Adverbs are generated using rules from: http://www.edufind.com/english-grammar/forming-adverbs-adjectives/ :param adjective: adjective :return: adverb form of the input adjective
Below is the the instruction that describes the task: ### Input: Forms an adverb from the input adjective, f.ex. "happy" => "happily". Adverbs are generated using rules from: http://www.edufind.com/english-grammar/forming-adverbs-adjectives/ :param adjective: adjective :return: adverb form of the input...
def tx2genefile(gtf, out_file=None): """ write out a file of transcript->gene mappings. use the installed tx2gene.csv if it exists, else write a new one out """ installed_tx2gene = os.path.join(os.path.dirname(gtf), "tx2gene.csv") if file_exists(installed_tx2gene): return installed_tx2ge...
write out a file of transcript->gene mappings. use the installed tx2gene.csv if it exists, else write a new one out
Below is the the instruction that describes the task: ### Input: write out a file of transcript->gene mappings. use the installed tx2gene.csv if it exists, else write a new one out ### Response: def tx2genefile(gtf, out_file=None): """ write out a file of transcript->gene mappings. use the installe...
def GetFileObject(self, data_stream_name=''): """Retrieves the file-like object. Args: data_stream_name (Optional[str]): name of the data stream, where an empty string represents the default data stream. Returns: FakeFileIO: a file-like object or None if not available. Raises: ...
Retrieves the file-like object. Args: data_stream_name (Optional[str]): name of the data stream, where an empty string represents the default data stream. Returns: FakeFileIO: a file-like object or None if not available. Raises: IOError: if the file entry is not a file. ...
Below is the the instruction that describes the task: ### Input: Retrieves the file-like object. Args: data_stream_name (Optional[str]): name of the data stream, where an empty string represents the default data stream. Returns: FakeFileIO: a file-like object or None if not available...
def mux_pilot_blocks(IQ_data, Np): """ Parameters ---------- IQ_data : a 2D array of input QAM symbols with the columns representing the NF carrier frequencies and each row the QAM symbols used to form an OFDM symbol Np : the period of the pilot blocks; e.g., a pilot bl...
Parameters ---------- IQ_data : a 2D array of input QAM symbols with the columns representing the NF carrier frequencies and each row the QAM symbols used to form an OFDM symbol Np : the period of the pilot blocks; e.g., a pilot block is inserted every Np OFDM sy...
Below is the the instruction that describes the task: ### Input: Parameters ---------- IQ_data : a 2D array of input QAM symbols with the columns representing the NF carrier frequencies and each row the QAM symbols used to form an OFDM symbol Np : the period of the pilot bl...
def long_press(self, locator, duration=1000): """ Long press the element with optional duration """ driver = self._current_application() element = self._element_find(locator, True, True) action = TouchAction(driver) action.press(element).wait(duration).release().perform()
Long press the element with optional duration
Below is the the instruction that describes the task: ### Input: Long press the element with optional duration ### Response: def long_press(self, locator, duration=1000): """ Long press the element with optional duration """ driver = self._current_application() element = self._element_fi...
def select_by_mtime(self, min_time=0, max_time=ts_2100, recursive=True): """ Select file path by modify time. :param min_time: lower bound timestamp :param max_time: upper bound timestamp **中文文档** 选择所有 :attr:`pathlib_mate.pathlib2.Path.mtime` 在一...
Select file path by modify time. :param min_time: lower bound timestamp :param max_time: upper bound timestamp **中文文档** 选择所有 :attr:`pathlib_mate.pathlib2.Path.mtime` 在一定范围内的文件。
Below is the the instruction that describes the task: ### Input: Select file path by modify time. :param min_time: lower bound timestamp :param max_time: upper bound timestamp **中文文档** 选择所有 :attr:`pathlib_mate.pathlib2.Path.mtime` 在一定范围内的文件。 ### Response: def select_by_mtime(self...
def getexcfo(e): ''' Get an err tufo from an exception. Args: e (Exception): An Exception (or Exception subclass). Notes: This can be called outside of the context of an exception handler, however details such as file, line, function name and source may be missing. ...
Get an err tufo from an exception. Args: e (Exception): An Exception (or Exception subclass). Notes: This can be called outside of the context of an exception handler, however details such as file, line, function name and source may be missing. Returns: ((str, dict...
Below is the the instruction that describes the task: ### Input: Get an err tufo from an exception. Args: e (Exception): An Exception (or Exception subclass). Notes: This can be called outside of the context of an exception handler, however details such as file, line, function name...
def from_file(filename, output_path, options=None, toc=None, cover=None, css=None, config=None, cover_first=None): """ Convert HTML file/files to IMG file/files :param filename: path of HTML file or list with ...
Convert HTML file/files to IMG file/files :param filename: path of HTML file or list with paths or file-like object :param output_path: path to output PDF file/files. False means file will be returned as string :param options: (optional) dict with wkhtmltopdf global and page options, with or w/o '--' :...
Below is the the instruction that describes the task: ### Input: Convert HTML file/files to IMG file/files :param filename: path of HTML file or list with paths or file-like object :param output_path: path to output PDF file/files. False means file will be returned as string :param options: (optional) ...
def send_message(self, id: str, message: str) -> Dict[str, Any]: """Send a message to a channel For formatting options, see the documentation: https://discordapp.com/developers/docs/resources/channel#create-message Args: id: channel snowflake id message: you...
Send a message to a channel For formatting options, see the documentation: https://discordapp.com/developers/docs/resources/channel#create-message Args: id: channel snowflake id message: your message (string) Returns: Dictionary object of the ne...
Below is the the instruction that describes the task: ### Input: Send a message to a channel For formatting options, see the documentation: https://discordapp.com/developers/docs/resources/channel#create-message Args: id: channel snowflake id message: your messa...
def covstr(strings): """ convert string to int or float. """ try: result = int(strings) except ValueError: result = float(strings) return result
convert string to int or float.
Below is the the instruction that describes the task: ### Input: convert string to int or float. ### Response: def covstr(strings): """ convert string to int or float. """ try: result = int(strings) except ValueError: result = float(strings) return result
def prepare_info(self, ts=None): """Return all session unique ids recorded in prepare phase. :param ts: timestamp, default to current timestamp :return: set of session unique ids """ sp_key = "%s:session_prepare" % self.namespace(ts or int(time.time())) return set(s(m) f...
Return all session unique ids recorded in prepare phase. :param ts: timestamp, default to current timestamp :return: set of session unique ids
Below is the the instruction that describes the task: ### Input: Return all session unique ids recorded in prepare phase. :param ts: timestamp, default to current timestamp :return: set of session unique ids ### Response: def prepare_info(self, ts=None): """Return all session unique ids re...
def get_vertices_per_edge(mesh_v, mesh_f): """Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. If output of get_faces_per_edge is provided, this is used to avoid call to get_vert_connectivity()""" vc = sp.coo_m...
Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. If output of get_faces_per_edge is provided, this is used to avoid call to get_vert_connectivity()
Below is the the instruction that describes the task: ### Input: Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. If output of get_faces_per_edge is provided, this is used to avoid call to get_vert_connectivity() ##...
def functions_shadowed(self): ''' Return the list of functions shadowed Returns: list(core.Function) ''' candidates = [c.functions_not_inherited for c in self.contract.inheritance] candidates = [candidate for sublist in candidates for candidate in sublist...
Return the list of functions shadowed Returns: list(core.Function)
Below is the the instruction that describes the task: ### Input: Return the list of functions shadowed Returns: list(core.Function) ### Response: def functions_shadowed(self): ''' Return the list of functions shadowed Returns: list(core.Function) ...
def delete_relay(self, relayid, data): """Delete relay settings""" return self.api_call( ENDPOINTS['relays']['delete'], dict(relayid=relayid), body=data)
Delete relay settings
Below is the the instruction that describes the task: ### Input: Delete relay settings ### Response: def delete_relay(self, relayid, data): """Delete relay settings""" return self.api_call( ENDPOINTS['relays']['delete'], dict(relayid=relayid), body=data)
def _get_dep_statuses(self, ti, session, dep_context): """ Determines whether a task is ready to be rescheduled. Only tasks in NONE state with at least one row in task_reschedule table are handled by this dependency class, otherwise this dependency is considered as passed. This d...
Determines whether a task is ready to be rescheduled. Only tasks in NONE state with at least one row in task_reschedule table are handled by this dependency class, otherwise this dependency is considered as passed. This dependency fails if the latest reschedule request's reschedule date ...
Below is the the instruction that describes the task: ### Input: Determines whether a task is ready to be rescheduled. Only tasks in NONE state with at least one row in task_reschedule table are handled by this dependency class, otherwise this dependency is considered as passed. This depende...
def set_value(self, value, block_events=False): """ Sets the current value of the number box. Setting block_events=True will temporarily block the widget from sending any signals when setting the value. """ if block_events: self.block_events() self._widget.setVal...
Sets the current value of the number box. Setting block_events=True will temporarily block the widget from sending any signals when setting the value.
Below is the the instruction that describes the task: ### Input: Sets the current value of the number box. Setting block_events=True will temporarily block the widget from sending any signals when setting the value. ### Response: def set_value(self, value, block_events=False): """ ...
def _validate(self, writing=False): """Verify that the box obeys the specifications.""" if self.colorspace is not None and self.icc_profile is not None: msg = ("Colorspace and icc_profile cannot both be set when " "creating a ColourSpecificationBox.") self._dis...
Verify that the box obeys the specifications.
Below is the the instruction that describes the task: ### Input: Verify that the box obeys the specifications. ### Response: def _validate(self, writing=False): """Verify that the box obeys the specifications.""" if self.colorspace is not None and self.icc_profile is not None: msg = ("C...
def to_float(b:Collection[Tensor])->Collection[Tensor]: "Recursively map lists of tensors in `b ` to FP16." if is_listy(b): return [to_float(o) for o in b] return b.float() if b.dtype not in [torch.int64, torch.int32, torch.int16] else b
Recursively map lists of tensors in `b ` to FP16.
Below is the the instruction that describes the task: ### Input: Recursively map lists of tensors in `b ` to FP16. ### Response: def to_float(b:Collection[Tensor])->Collection[Tensor]: "Recursively map lists of tensors in `b ` to FP16." if is_listy(b): return [to_float(o) for o in b] return b.float() i...
def create_uaa(self, admin_secret, **kwargs): """ Creates an instance of UAA Service. :param admin_secret: The secret password for administering the service such as adding clients and users. """ uaa = predix.admin.uaa.UserAccountAuthentication(**kwargs) if no...
Creates an instance of UAA Service. :param admin_secret: The secret password for administering the service such as adding clients and users.
Below is the the instruction that describes the task: ### Input: Creates an instance of UAA Service. :param admin_secret: The secret password for administering the service such as adding clients and users. ### Response: def create_uaa(self, admin_secret, **kwargs): """ Creates ...
def handle_oauth1_response(self, args): """Handles an oauth1 authorization response.""" client = self.make_client() client.verifier = args.get('oauth_verifier') tup = session.get('%s_oauthtok' % self.name) if not tup: raise OAuthException( 'Token not f...
Handles an oauth1 authorization response.
Below is the the instruction that describes the task: ### Input: Handles an oauth1 authorization response. ### Response: def handle_oauth1_response(self, args): """Handles an oauth1 authorization response.""" client = self.make_client() client.verifier = args.get('oauth_verifier') t...
def interpolate_nearest(self, lons, lats, data): """ Interpolate using nearest-neighbour approximation Returns the same as interpolate(lons,lats,data,order=0) """ return self.interpolate(lons, lats, data, order=0)
Interpolate using nearest-neighbour approximation Returns the same as interpolate(lons,lats,data,order=0)
Below is the the instruction that describes the task: ### Input: Interpolate using nearest-neighbour approximation Returns the same as interpolate(lons,lats,data,order=0) ### Response: def interpolate_nearest(self, lons, lats, data): """ Interpolate using nearest-neighbour approximation ...
def _set_access_mac_vlan_classification(self, v, load=False): """ Setter method for access_mac_vlan_classification, mapped from YANG variable /interface/ethernet/switchport/access_mac_vlan_classification (container) If this variable is read-only (config: false) in the source YANG file, then _set_access_...
Setter method for access_mac_vlan_classification, mapped from YANG variable /interface/ethernet/switchport/access_mac_vlan_classification (container) If this variable is read-only (config: false) in the source YANG file, then _set_access_mac_vlan_classification is considered as a private method. Backends lo...
Below is the the instruction that describes the task: ### Input: Setter method for access_mac_vlan_classification, mapped from YANG variable /interface/ethernet/switchport/access_mac_vlan_classification (container) If this variable is read-only (config: false) in the source YANG file, then _set_access_mac_v...
async def handle_request(self, channel: Channel, body, envelope, properties, futurize=True): """ the 'futurize' param is simply because aioamqp doesnt send another job until this method returns (completes), so we ensure the future of ourselves and return im...
the 'futurize' param is simply because aioamqp doesnt send another job until this method returns (completes), so we ensure the future of ourselves and return immediately so we can handle many requests at a time.
Below is the the instruction that describes the task: ### Input: the 'futurize' param is simply because aioamqp doesnt send another job until this method returns (completes), so we ensure the future of ourselves and return immediately so we can handle many requests at a time. ### Response...