code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def publish(self, cart, env=None): """ `cart` - Release cart to publish in json format Publish a release cart in JSON format to the pre-release environment. """ juicer.utils.Log.log_debug("Initializing publish of cart '%s'" % cart.cart_name) if not env: env ...
`cart` - Release cart to publish in json format Publish a release cart in JSON format to the pre-release environment.
Below is the the instruction that describes the task: ### Input: `cart` - Release cart to publish in json format Publish a release cart in JSON format to the pre-release environment. ### Response: def publish(self, cart, env=None): """ `cart` - Release cart to publish in json format ...
def do_checkout(self, subcmd, opts, *args): """Check out a working copy from a repository. usage: checkout URL... [PATH] Note: If PATH is omitted, the basename of the URL will be used as the destination. If multiple URLs are given each will be checked out in...
Check out a working copy from a repository. usage: checkout URL... [PATH] Note: If PATH is omitted, the basename of the URL will be used as the destination. If multiple URLs are given each will be checked out into a sub-directory of PATH, with the name of the sub-di...
Below is the the instruction that describes the task: ### Input: Check out a working copy from a repository. usage: checkout URL... [PATH] Note: If PATH is omitted, the basename of the URL will be used as the destination. If multiple URLs are given each will be checked ...
def generate_data_for_registered_problem(problem_name): """Generate data for a registered problem.""" tf.logging.info("Generating data for %s.", problem_name) if FLAGS.num_shards: raise ValueError("--num_shards should not be set for registered Problem.") problem = registry.problem(problem_name) task_id = ...
Generate data for a registered problem.
Below is the the instruction that describes the task: ### Input: Generate data for a registered problem. ### Response: def generate_data_for_registered_problem(problem_name): """Generate data for a registered problem.""" tf.logging.info("Generating data for %s.", problem_name) if FLAGS.num_shards: raise ...
def save_file(self, title="Save As", initialDir="~", fileTypes="*|All Files", rememberAs=None, **kwargs): """ Show a Save As dialog Usage: C{dialog.save_file(title="Save As", initialDir="~", fileTypes="*|All Files", rememberAs=None, **kwargs)} @param title: window title...
Show a Save As dialog Usage: C{dialog.save_file(title="Save As", initialDir="~", fileTypes="*|All Files", rememberAs=None, **kwargs)} @param title: window title for the dialog @param initialDir: starting directory for the file dialog @param fileTypes: file type filter e...
Below is the the instruction that describes the task: ### Input: Show a Save As dialog Usage: C{dialog.save_file(title="Save As", initialDir="~", fileTypes="*|All Files", rememberAs=None, **kwargs)} @param title: window title for the dialog @param initialDir: starting direc...
def api_range( self, serial: str, date: Optional[timelike] = None ) -> SensorRange: """Wraps a polygon representing a sensor's range. By default, returns the current range. Otherwise, you may enter a specific day (as a string, as an epoch or as a datetime) """ if da...
Wraps a polygon representing a sensor's range. By default, returns the current range. Otherwise, you may enter a specific day (as a string, as an epoch or as a datetime)
Below is the the instruction that describes the task: ### Input: Wraps a polygon representing a sensor's range. By default, returns the current range. Otherwise, you may enter a specific day (as a string, as an epoch or as a datetime) ### Response: def api_range( self, serial: str, date: O...
def evaluate_at(self, eval_at, testcases, mode=None): """ Sets the evaluation interation indices. :param list eval_at: iteration indices where an evaluation should be performed :param numpy.array testcases: testcases used for evaluation """ self.eval_at = eval_at ...
Sets the evaluation interation indices. :param list eval_at: iteration indices where an evaluation should be performed :param numpy.array testcases: testcases used for evaluation
Below is the the instruction that describes the task: ### Input: Sets the evaluation interation indices. :param list eval_at: iteration indices where an evaluation should be performed :param numpy.array testcases: testcases used for evaluation ### Response: def evaluate_at(self, eval_at, t...
def time_seg_to_index(time_str, slide_step): """ 将时间片字符串转换为时间片索引值 :param time_str: eg: '11:10:21' :param slide_step: :return: """ minutes_idx = time_util.time_str_to_minutes(time_str) time_seg_idx = minutes_idx // slide_step return time_seg_idx
将时间片字符串转换为时间片索引值 :param time_str: eg: '11:10:21' :param slide_step: :return:
Below is the the instruction that describes the task: ### Input: 将时间片字符串转换为时间片索引值 :param time_str: eg: '11:10:21' :param slide_step: :return: ### Response: def time_seg_to_index(time_str, slide_step): """ 将时间片字符串转换为时间片索引值 :param time_str: eg: '11:10:21' :param slide_step: :return: ...
def mate(self, other): "Return a new individual crossing self and other." c = random.randrange(len(self.genes)) return self.__class__(self.genes[:c] + other.genes[c:])
Return a new individual crossing self and other.
Below is the the instruction that describes the task: ### Input: Return a new individual crossing self and other. ### Response: def mate(self, other): "Return a new individual crossing self and other." c = random.randrange(len(self.genes)) return self.__class__(self.genes[:c] + other.genes[...
def make_sign(api_secret, params=[]): """ >>> make_sign("123456",[1,'2',u'中文']) '33C9065427EECA3490C5642C99165145' """ _params = [utils.safeunicode(p) for p in params if p is not None] _params.sort() # print 'sorted params:',_params _params.insert(0, api_secret) strs = ''.joi...
>>> make_sign("123456",[1,'2',u'中文']) '33C9065427EECA3490C5642C99165145'
Below is the the instruction that describes the task: ### Input: >>> make_sign("123456",[1,'2',u'中文']) '33C9065427EECA3490C5642C99165145' ### Response: def make_sign(api_secret, params=[]): """ >>> make_sign("123456",[1,'2',u'中文']) '33C9065427EECA3490C5642C99165145' """ _params ...
def load(path, bigdl_type="float"): """ Load a pre-trained Bigdl model. :param path: The path containing the pre-trained model. :return: A pre-trained model. """ jmodel = callBigDlFunc(bigdl_type, "loadBigDL", path) return Layer.of(jmodel)
Load a pre-trained Bigdl model. :param path: The path containing the pre-trained model. :return: A pre-trained model.
Below is the the instruction that describes the task: ### Input: Load a pre-trained Bigdl model. :param path: The path containing the pre-trained model. :return: A pre-trained model. ### Response: def load(path, bigdl_type="float"): """ Load a pre-trained Bigdl model. :par...
def get_authorization_url(self, signin_with_twitter=False, access_type=None): """Get the authorization URL to redirect the user""" try: if signin_with_twitter: url = self._get_oauth_url('authenticate') ...
Get the authorization URL to redirect the user
Below is the the instruction that describes the task: ### Input: Get the authorization URL to redirect the user ### Response: def get_authorization_url(self, signin_with_twitter=False, access_type=None): """Get the authorization URL to redirect th...
def _changeMs(self, line): """Change the ms part in the string if needed.""" # use the position of the last space instead try: last_space_pos = line.rindex(' ') except ValueError: return line else: end_str = line[last_space_pos:] ne...
Change the ms part in the string if needed.
Below is the the instruction that describes the task: ### Input: Change the ms part in the string if needed. ### Response: def _changeMs(self, line): """Change the ms part in the string if needed.""" # use the position of the last space instead try: last_space_pos = line.rindex(...
def distance_stats(x, y, **kwargs): """ distance_stats(x, y, *, exponent=1) Computes the usual (biased) estimators for the distance covariance and distance correlation between two random vectors, and the individual distance variances. Parameters ---------- x: array_like First r...
distance_stats(x, y, *, exponent=1) Computes the usual (biased) estimators for the distance covariance and distance correlation between two random vectors, and the individual distance variances. Parameters ---------- x: array_like First random vector. The columns correspond with the in...
Below is the the instruction that describes the task: ### Input: distance_stats(x, y, *, exponent=1) Computes the usual (biased) estimators for the distance covariance and distance correlation between two random vectors, and the individual distance variances. Parameters ---------- x: array...
def ND_all_available(): """Return an array of available nominal diameters. NDs available are those commonly used as based on the 'Used' column in the pipedb. """ ND_all_available = [] for i in range(len(pipedb['NDinch'])): if pipedb.iloc[i, 4] == 1: ND_all_available.append((...
Return an array of available nominal diameters. NDs available are those commonly used as based on the 'Used' column in the pipedb.
Below is the the instruction that describes the task: ### Input: Return an array of available nominal diameters. NDs available are those commonly used as based on the 'Used' column in the pipedb. ### Response: def ND_all_available(): """Return an array of available nominal diameters. NDs availabl...
def precondition_u_kn(u_kn, N_k, f_k): """Subtract a sample-dependent constant from u_kn to improve precision Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_s...
Subtract a sample-dependent constant from u_kn to improve precision Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_states), dtype='int' The number of samp...
Below is the the instruction that describes the task: ### Input: Subtract a sample-dependent constant from u_kn to improve precision Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k :...
def find_gamma_params(mode, std): """Given a modal value and a standard deviation, compute corresponding parameters for the gamma distribution. Intended to be used to replace normal distributions when the value must be positive and the uncertainty is comparable to the best value. Conversion equatio...
Given a modal value and a standard deviation, compute corresponding parameters for the gamma distribution. Intended to be used to replace normal distributions when the value must be positive and the uncertainty is comparable to the best value. Conversion equations determined from the relations given in...
Below is the the instruction that describes the task: ### Input: Given a modal value and a standard deviation, compute corresponding parameters for the gamma distribution. Intended to be used to replace normal distributions when the value must be positive and the uncertainty is comparable to the best v...
def rename_backup(name, suffix='.bak'): """ Append a backup prefix to a file or directory, with an increasing numeric suffix (.N) if a file already exists """ newname = '%s%s' % (name, suffix) n = 0 while os.path.exists(newname): n += 1 newname = '%s%s.%d' % (name, suffix, n)...
Append a backup prefix to a file or directory, with an increasing numeric suffix (.N) if a file already exists
Below is the the instruction that describes the task: ### Input: Append a backup prefix to a file or directory, with an increasing numeric suffix (.N) if a file already exists ### Response: def rename_backup(name, suffix='.bak'): """ Append a backup prefix to a file or directory, with an increasing num...
def from_bucket(cls, connection, bucket): """Create from bucket object.""" if bucket is None: raise errors.NoContainerException # It appears that Amazon does not have a single-shot REST query to # determine the number of keys / overall byte size of a bucket. return c...
Create from bucket object.
Below is the the instruction that describes the task: ### Input: Create from bucket object. ### Response: def from_bucket(cls, connection, bucket): """Create from bucket object.""" if bucket is None: raise errors.NoContainerException # It appears that Amazon does not have a sin...
def from_spec(spec, kwargs=None): """ Creates a layer from a specification dict. """ layer = util.get_object( obj=spec, predefined_objects=tensorforce.core.networks.layers, kwargs=kwargs ) assert isinstance(layer, Layer) return ...
Creates a layer from a specification dict.
Below is the the instruction that describes the task: ### Input: Creates a layer from a specification dict. ### Response: def from_spec(spec, kwargs=None): """ Creates a layer from a specification dict. """ layer = util.get_object( obj=spec, predefined_object...
def _serialize_default(cls, obj): """ :type obj: int|str|bool|float|bytes|unicode|list|dict|object :rtype: int|str|bool|list|dict """ if obj is None or cls._is_primitive(obj): return obj elif cls._is_bytes(obj): return obj.decode() elif t...
:type obj: int|str|bool|float|bytes|unicode|list|dict|object :rtype: int|str|bool|list|dict
Below is the the instruction that describes the task: ### Input: :type obj: int|str|bool|float|bytes|unicode|list|dict|object :rtype: int|str|bool|list|dict ### Response: def _serialize_default(cls, obj): """ :type obj: int|str|bool|float|bytes|unicode|list|dict|object :rtype: int...
def encode(data, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8, case_sensitive=True): """Creates a QR-Code from string data. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encoded in UTF-8. version: int: The minimum version ...
Creates a QR-Code from string data. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encoded in UTF-8. version: int: The minimum version to use. If set to 0, the library picks the smallest version that the data fits in. level...
Below is the the instruction that describes the task: ### Input: Creates a QR-Code from string data. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encoded in UTF-8. version: int: The minimum version to use. If set to 0, the library pi...
def get_config_filename(args): '''get the file name of config file''' experiment_id = check_experiment_id(args) if experiment_id is None: print_error('Please set the experiment id!') exit(1) experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() ...
get the file name of config file
Below is the the instruction that describes the task: ### Input: get the file name of config file ### Response: def get_config_filename(args): '''get the file name of config file''' experiment_id = check_experiment_id(args) if experiment_id is None: print_error('Please set the experiment id!') ...
def decode(self, encoded, parentFieldName=''): """ See the function description in base.py """ assert (encoded[0:self.n] <= 1.0).all() resultString = "" resultRanges = [] overlaps = (self.sdrs * encoded[0:self.n]).sum(axis=1) if self.verbosity >= 2: print "Overlaps for decoding:"...
See the function description in base.py
Below is the the instruction that describes the task: ### Input: See the function description in base.py ### Response: def decode(self, encoded, parentFieldName=''): """ See the function description in base.py """ assert (encoded[0:self.n] <= 1.0).all() resultString = "" resultRanges = [] ...
def segment(self, line): """ Tokenizes single sentence and adds special BOS and EOS tokens. :param line: sentence returns: list representing tokenized sentence """ line = line.strip().split() entry = [self.tok2idx[i] for i in line] entry = [config.BOS] +...
Tokenizes single sentence and adds special BOS and EOS tokens. :param line: sentence returns: list representing tokenized sentence
Below is the the instruction that describes the task: ### Input: Tokenizes single sentence and adds special BOS and EOS tokens. :param line: sentence returns: list representing tokenized sentence ### Response: def segment(self, line): """ Tokenizes single sentence and adds special...
def build_source_files(self): """Return acessors to the build files""" from .files import BuildSourceFileAccessor return BuildSourceFileAccessor(self, self.dataset, self.source_fs)
Return acessors to the build files
Below is the the instruction that describes the task: ### Input: Return acessors to the build files ### Response: def build_source_files(self): """Return acessors to the build files""" from .files import BuildSourceFileAccessor return BuildSourceFileAccessor(self, self.dataset, self.source...
def run_main(args): """Execute job/task submission from command-line arguments.""" if args.command and args.script: raise ValueError('Cannot supply both a --command and --script flag') provider_base.check_for_unsupported_flag(args) # Set up job parameters and job data from a tasks file or flags. input_...
Execute job/task submission from command-line arguments.
Below is the the instruction that describes the task: ### Input: Execute job/task submission from command-line arguments. ### Response: def run_main(args): """Execute job/task submission from command-line arguments.""" if args.command and args.script: raise ValueError('Cannot supply both a --command and -...
def _position_in_feature(pos_a, pos_b): """return distance to 3' and 5' end of the feature""" strd = "-" if pos_a[2] in pos_b[2]: strd = "+" if pos_a[2] in "+" and pos_b[2] in "+": lento5 = pos_a[0] - pos_b[1] + 1 lento3 = pos_a[1] - pos_b[1] + 1 if pos_a[2] in "+" and pos_b[...
return distance to 3' and 5' end of the feature
Below is the the instruction that describes the task: ### Input: return distance to 3' and 5' end of the feature ### Response: def _position_in_feature(pos_a, pos_b): """return distance to 3' and 5' end of the feature""" strd = "-" if pos_a[2] in pos_b[2]: strd = "+" if pos_a[2] in "+" and ...
def metadata(self): """ Retrieve the metadata info for this prefix Returns: dict: metadata info """ if self._metadata is None: try: with open(self.paths.metadata()) as metadata_fd: self._metadata = json.load(metadata_fd...
Retrieve the metadata info for this prefix Returns: dict: metadata info
Below is the the instruction that describes the task: ### Input: Retrieve the metadata info for this prefix Returns: dict: metadata info ### Response: def metadata(self): """ Retrieve the metadata info for this prefix Returns: dict: metadata info ""...
def _batch_entry_run(self): """The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properly unit tested. """ time.sleep(self.secs_between_batches) with self._batch_lock: self.process_batches()
The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properly unit tested.
Below is the the instruction that describes the task: ### Input: The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properly unit tested. ### Response: def _batch_entry_run(self): """The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properl...
def lex(self, text): """ Yield (token_type, str_data) tokens. The last token will be (EOF, None) where EOF is the singleton object defined in this module. """ for match in self.regex.finditer(text): for name, _ in self.lexicon: m = match.group(name) ...
Yield (token_type, str_data) tokens. The last token will be (EOF, None) where EOF is the singleton object defined in this module.
Below is the the instruction that describes the task: ### Input: Yield (token_type, str_data) tokens. The last token will be (EOF, None) where EOF is the singleton object defined in this module. ### Response: def lex(self, text): """ Yield (token_type, str_data) tokens. The last t...
def getrawfile(self, project_id, sha1, filepath): """ Get the raw file contents for a file by commit SHA and path. :param project_id: The ID of a project :param sha1: The commit or branch name :param filepath: The path the file :return: raw file contents """ ...
Get the raw file contents for a file by commit SHA and path. :param project_id: The ID of a project :param sha1: The commit or branch name :param filepath: The path the file :return: raw file contents
Below is the the instruction that describes the task: ### Input: Get the raw file contents for a file by commit SHA and path. :param project_id: The ID of a project :param sha1: The commit or branch name :param filepath: The path the file :return: raw file contents ### Response: de...
async def govt(self, root): """Nation's government expenditure, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ keys of str and values of float Keys being, in order: ``Administration``, ``Defense``, ``Educat...
Nation's government expenditure, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ keys of str and values of float Keys being, in order: ``Administration``, ``Defense``, ``Education``, ``Environment``, ``Healthcare``,...
Below is the the instruction that describes the task: ### Input: Nation's government expenditure, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ keys of str and values of float Keys being, in order: ``Administration``, ``D...
def get(self, name, defval=None): ''' Retrieve a value from the closest scope frame. ''' for frame in reversed(self.frames): valu = frame.get(name, s_common.novalu) if valu != s_common.novalu: return valu task = self.ctors.get(name) ...
Retrieve a value from the closest scope frame.
Below is the the instruction that describes the task: ### Input: Retrieve a value from the closest scope frame. ### Response: def get(self, name, defval=None): ''' Retrieve a value from the closest scope frame. ''' for frame in reversed(self.frames): valu = frame.get(nam...
def get_attachment_formset(self, formset_class): """ Returns an instance of the attachment formset to be used in the view. """ if ( self.request.forum_permission_handler.can_attach_files( self.get_forum(), self.request.user, ) ): return formset...
Returns an instance of the attachment formset to be used in the view.
Below is the the instruction that describes the task: ### Input: Returns an instance of the attachment formset to be used in the view. ### Response: def get_attachment_formset(self, formset_class): """ Returns an instance of the attachment formset to be used in the view. """ if ( self.r...
def get_agent_lookup_session(self): """Gets the ``OsidSession`` associated with the agent lookup service. return: (osid.authentication.AgentLookupSession) - an ``AgentLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_...
Gets the ``OsidSession`` associated with the agent lookup service. return: (osid.authentication.AgentLookupSession) - an ``AgentLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_agent_lookup()`` is ``false`` *complian...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the agent lookup service. return: (osid.authentication.AgentLookupSession) - an ``AgentLookupSession`` raise: OperationFailed - unable to complete request raise: Unimp...
def max_marginal(self, variables=None, evidence=None, elimination_order=None): """ Computes the max-marginal over the variables given the evidence. Parameters ---------- variables: list list of variables over which we want to compute the max-marginal. evidenc...
Computes the max-marginal over the variables given the evidence. Parameters ---------- variables: list list of variables over which we want to compute the max-marginal. evidence: dict a dict key, value pair as {var: state_of_var_observed} None if no e...
Below is the the instruction that describes the task: ### Input: Computes the max-marginal over the variables given the evidence. Parameters ---------- variables: list list of variables over which we want to compute the max-marginal. evidence: dict a dict key...
def default(self, o): # pylint: disable=method-hidden """Support more object types.""" if isinstance(o, set): return list(sorted(o)) elif hasattr(o, 'as_dict'): return o.as_dict() else: return super(JSONEncoder, self).default(o)
Support more object types.
Below is the the instruction that describes the task: ### Input: Support more object types. ### Response: def default(self, o): # pylint: disable=method-hidden """Support more object types.""" if isinstance(o, set): return list(sorted(o)) elif hasattr(o, 'as_dict'): ...
def _text_to_string(self, text): """ Provides for escape characters and converting to pdf text object (pdf strings are in parantheses). Mainly for use in the information block here, this functionality is also present in the text object. """ if text: ...
Provides for escape characters and converting to pdf text object (pdf strings are in parantheses). Mainly for use in the information block here, this functionality is also present in the text object.
Below is the the instruction that describes the task: ### Input: Provides for escape characters and converting to pdf text object (pdf strings are in parantheses). Mainly for use in the information block here, this functionality is also present in the text object. ### Response...
def prettyMemory(k, field=None, isBytes=False): """ Given input k as kilobytes, return a nicely formatted string. """ if isBytes: k /= 1024 if k < 1024: return padStr("%gK" % k, field) if k < (1024 * 1024): return padStr("%.1fM" % (old_div(k, 1024.0)), field) if k < (1024...
Given input k as kilobytes, return a nicely formatted string.
Below is the the instruction that describes the task: ### Input: Given input k as kilobytes, return a nicely formatted string. ### Response: def prettyMemory(k, field=None, isBytes=False): """ Given input k as kilobytes, return a nicely formatted string. """ if isBytes: k /= 1024 if k < 102...
def main(json_file): """ cachemaker.py creates a precache datastore of all available apis of CloudStack and dumps the precache dictionary in an importable python module. This way we cheat on the runtime overhead of completing commands and help docs. This reduces the overall search and cache_miss...
cachemaker.py creates a precache datastore of all available apis of CloudStack and dumps the precache dictionary in an importable python module. This way we cheat on the runtime overhead of completing commands and help docs. This reduces the overall search and cache_miss (computation) complexity from O(...
Below is the the instruction that describes the task: ### Input: cachemaker.py creates a precache datastore of all available apis of CloudStack and dumps the precache dictionary in an importable python module. This way we cheat on the runtime overhead of completing commands and help docs. This reduces t...
def parse_node(self, node): """ Parses the specified child task node, and returns the task spec. This can be called by a TaskParser instance, that is owned by this ProcessParser. """ if node.get('id') in self.parsed_nodes: return self.parsed_nodes[node.get('i...
Parses the specified child task node, and returns the task spec. This can be called by a TaskParser instance, that is owned by this ProcessParser.
Below is the the instruction that describes the task: ### Input: Parses the specified child task node, and returns the task spec. This can be called by a TaskParser instance, that is owned by this ProcessParser. ### Response: def parse_node(self, node): """ Parses the specified chil...
def list_user_requests_view(request, targetUsername): ''' Show user his/her requests in list form. ''' if targetUsername == request.user.username: return list_my_requests_view(request) targetUser = get_object_or_404(User, username=targetUsername) targetProfile = get_object_or_404(UserPr...
Show user his/her requests in list form.
Below is the the instruction that describes the task: ### Input: Show user his/her requests in list form. ### Response: def list_user_requests_view(request, targetUsername): ''' Show user his/her requests in list form. ''' if targetUsername == request.user.username: return list_my_requests_...
def UV_H(self): """ UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U) K = all closed sets This is UV_H function, but the returned implications are respected by all attribute sets of this context. This corresponds to a multiplication or & ...
UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U) K = all closed sets This is UV_H function, but the returned implications are respected by all attribute sets of this context. This corresponds to a multiplication or & operation of the Hg sets.
Below is the the instruction that describes the task: ### Input: UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U) K = all closed sets This is UV_H function, but the returned implications are respected by all attribute sets of this context. This corr...
def objectid_search(gaiaid, gaia_mirror=None, columns=('source_id', 'ra','dec', 'phot_g_mean_mag', 'phot_bp_mean_mag', 'phot_rp_mean_mag', ...
This queries the GAIA TAP service for a single GAIA source ID. Parameters ---------- gaiaid : str The source ID of the object whose info will be collected. gaia_mirror : {'gaia','heidelberg','vizier'} or None This is the key used to select a GAIA catalog mirror from the `GAIA_...
Below is the the instruction that describes the task: ### Input: This queries the GAIA TAP service for a single GAIA source ID. Parameters ---------- gaiaid : str The source ID of the object whose info will be collected. gaia_mirror : {'gaia','heidelberg','vizier'} or None This is...
def _set_mct_state(self, v, load=False): """ Setter method for mct_state, mapped from YANG variable /mct_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_mct_state is considered as a private method. Backends looking to populate this variable should ...
Setter method for mct_state, mapped from YANG variable /mct_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_mct_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mct_state() directl...
Below is the the instruction that describes the task: ### Input: Setter method for mct_state, mapped from YANG variable /mct_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_mct_state is considered as a private method. Backends looking to populate this v...
def _sighash_anyone_can_pay(self, index, copy_tx, sighash_type): ''' int, byte-like, Tx, int -> bytes Applies SIGHASH_ANYONECANPAY procedure. Should be called by another SIGHASH procedure. Not on its own. https://en.bitcoin.it/wiki/OP_CHECKSIG#Procedure_for_Hashtype_SIGHA...
int, byte-like, Tx, int -> bytes Applies SIGHASH_ANYONECANPAY procedure. Should be called by another SIGHASH procedure. Not on its own. https://en.bitcoin.it/wiki/OP_CHECKSIG#Procedure_for_Hashtype_SIGHASH_ANYONECANPAY
Below is the the instruction that describes the task: ### Input: int, byte-like, Tx, int -> bytes Applies SIGHASH_ANYONECANPAY procedure. Should be called by another SIGHASH procedure. Not on its own. https://en.bitcoin.it/wiki/OP_CHECKSIG#Procedure_for_Hashtype_SIGHASH_ANYONECANPAY ...
def get_std_dev_area(self, mag, rake): """ Standard deviation for WC1994. Magnitude is ignored. """ assert rake is None or -180 <= rake <= 180 if rake is None: # their "All" case return 0.24 elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -13...
Standard deviation for WC1994. Magnitude is ignored.
Below is the the instruction that describes the task: ### Input: Standard deviation for WC1994. Magnitude is ignored. ### Response: def get_std_dev_area(self, mag, rake): """ Standard deviation for WC1994. Magnitude is ignored. """ assert rake is None or -180 <= rake <= 180 ...
def has_soma_points(data_wrapper): '''Checks if the TYPE column of raw data block has an element of type soma Returns: CheckResult with result ''' db = data_wrapper.data_block return CheckResult(POINT_TYPE.SOMA in db[:, COLS.TYPE], None)
Checks if the TYPE column of raw data block has an element of type soma Returns: CheckResult with result
Below is the the instruction that describes the task: ### Input: Checks if the TYPE column of raw data block has an element of type soma Returns: CheckResult with result ### Response: def has_soma_points(data_wrapper): '''Checks if the TYPE column of raw data block has an element of type soma ...
def auto_authorize(scope, password=[None]): """ Executes a command on the remote host that causes an authorization procedure to be started, then authorizes using the given password in the same way in which authorize() works. Depending on the detected operating system of the remote host the follo...
Executes a command on the remote host that causes an authorization procedure to be started, then authorizes using the given password in the same way in which authorize() works. Depending on the detected operating system of the remote host the following commands are started: - on IOS, the "enable"...
Below is the the instruction that describes the task: ### Input: Executes a command on the remote host that causes an authorization procedure to be started, then authorizes using the given password in the same way in which authorize() works. Depending on the detected operating system of the remote host ...
def decode(self, hashid): """Restore a tuple of numbers from the passed `hashid`. :param hashid The hashid to decode >>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456') >>> hashids.decode('1d6216i30h53elk3') (1, 23, 456) """ if not hashid or not _...
Restore a tuple of numbers from the passed `hashid`. :param hashid The hashid to decode >>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456') >>> hashids.decode('1d6216i30h53elk3') (1, 23, 456)
Below is the the instruction that describes the task: ### Input: Restore a tuple of numbers from the passed `hashid`. :param hashid The hashid to decode >>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456') >>> hashids.decode('1d6216i30h53elk3') (1, 23, 456) ### Respon...
def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'): """Return numpy.memmap of data stored in file.""" if not self.is_file: raise ValueError('Cannot memory-map file without fileno') return numpy.memmap(self._fh, dtype=dtype, mode=mode, offs...
Return numpy.memmap of data stored in file.
Below is the the instruction that describes the task: ### Input: Return numpy.memmap of data stored in file. ### Response: def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'): """Return numpy.memmap of data stored in file.""" if not self.is_file: raise ValueError('Cannot...
def _insert(wrap: str, tag: Optional[str]) -> str: """Insert the component tag into the wrapper html. This ignores other tags already created like ``{socket}``. https://stackoverflow.com/a/11284026/744520 """ if tag is None: raise ValueError('tag cannot be None') ...
Insert the component tag into the wrapper html. This ignores other tags already created like ``{socket}``. https://stackoverflow.com/a/11284026/744520
Below is the the instruction that describes the task: ### Input: Insert the component tag into the wrapper html. This ignores other tags already created like ``{socket}``. https://stackoverflow.com/a/11284026/744520 ### Response: def _insert(wrap: str, tag: Optional[str]) -> str: """Inser...
def capture_heroku_database(self): """ Capture Heroku database backup. """ self.print_message("Capturing database backup for app '%s'" % self.args.source_app) args = [ "heroku", "pg:backups:capture", "--app=%s" % self.args.source_app, ] if self...
Capture Heroku database backup.
Below is the the instruction that describes the task: ### Input: Capture Heroku database backup. ### Response: def capture_heroku_database(self): """ Capture Heroku database backup. """ self.print_message("Capturing database backup for app '%s'" % self.args.source_app) args = [ ...
def partial_trace(self, qubits: Qubits) -> 'Channel': """Return the partial trace over the specified qubits""" vec = self.vec.partial_trace(qubits) return Channel(vec.tensor, vec.qubits)
Return the partial trace over the specified qubits
Below is the the instruction that describes the task: ### Input: Return the partial trace over the specified qubits ### Response: def partial_trace(self, qubits: Qubits) -> 'Channel': """Return the partial trace over the specified qubits""" vec = self.vec.partial_trace(qubits) return Channe...
def _core_properties_part(self): """ |CorePropertiesPart| object related to this package. Creates a default core properties part if one is not present (not common). """ try: return self.part_related_by(RT.CORE_PROPERTIES) except KeyError: core_prop...
|CorePropertiesPart| object related to this package. Creates a default core properties part if one is not present (not common).
Below is the the instruction that describes the task: ### Input: |CorePropertiesPart| object related to this package. Creates a default core properties part if one is not present (not common). ### Response: def _core_properties_part(self): """ |CorePropertiesPart| object related to this pac...
def sspro_summary(self): """Parse the SSpro output file and return a summary of secondary structure composition. The output file is just a FASTA formatted file, so you can get residue level information by parsing it like a normal sequence file. Returns: dict: Percentage...
Parse the SSpro output file and return a summary of secondary structure composition. The output file is just a FASTA formatted file, so you can get residue level information by parsing it like a normal sequence file. Returns: dict: Percentage of: H: helix ...
Below is the the instruction that describes the task: ### Input: Parse the SSpro output file and return a summary of secondary structure composition. The output file is just a FASTA formatted file, so you can get residue level information by parsing it like a normal sequence file. Retu...
def events_for_onchain_secretreveal( target_state: TargetTransferState, channel_state: NettingChannelState, block_number: BlockNumber, block_hash: BlockHash, ) -> List[Event]: """ Emits the event for revealing the secret on-chain if the transfer can not be settled off-chain. ...
Emits the event for revealing the secret on-chain if the transfer can not be settled off-chain.
Below is the the instruction that describes the task: ### Input: Emits the event for revealing the secret on-chain if the transfer can not be settled off-chain. ### Response: def events_for_onchain_secretreveal( target_state: TargetTransferState, channel_state: NettingChannelState, bloc...
def parse_arg(f, kwd, offset=0): """ convert dictionary of keyword argument and value to positional argument equivalent to:: vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]]) """ vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]])
convert dictionary of keyword argument and value to positional argument equivalent to:: vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]])
Below is the the instruction that describes the task: ### Input: convert dictionary of keyword argument and value to positional argument equivalent to:: vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]]) ### Response: def parse_arg(f, kwd, offset=0): """ convert dicti...
def _parameters(cls, tokens): """ Extract all of the parameters from the tokens. :param tokens: The tokens to extract the parameters from :type tokens: list :rtype: dict """ arguments = [] options = [] for token in tokens: if not tok...
Extract all of the parameters from the tokens. :param tokens: The tokens to extract the parameters from :type tokens: list :rtype: dict
Below is the the instruction that describes the task: ### Input: Extract all of the parameters from the tokens. :param tokens: The tokens to extract the parameters from :type tokens: list :rtype: dict ### Response: def _parameters(cls, tokens): """ Extract all of the param...
def get_token_accuracy(targets, outputs, ignore_index=None): """ Get the accuracy token accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
Get the accuracy token accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ignore_index (int, optional): Specifies a target index that is ...
Below is the the instruction that describes the task: ### Input: Get the accuracy token accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
def add_lrn(self, name, input_name, output_name, alpha, beta, local_size, k = 1.0): """ Add a LRN (local response normalization) layer. Please see the LRNLayerParams message in Core ML neural network protobuf for more information about the operation of this layer. Supports "across" channels norm...
Add a LRN (local response normalization) layer. Please see the LRNLayerParams message in Core ML neural network protobuf for more information about the operation of this layer. Supports "across" channels normalization. Parameters ---------- name: str The name of this layer. ...
Below is the the instruction that describes the task: ### Input: Add a LRN (local response normalization) layer. Please see the LRNLayerParams message in Core ML neural network protobuf for more information about the operation of this layer. Supports "across" channels normalization. Parameters ...
def b64decode(s, altchars=None): """Decode a Base64 encoded string. s is the string to decode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the '+' and '/' characters. The decoded string is ret...
Decode a Base64 encoded string. s is the string to decode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the '+' and '/' characters. The decoded string is returned. A TypeError is raised if s is ...
Below is the the instruction that describes the task: ### Input: Decode a Base64 encoded string. s is the string to decode. Optional altchars must be a string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the '+' and '/' characters. ...
def run(self): """ Begin reading through audio files, saving false activations and retraining when necessary """ for fn in glob_all(self.args.random_data_folder, '*.wav'): if fn in self.trained_fns: print('Skipping ' + fn + '...') conti...
Begin reading through audio files, saving false activations and retraining when necessary
Below is the the instruction that describes the task: ### Input: Begin reading through audio files, saving false activations and retraining when necessary ### Response: def run(self): """ Begin reading through audio files, saving false activations and retraining when necessary ...
def _get_triplet_value_list(self, graph, identity, rdf_type): """ Get a list of values from RDF triples when more than one may be present """ values = [] for elem in graph.objects(identity, rdf_type): values.append(elem.toPython()) return values
Get a list of values from RDF triples when more than one may be present
Below is the the instruction that describes the task: ### Input: Get a list of values from RDF triples when more than one may be present ### Response: def _get_triplet_value_list(self, graph, identity, rdf_type): """ Get a list of values from RDF triples when more than one may be present ""...
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again ...
Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of chunks - and should be processed by one worker. ...
Below is the the instruction that describes the task: ### Input: Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again ...
def get_asset_id(cls, transactions): """Get the asset id from a list of :class:`~.Transactions`. This is useful when we want to check if the multiple inputs of a transaction are related to the same asset id. Args: transactions (:obj:`list` of :class:`~bigchaindb.common. ...
Get the asset id from a list of :class:`~.Transactions`. This is useful when we want to check if the multiple inputs of a transaction are related to the same asset id. Args: transactions (:obj:`list` of :class:`~bigchaindb.common. transaction.Transaction`): A list o...
Below is the the instruction that describes the task: ### Input: Get the asset id from a list of :class:`~.Transactions`. This is useful when we want to check if the multiple inputs of a transaction are related to the same asset id. Args: transactions (:obj:`list` of :class:`~b...
def update(x, **entries): """Update a dict, or an object with slots, according to `entries` dict. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) """ if isinstance(x, dict): x.update(entries) else: x.__dict__.upd...
Update a dict, or an object with slots, according to `entries` dict. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20)
Below is the the instruction that describes the task: ### Input: Update a dict, or an object with slots, according to `entries` dict. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) ### Response: def update(x, **entries): """Update a d...
def get_argument_endtime(self): """ Helper function to get endtime argument. Raises exception if argument is missing. Returns the endtime argument. """ try: endtime = self.get_argument(constants.PARAM_ENDTIME) return endtime except tornado.web.MissingArgumentError as e: rai...
Helper function to get endtime argument. Raises exception if argument is missing. Returns the endtime argument.
Below is the the instruction that describes the task: ### Input: Helper function to get endtime argument. Raises exception if argument is missing. Returns the endtime argument. ### Response: def get_argument_endtime(self): """ Helper function to get endtime argument. Raises exception if argumen...
def get_builder_image_id(self): """ Find out the docker ID of the buildroot image we are in. """ try: buildroot_tag = os.environ["OPENSHIFT_CUSTOM_BUILD_BASE_IMAGE"] except KeyError: return '' try: pod = self.osbs.get_pod_for_build(se...
Find out the docker ID of the buildroot image we are in.
Below is the the instruction that describes the task: ### Input: Find out the docker ID of the buildroot image we are in. ### Response: def get_builder_image_id(self): """ Find out the docker ID of the buildroot image we are in. """ try: buildroot_tag = os.environ["OPEN...
def rnegative_binomial(mu, alpha, size=None): """ Random negative binomial variates. """ # Using gamma-poisson mixture rather than numpy directly # because numpy apparently rounds mu = np.asarray(mu, dtype=float) pois_mu = np.random.gamma(alpha, mu / alpha, size) return np.random.poisson...
Random negative binomial variates.
Below is the the instruction that describes the task: ### Input: Random negative binomial variates. ### Response: def rnegative_binomial(mu, alpha, size=None): """ Random negative binomial variates. """ # Using gamma-poisson mixture rather than numpy directly # because numpy apparently rounds ...
def pack(self, value=None): """Pack and complete the last byte by padding.""" if isinstance(value, Match): return value.pack() elif value is None: self._update_match_length() packet = super().pack() return self._complete_last_byte(packet) r...
Pack and complete the last byte by padding.
Below is the the instruction that describes the task: ### Input: Pack and complete the last byte by padding. ### Response: def pack(self, value=None): """Pack and complete the last byte by padding.""" if isinstance(value, Match): return value.pack() elif value is None: ...
def _extract_device_uuid(cls, slug): """Turn a string slug into a UUID """ if len(slug) != 22: raise ArgumentError("Invalid device slug", slug=slug) hexdigits = slug[3:] hexdigits = hexdigits.replace('-', '') try: rawbytes = binascii.unhexlify(h...
Turn a string slug into a UUID
Below is the the instruction that describes the task: ### Input: Turn a string slug into a UUID ### Response: def _extract_device_uuid(cls, slug): """Turn a string slug into a UUID """ if len(slug) != 22: raise ArgumentError("Invalid device slug", slug=slug) hexdigits ...
def _create_graph(self, upgrades, history=None): """Create dependency graph from upgrades. :param upgrades: Dict of upgrades :param history: Dict of applied upgrades """ history = history or {} graph_incoming = {} # nodes their incoming edges graph_outgoing = {}...
Create dependency graph from upgrades. :param upgrades: Dict of upgrades :param history: Dict of applied upgrades
Below is the the instruction that describes the task: ### Input: Create dependency graph from upgrades. :param upgrades: Dict of upgrades :param history: Dict of applied upgrades ### Response: def _create_graph(self, upgrades, history=None): """Create dependency graph from upgrades. ...
def _encode_var(cls, var): """ Encodes a variable to the appropriate string format for ini files. :param var: The variable to encode :return: The ini representation of the variable :rtype: str """ if isinstance(var, str): if any(_ in var for _ in cls.require...
Encodes a variable to the appropriate string format for ini files. :param var: The variable to encode :return: The ini representation of the variable :rtype: str
Below is the the instruction that describes the task: ### Input: Encodes a variable to the appropriate string format for ini files. :param var: The variable to encode :return: The ini representation of the variable :rtype: str ### Response: def _encode_var(cls, var): """ Encodes a ...
def change_openid(self, from_appid, openid_list): '''微信公众号主体变更迁移用户 openid 详情请参考 http://kf.qq.com/faq/170221aUnmmU170221eUZJNf.html :param from_appid: 原公众号的 appid :param openid_list: 需要转换的openid,这些必须是旧账号目前关注的才行,否则会出错;一次最多100个 :return: 转换后的 openid 信息列表 ''' ...
微信公众号主体变更迁移用户 openid 详情请参考 http://kf.qq.com/faq/170221aUnmmU170221eUZJNf.html :param from_appid: 原公众号的 appid :param openid_list: 需要转换的openid,这些必须是旧账号目前关注的才行,否则会出错;一次最多100个 :return: 转换后的 openid 信息列表
Below is the the instruction that describes the task: ### Input: 微信公众号主体变更迁移用户 openid 详情请参考 http://kf.qq.com/faq/170221aUnmmU170221eUZJNf.html :param from_appid: 原公众号的 appid :param openid_list: 需要转换的openid,这些必须是旧账号目前关注的才行,否则会出错;一次最多100个 :return: 转换后的 openid 信息列表 ### Respons...
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ # if no actual arguments, print help if len(self.actual_arguments) < 1: return self.print_help(short=True) # check if we have a recognized tool switc...
Perform command and return the appropriate exit code. :rtype: int
Below is the the instruction that describes the task: ### Input: Perform command and return the appropriate exit code. :rtype: int ### Response: def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ # if no actual argu...
def bulk_send(self, topic, kmsgs): """ Send a batch of messages :param str topic: a kafka topic :param ksr.transport.Message kmsgs: Messages to serialize :return: Execution result :rtype: kser.result.Result """ try: self.client.do_request( ...
Send a batch of messages :param str topic: a kafka topic :param ksr.transport.Message kmsgs: Messages to serialize :return: Execution result :rtype: kser.result.Result
Below is the the instruction that describes the task: ### Input: Send a batch of messages :param str topic: a kafka topic :param ksr.transport.Message kmsgs: Messages to serialize :return: Execution result :rtype: kser.result.Result ### Response: def bulk_send(self, topic, kmsgs): ...
def get_branch_sha(profile, name): """Get the SHA a branch's HEAD points to. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ...
Get the SHA a branch's HEAD points to. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name The name of the branch...
Below is the the instruction that describes the task: ### Input: Get the SHA a branch's HEAD points to. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``toke...
def _load_ca_certs(cls, session: AppSession, clean: bool=True): '''Load the Certificate Authority certificates. ''' args = session.args if session.ca_certs_filename: return session.ca_certs_filename certs = set() if args.use_internal_ca_certs: p...
Load the Certificate Authority certificates.
Below is the the instruction that describes the task: ### Input: Load the Certificate Authority certificates. ### Response: def _load_ca_certs(cls, session: AppSession, clean: bool=True): '''Load the Certificate Authority certificates. ''' args = session.args if session.ca_certs_fi...
def _call_backend(self, method, default, *args, **kwargs): """Call the backend method with args. If there is currently no backend, return default.""" meth = getattr(self.backend, method, None) if meth is None: return default else: return meth(*args, **kwa...
Call the backend method with args. If there is currently no backend, return default.
Below is the the instruction that describes the task: ### Input: Call the backend method with args. If there is currently no backend, return default. ### Response: def _call_backend(self, method, default, *args, **kwargs): """Call the backend method with args. If there is currently no bac...
def output_package(dist): """Return string displaying package information.""" if dist_is_editable(dist): return '%s (%s, %s)' % ( dist.project_name, dist.version, dist.location, ) return '%s (%s)' % (dist.project_name, dist....
Return string displaying package information.
Below is the the instruction that describes the task: ### Input: Return string displaying package information. ### Response: def output_package(dist): """Return string displaying package information.""" if dist_is_editable(dist): return '%s (%s, %s)' % ( dist.project_nam...
def get_incomplete_penetrance_genes(hpo_lines): """Get a set with all genes that have incomplete penetrance according to HPO Args: hpo_lines(iterable(str)) Returns: incomplete_penetrance_genes(set): A set with the hgnc symbols of all genes...
Get a set with all genes that have incomplete penetrance according to HPO Args: hpo_lines(iterable(str)) Returns: incomplete_penetrance_genes(set): A set with the hgnc symbols of all genes with incomplete penetrance
Below is the the instruction that describes the task: ### Input: Get a set with all genes that have incomplete penetrance according to HPO Args: hpo_lines(iterable(str)) Returns: incomplete_penetrance_genes(set): A set with the hgnc symbols of all ...
def timedelta_to_str(value: datetime.timedelta, fmt: str = None) -> str: """Display the timedelta formatted according to the given string. You should use global setting ``TIMEDELTA_FORMAT`` to specify default format to this function there (like ``DATE_FORMAT`` for builtin ``date`` template filter). ...
Display the timedelta formatted according to the given string. You should use global setting ``TIMEDELTA_FORMAT`` to specify default format to this function there (like ``DATE_FORMAT`` for builtin ``date`` template filter). Default value for ``TIMEDELTA_FORMAT`` is ``'G:i'``. Format uses the same...
Below is the the instruction that describes the task: ### Input: Display the timedelta formatted according to the given string. You should use global setting ``TIMEDELTA_FORMAT`` to specify default format to this function there (like ``DATE_FORMAT`` for builtin ``date`` template filter). Default v...
def targets_from_background(back_cnn, work_dir, data): """Retrieve target and antitarget BEDs from background CNN file. """ target_file = os.path.join(work_dir, "%s.target.bed" % dd.get_sample_name(data)) anti_file = os.path.join(work_dir, "%s.antitarget.bed" % dd.get_sample_name(data)) if not utils...
Retrieve target and antitarget BEDs from background CNN file.
Below is the the instruction that describes the task: ### Input: Retrieve target and antitarget BEDs from background CNN file. ### Response: def targets_from_background(back_cnn, work_dir, data): """Retrieve target and antitarget BEDs from background CNN file. """ target_file = os.path.join(work_dir, "...
def drive_rotational_speed_rpm(self): """Gets set of rotational speed of the disks""" drv_rot_speed_rpm = set() for member in self.get_members(): drv_rot_speed_rpm.update(member.drive_rotational_speed_rpm) return drv_rot_speed_rpm
Gets set of rotational speed of the disks
Below is the the instruction that describes the task: ### Input: Gets set of rotational speed of the disks ### Response: def drive_rotational_speed_rpm(self): """Gets set of rotational speed of the disks""" drv_rot_speed_rpm = set() for member in self.get_members(): drv_rot_spee...
def write(self, section, option, value): """Write to file. Parameters ---------- section : string Section. option : string Option. value : string Value. """ self.config.read(self.filepath) string = tidy_headers....
Write to file. Parameters ---------- section : string Section. option : string Option. value : string Value.
Below is the the instruction that describes the task: ### Input: Write to file. Parameters ---------- section : string Section. option : string Option. value : string Value. ### Response: def write(self, section, option, value): "...
def force_utf8_in_ascii_mode_hack(): '''In systems without a UTF8 locale configured, Python will default to ASCII mode for stdout and stderr. This causes our fancy display to fail with encoding errors. In particular, you run into this if you try to run peru inside of Docker. This is a hack to force emit...
In systems without a UTF8 locale configured, Python will default to ASCII mode for stdout and stderr. This causes our fancy display to fail with encoding errors. In particular, you run into this if you try to run peru inside of Docker. This is a hack to force emitting UTF8 in that case. Hopefully it doe...
Below is the the instruction that describes the task: ### Input: In systems without a UTF8 locale configured, Python will default to ASCII mode for stdout and stderr. This causes our fancy display to fail with encoding errors. In particular, you run into this if you try to run peru inside of Docker. Thi...
def _remote_profile_dir_default(self): """turns /home/you/.ipython/profile_foo into .ipython/profile_foo """ home = get_home_dir() if not home.endswith('/'): home = home+'/' if self.profile_dir.startswith(home): return self.profile_dir[len(home):]...
turns /home/you/.ipython/profile_foo into .ipython/profile_foo
Below is the the instruction that describes the task: ### Input: turns /home/you/.ipython/profile_foo into .ipython/profile_foo ### Response: def _remote_profile_dir_default(self): """turns /home/you/.ipython/profile_foo into .ipython/profile_foo """ home = get_home_dir() if not hom...
def style_checkboxes(widget): """ Iterates over widget children to change checkboxes stylesheet. The default rendering of checkboxes does not allow to tell a focused one from an unfocused one. """ ww = widget.findChildren(QCheckBox) for w in ww: w.setStyleSheet("QCheckBox...
Iterates over widget children to change checkboxes stylesheet. The default rendering of checkboxes does not allow to tell a focused one from an unfocused one.
Below is the the instruction that describes the task: ### Input: Iterates over widget children to change checkboxes stylesheet. The default rendering of checkboxes does not allow to tell a focused one from an unfocused one. ### Response: def style_checkboxes(widget): """ Iterates over widget ...
def plot_cells(cell_1, cell_2, cell_3): """Plots three cells""" fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5)) for ax in [ax1, ax2, ax3]: ax.grid(False) ax.set_xticks([]) ax.set_yticks([]) ax1.set_title("Type 1") ax1.imshow(cell_1) ax2.set_title("Type 2") ...
Plots three cells
Below is the the instruction that describes the task: ### Input: Plots three cells ### Response: def plot_cells(cell_1, cell_2, cell_3): """Plots three cells""" fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5)) for ax in [ax1, ax2, ax3]: ax.grid(False) ax.set_xticks([]) ...
def _write_mef(self, key, extlist, outfile): """Write out regular multi-extension FITS data.""" channel = self.fv.get_channel(self.chname) with fits.open(outfile, mode='update') as pf: # Process each modified data extension for idx in extlist: k = '{0}[{1}...
Write out regular multi-extension FITS data.
Below is the the instruction that describes the task: ### Input: Write out regular multi-extension FITS data. ### Response: def _write_mef(self, key, extlist, outfile): """Write out regular multi-extension FITS data.""" channel = self.fv.get_channel(self.chname) with fits.open(outfile, mode...
def execute(self, method, args, kwargs): """ Execute the given method and stores its result. The result is considered "done" even if the method raises an exception :param method: The method to execute :param args: Method positional arguments :param kwargs: Method keyword...
Execute the given method and stores its result. The result is considered "done" even if the method raises an exception :param method: The method to execute :param args: Method positional arguments :param kwargs: Method keyword arguments :raise Exception: The exception raised by ...
Below is the the instruction that describes the task: ### Input: Execute the given method and stores its result. The result is considered "done" even if the method raises an exception :param method: The method to execute :param args: Method positional arguments :param kwargs: Method...
def xrange(self, name, min='-', max='+', count=None): """ Read stream values within an interval. name: name of the stream. start: first stream ID. defaults to '-', meaning the earliest available. finish: last stream ID. defaults to '+', meaning the ...
Read stream values within an interval. name: name of the stream. start: first stream ID. defaults to '-', meaning the earliest available. finish: last stream ID. defaults to '+', meaning the latest available. count: if set, only return this many items, begi...
Below is the the instruction that describes the task: ### Input: Read stream values within an interval. name: name of the stream. start: first stream ID. defaults to '-', meaning the earliest available. finish: last stream ID. defaults to '+', meaning the lates...
def get_thumbnail(self, mxcurl, width, height, method='scale', allow_remote=True): """Download raw media thumbnail from provided mxc URL. Args: mxcurl (str): mxc media URL width (int): desired thumbnail width height (int): desired thumbnail height method ...
Download raw media thumbnail from provided mxc URL. Args: mxcurl (str): mxc media URL width (int): desired thumbnail width height (int): desired thumbnail height method (str): thumb creation method. Must be in ['scale', 'crop']. Default 'scale'. ...
Below is the the instruction that describes the task: ### Input: Download raw media thumbnail from provided mxc URL. Args: mxcurl (str): mxc media URL width (int): desired thumbnail width height (int): desired thumbnail height method (str): thumb creation met...
def create_wallet(self, master_secret=b""): """Create a BIP0032-style hierarchical wallet. @param: master_secret Create from master secret, otherwise random. """ master_secret = deserialize.bytes_str(master_secret) bip32node = control.create_wallet(self.testnet, ...
Create a BIP0032-style hierarchical wallet. @param: master_secret Create from master secret, otherwise random.
Below is the the instruction that describes the task: ### Input: Create a BIP0032-style hierarchical wallet. @param: master_secret Create from master secret, otherwise random. ### Response: def create_wallet(self, master_secret=b""): """Create a BIP0032-style hierarchical wallet. @param: ...
def shape_from_str_tuple(sshape, variables, ignore=None): """ Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary Parameters ---------- sshape : tuple/string composed of integers and strings. The strings should related to integral prop...
Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary Parameters ---------- sshape : tuple/string composed of integers and strings. The strings should related to integral properties registered with this Solver object variables : dict...
Below is the the instruction that describes the task: ### Input: Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary Parameters ---------- sshape : tuple/string composed of integers and strings. The strings should related to integral prope...
def convert_to_file(cgi_input, output_file, twobit_ref, twobit_name, var_only=False): """Convert a CGI var file and output VCF-formatted data to file""" if isinstance(output_file, str): output_file = auto_zip_open(output_file, 'w') conversion = convert(cgi_input=cgi_input, twobit_ref=twobit_ref, t...
Convert a CGI var file and output VCF-formatted data to file
Below is the the instruction that describes the task: ### Input: Convert a CGI var file and output VCF-formatted data to file ### Response: def convert_to_file(cgi_input, output_file, twobit_ref, twobit_name, var_only=False): """Convert a CGI var file and output VCF-formatted data to file""" if isinstance...
def genemania_force_directed(self,curveSteepness=None,defaultEdgeWeight=None,\ defaultSpringCoefficient=None,defaultSpringLength=None,EdgeAttribute=None,\ ignoreHiddenElements=None,isDeterministic=None,maxNodeMass=None,\ maxWeightCutoff=None,midpointEdges=None,minNodeMass=None,minWeightCutoff=None,\ network=Non...
Execute the GeneMANIA Force Directed Layout on a network. :param curveSteepness (string, optional): :param defaultEdgeWeight (string, optional): The default edge weight to con sider, default is 0.5 :param defaultSpringCoefficient (string, optional): :param defaultSpringLength (string, optional): :param Ed...
Below is the the instruction that describes the task: ### Input: Execute the GeneMANIA Force Directed Layout on a network. :param curveSteepness (string, optional): :param defaultEdgeWeight (string, optional): The default edge weight to con sider, default is 0.5 :param defaultSpringCoefficient (string, op...
def super_parent(self, mol, skip_standardize=False): """Return the super parent of a given molecule. THe super parent is fragment, charge, isotope, stereochemistry and tautomer insensitive. From the input molecule, the largest fragment is taken. This is uncharged and then isotope and stereochem...
Return the super parent of a given molecule. THe super parent is fragment, charge, isotope, stereochemistry and tautomer insensitive. From the input molecule, the largest fragment is taken. This is uncharged and then isotope and stereochemistry information is discarded. Finally, the canonical t...
Below is the the instruction that describes the task: ### Input: Return the super parent of a given molecule. THe super parent is fragment, charge, isotope, stereochemistry and tautomer insensitive. From the input molecule, the largest fragment is taken. This is uncharged and then isotope and stere...
def prepare(self): ''' Run the preparation sequence required to start a salt proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(ProxyMinion, self).prepare() if not self.values.proxyid: self....
Run the preparation sequence required to start a salt proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare()
Below is the the instruction that describes the task: ### Input: Run the preparation sequence required to start a salt proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ### Response: def prepare(self): ''' Run the preparation seque...