repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
kyuupichan/aiorpcX
aiorpcx/jsonrpc.py
https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/jsonrpc.py#L284-L287
def request_message(cls, item, request_id): '''Convert an RPCRequest item to a message.''' assert isinstance(item, Request) return cls.encode_payload(cls.request_payload(item, request_id))
[ "def", "request_message", "(", "cls", ",", "item", ",", "request_id", ")", ":", "assert", "isinstance", "(", "item", ",", "Request", ")", "return", "cls", ".", "encode_payload", "(", "cls", ".", "request_payload", "(", "item", ",", "request_id", ")", ")" ]
Convert an RPCRequest item to a message.
[ "Convert", "an", "RPCRequest", "item", "to", "a", "message", "." ]
python
train
materialsproject/pymatgen
pymatgen/analysis/gb/grain.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/gb/grain.py#L110-L122
def copy(self): """ Convenience method to get a copy of the structure, with options to add site properties. Returns: A copy of the Structure, with optionally new site_properties and optionally sanitized. """ return GrainBoundary(self.lattice, self...
[ "def", "copy", "(", "self", ")", ":", "return", "GrainBoundary", "(", "self", ".", "lattice", ",", "self", ".", "species_and_occu", ",", "self", ".", "frac_coords", ",", "self", ".", "rotation_axis", ",", "self", ".", "rotation_angle", ",", "self", ".", ...
Convenience method to get a copy of the structure, with options to add site properties. Returns: A copy of the Structure, with optionally new site_properties and optionally sanitized.
[ "Convenience", "method", "to", "get", "a", "copy", "of", "the", "structure", "with", "options", "to", "add", "site", "properties", "." ]
python
train
monarch-initiative/dipper
dipper/models/Genotype.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/models/Genotype.py#L56-L77
def addAllele( self, allele_id, allele_label, allele_type=None, allele_description=None): """ Make an allele object. If no allele_type is added, it will default to a geno:allele :param allele_id: curie for allele (required) :param allele_label: label for a...
[ "def", "addAllele", "(", "self", ",", "allele_id", ",", "allele_label", ",", "allele_type", "=", "None", ",", "allele_description", "=", "None", ")", ":", "# TODO should we accept a list of allele types?", "if", "allele_type", "is", "None", ":", "allele_type", "=", ...
Make an allele object. If no allele_type is added, it will default to a geno:allele :param allele_id: curie for allele (required) :param allele_label: label for allele (required) :param allele_type: id for an allele type (optional, recommended SO or GENO class) :param all...
[ "Make", "an", "allele", "object", ".", "If", "no", "allele_type", "is", "added", "it", "will", "default", "to", "a", "geno", ":", "allele", ":", "param", "allele_id", ":", "curie", "for", "allele", "(", "required", ")", ":", "param", "allele_label", ":",...
python
train
isislovecruft/python-gnupg
pretty_bad_protocol/_meta.py
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_meta.py#L352-L360
def default_preference_list(self, prefs): """Set the default preference list. :param str prefs: A string containing the default preferences for ciphers, digests, and compression algorithms. """ prefs = _check_preferences(prefs) if prefs is not None: ...
[ "def", "default_preference_list", "(", "self", ",", "prefs", ")", ":", "prefs", "=", "_check_preferences", "(", "prefs", ")", "if", "prefs", "is", "not", "None", ":", "self", ".", "_prefs", "=", "prefs" ]
Set the default preference list. :param str prefs: A string containing the default preferences for ciphers, digests, and compression algorithms.
[ "Set", "the", "default", "preference", "list", "." ]
python
train
fermiPy/fermipy
fermipy/srcmap_utils.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/srcmap_utils.py#L380-L403
def delete_source_map(srcmap_file, names, logger=None): """Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted. """ with fits.open(sr...
[ "def", "delete_source_map", "(", "srcmap_file", ",", "names", ",", "logger", "=", "None", ")", ":", "with", "fits", ".", "open", "(", "srcmap_file", ")", "as", "hdulist", ":", "hdunames", "=", "[", "hdu", ".", "name", ".", "upper", "(", ")", "for", "...
Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted.
[ "Delete", "a", "map", "from", "a", "binned", "analysis", "source", "map", "file", "if", "it", "exists", "." ]
python
train
QuantEcon/QuantEcon.py
quantecon/game_theory/repeated_game.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/game_theory/repeated_game.py#L306-L366
def _find_C(C, points, vertices, equations, extended_payoff, IC, tol): """ Find all the intersection points between the current convex hull and the two IC constraints. It is done by iterating simplex counterclockwise. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array...
[ "def", "_find_C", "(", "C", ",", "points", ",", "vertices", ",", "equations", ",", "extended_payoff", ",", "IC", ",", "tol", ")", ":", "n", "=", "0", "weights", "=", "np", ".", "empty", "(", "2", ")", "# vertices is ordered counterclockwise", "for", "i",...
Find all the intersection points between the current convex hull and the two IC constraints. It is done by iterating simplex counterclockwise. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated potential extreme points of one action profile. ...
[ "Find", "all", "the", "intersection", "points", "between", "the", "current", "convex", "hull", "and", "the", "two", "IC", "constraints", ".", "It", "is", "done", "by", "iterating", "simplex", "counterclockwise", "." ]
python
train
Clinical-Genomics/housekeeper
housekeeper/store/models.py
https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/models.py#L52-L54
def relative_root_dir(self): """Build the relative root dir path for the bundle version.""" return Path(self.bundle.name) / str(self.created_at.date())
[ "def", "relative_root_dir", "(", "self", ")", ":", "return", "Path", "(", "self", ".", "bundle", ".", "name", ")", "/", "str", "(", "self", ".", "created_at", ".", "date", "(", ")", ")" ]
Build the relative root dir path for the bundle version.
[ "Build", "the", "relative", "root", "dir", "path", "for", "the", "bundle", "version", "." ]
python
train
viniciuschiele/flask-apscheduler
flask_apscheduler/auth.py
https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/auth.py#L82-L102
def get_authorization(self): """ Get the username and password for Basic authentication header. :return Authentication: The authentication data or None if it is not present or invalid. """ auth = get_authorization_header() if not auth: return None au...
[ "def", "get_authorization", "(", "self", ")", ":", "auth", "=", "get_authorization_header", "(", ")", "if", "not", "auth", ":", "return", "None", "auth_type", ",", "auth_info", "=", "auth", "if", "auth_type", "!=", "b'basic'", ":", "return", "None", "try", ...
Get the username and password for Basic authentication header. :return Authentication: The authentication data or None if it is not present or invalid.
[ "Get", "the", "username", "and", "password", "for", "Basic", "authentication", "header", ".", ":", "return", "Authentication", ":", "The", "authentication", "data", "or", "None", "if", "it", "is", "not", "present", "or", "invalid", "." ]
python
train
annoviko/pyclustering
pyclustering/nnet/sync.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/sync.py#L258-L299
def allocate_phase_matrix(self, grid_width = None, grid_height = None, iteration = None): """! @brief Returns 2D matrix of phase values of oscillators at the specified iteration of simulation. @details User should ensure correct matrix sizes in line with following expression grid_width x grid...
[ "def", "allocate_phase_matrix", "(", "self", ",", "grid_width", "=", "None", ",", "grid_height", "=", "None", ",", "iteration", "=", "None", ")", ":", "output_dynamic", "=", "self", ".", "output", "if", "(", "(", "output_dynamic", "is", "None", ")", "or", ...
! @brief Returns 2D matrix of phase values of oscillators at the specified iteration of simulation. @details User should ensure correct matrix sizes in line with following expression grid_width x grid_height that should be equal to amount of oscillators otherwise exception is throw...
[ "!" ]
python
valid
mozilla-iot/webthing-python
webthing/property.py
https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/property.py#L91-L98
def set_value(self, value): """ Set the current value of the property. value -- the value to set """ self.validate_value(value) self.value.set(value)
[ "def", "set_value", "(", "self", ",", "value", ")", ":", "self", ".", "validate_value", "(", "value", ")", "self", ".", "value", ".", "set", "(", "value", ")" ]
Set the current value of the property. value -- the value to set
[ "Set", "the", "current", "value", "of", "the", "property", "." ]
python
test
awslabs/aws-cfn-template-flip
cfn_flip/__init__.py
https://github.com/awslabs/aws-cfn-template-flip/blob/837576bea243e3f5efb0a20b84802371272e2d33/cfn_flip/__init__.py#L63-L73
def to_yaml(template, clean_up=False, long_form=False): """ Assume the input is JSON and convert to YAML """ data = load_json(template) if clean_up: data = clean(data) return dump_yaml(data, clean_up, long_form)
[ "def", "to_yaml", "(", "template", ",", "clean_up", "=", "False", ",", "long_form", "=", "False", ")", ":", "data", "=", "load_json", "(", "template", ")", "if", "clean_up", ":", "data", "=", "clean", "(", "data", ")", "return", "dump_yaml", "(", "data...
Assume the input is JSON and convert to YAML
[ "Assume", "the", "input", "is", "JSON", "and", "convert", "to", "YAML" ]
python
train
chaosmail/python-fs
fs/fs.py
https://github.com/chaosmail/python-fs/blob/2567922ced9387e327e65f3244caff3b7af35684/fs/fs.py#L175-L180
def listdirs(path='.'): """generator that returns all directories of *path*""" import os for f in os.listdir(path): if isdir(join(path, f)): yield join(path, f) if path != '.' else f
[ "def", "listdirs", "(", "path", "=", "'.'", ")", ":", "import", "os", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "isdir", "(", "join", "(", "path", ",", "f", ")", ")", ":", "yield", "join", "(", "path", ",", "f", ")"...
generator that returns all directories of *path*
[ "generator", "that", "returns", "all", "directories", "of", "*", "path", "*" ]
python
train
cuihantao/andes
andes/filters/card.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/card.py#L26-L110
def read(file, system): """Parse an ANDES card file into internal variables""" try: fid = open(file, 'r') raw_file = fid.readlines() except IOError: print('* IOError while reading input card file.') return ret_dict = dict() ret_dict['outfile'] = file.split('.')[0].lo...
[ "def", "read", "(", "file", ",", "system", ")", ":", "try", ":", "fid", "=", "open", "(", "file", ",", "'r'", ")", "raw_file", "=", "fid", ".", "readlines", "(", ")", "except", "IOError", ":", "print", "(", "'* IOError while reading input card file.'", "...
Parse an ANDES card file into internal variables
[ "Parse", "an", "ANDES", "card", "file", "into", "internal", "variables" ]
python
train
transifex/transifex-python-library
txlib/api/resources.py
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/resources.py#L27-L32
def retrieve_content(self): """Retrieve the content of a resource.""" path = self._construct_path_to_source_content() res = self._http.get(path) self._populated_fields['content'] = res['content'] return res['content']
[ "def", "retrieve_content", "(", "self", ")", ":", "path", "=", "self", ".", "_construct_path_to_source_content", "(", ")", "res", "=", "self", ".", "_http", ".", "get", "(", "path", ")", "self", ".", "_populated_fields", "[", "'content'", "]", "=", "res", ...
Retrieve the content of a resource.
[ "Retrieve", "the", "content", "of", "a", "resource", "." ]
python
train
woolfson-group/isambard
isambard/add_ons/filesystem.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/add_ons/filesystem.py#L131-L179
def fastas(self, download=False): """ Dict of filepaths for all fasta files associated with code. Parameters ---------- download : bool If True, downloads the fasta file from the PDB. If False, uses the ampal Protein.fasta property Defaults to False -...
[ "def", "fastas", "(", "self", ",", "download", "=", "False", ")", ":", "fastas_dict", "=", "{", "}", "fasta_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "parent_dir", ",", "'fasta'", ")", "if", "not", "os", ".", "path", ".", "exists...
Dict of filepaths for all fasta files associated with code. Parameters ---------- download : bool If True, downloads the fasta file from the PDB. If False, uses the ampal Protein.fasta property Defaults to False - this is definitely the recommended behaviour....
[ "Dict", "of", "filepaths", "for", "all", "fasta", "files", "associated", "with", "code", "." ]
python
train
markovmodel/msmtools
msmtools/analysis/dense/pcca.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/pcca.py#L194-L219
def _fill_matrix(rot_crop_matrix, eigvectors): """ Helper function for opt_soft """ (x, y) = rot_crop_matrix.shape row_sums = np.sum(rot_crop_matrix, axis=1) row_sums = np.reshape(row_sums, (x, 1)) # add -row_sums as leftmost column to rot_crop_matrix rot_crop_matrix = np.concatenate...
[ "def", "_fill_matrix", "(", "rot_crop_matrix", ",", "eigvectors", ")", ":", "(", "x", ",", "y", ")", "=", "rot_crop_matrix", ".", "shape", "row_sums", "=", "np", ".", "sum", "(", "rot_crop_matrix", ",", "axis", "=", "1", ")", "row_sums", "=", "np", "."...
Helper function for opt_soft
[ "Helper", "function", "for", "opt_soft" ]
python
train
biocore/deblur
deblur/workflow.py
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L532-L570
def remove_chimeras_denovo_from_seqs(seqs_fp, working_dir, threads=1): """Remove chimeras de novo using UCHIME (VSEARCH implementation). Parameters ---------- seqs_fp: string file path to FASTA input sequence file output_fp: string file path to store chimera-free results threads...
[ "def", "remove_chimeras_denovo_from_seqs", "(", "seqs_fp", ",", "working_dir", ",", "threads", "=", "1", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'remove_chimeras_denovo_from_seqs seqs file %s'", "'to w...
Remove chimeras de novo using UCHIME (VSEARCH implementation). Parameters ---------- seqs_fp: string file path to FASTA input sequence file output_fp: string file path to store chimera-free results threads : int number of threads (0 for all cores) Returns ------- ...
[ "Remove", "chimeras", "de", "novo", "using", "UCHIME", "(", "VSEARCH", "implementation", ")", "." ]
python
train
genesluder/python-agiletixapi
agiletixapi/utils.py
https://github.com/genesluder/python-agiletixapi/blob/a7a3907414cd5623f4542b03cb970862368a894a/agiletixapi/utils.py#L79-L83
def to_pascal_case(s): """Transform underscore separated string to pascal case """ return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())
[ "def", "to_pascal_case", "(", "s", ")", ":", "return", "re", ".", "sub", "(", "r'(?!^)_([a-zA-Z])'", ",", "lambda", "m", ":", "m", ".", "group", "(", "1", ")", ".", "upper", "(", ")", ",", "s", ".", "capitalize", "(", ")", ")" ]
Transform underscore separated string to pascal case
[ "Transform", "underscore", "separated", "string", "to", "pascal", "case" ]
python
train
mandiant/ioc_writer
ioc_writer/ioc_api.py
https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_api.py#L694-L704
def get_i_text(node): """ Get the text for an Indicator node. :param node: Indicator node. :return: """ if node.tag != 'Indicator': raise IOCParseError('Invalid tag: {}'.format(node.tag)) s = node.get('operator').upper() return s
[ "def", "get_i_text", "(", "node", ")", ":", "if", "node", ".", "tag", "!=", "'Indicator'", ":", "raise", "IOCParseError", "(", "'Invalid tag: {}'", ".", "format", "(", "node", ".", "tag", ")", ")", "s", "=", "node", ".", "get", "(", "'operator'", ")", ...
Get the text for an Indicator node. :param node: Indicator node. :return:
[ "Get", "the", "text", "for", "an", "Indicator", "node", "." ]
python
train
Alignak-monitoring/alignak
alignak/objects/service.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1346-L1356
def apply_inheritance(self): """ For all items and templates inherit properties and custom variables. :return: None """ super(Services, self).apply_inheritance() # add_item only ensure we can build a key for services later (after explode) for item in list(se...
[ "def", "apply_inheritance", "(", "self", ")", ":", "super", "(", "Services", ",", "self", ")", ".", "apply_inheritance", "(", ")", "# add_item only ensure we can build a key for services later (after explode)", "for", "item", "in", "list", "(", "self", ".", "items", ...
For all items and templates inherit properties and custom variables. :return: None
[ "For", "all", "items", "and", "templates", "inherit", "properties", "and", "custom", "variables", "." ]
python
train
saltstack/salt
salt/states/cron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L451-L669
def file(name, source_hash='', source_hash_name=None, user='root', template=None, context=None, replace=True, defaults=None, backup='', **kwargs): ''' Provides file.managed-like functionality (templating, etc.) for a pre-made c...
[ "def", "file", "(", "name", ",", "source_hash", "=", "''", ",", "source_hash_name", "=", "None", ",", "user", "=", "'root'", ",", "template", "=", "None", ",", "context", "=", "None", ",", "replace", "=", "True", ",", "defaults", "=", "None", ",", "b...
Provides file.managed-like functionality (templating, etc.) for a pre-made crontab file, to be assigned to a given user. name The source file to be used as the crontab. This source file can be hosted on either the salt master server, or on an HTTP or FTP server. For files hosted on the ...
[ "Provides", "file", ".", "managed", "-", "like", "functionality", "(", "templating", "etc", ".", ")", "for", "a", "pre", "-", "made", "crontab", "file", "to", "be", "assigned", "to", "a", "given", "user", "." ]
python
train
mulkieran/justbases
src/justbases/_rationals.py
https://github.com/mulkieran/justbases/blob/dd52ff4b3d11609f54b2673599ee4eeb20f9734f/src/justbases/_rationals.py#L562-L589
def _increment(sign, integer_part, non_repeating_part, base): """ Return an increment radix. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the integer part :type integer_part: list of int :param non_repeating_part: the fractional part :type non...
[ "def", "_increment", "(", "sign", ",", "integer_part", ",", "non_repeating_part", ",", "base", ")", ":", "(", "carry", ",", "non_repeating_part", ")", "=", "Nats", ".", "carry_in", "(", "non_repeating_part", ",", "1", ",", "base", ")", "(", "carry", ",", ...
Return an increment radix. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the integer part :type integer_part: list of int :param non_repeating_part: the fractional part :type non_repeating_part: list of int :param int base: the base :returns: ...
[ "Return", "an", "increment", "radix", "." ]
python
train
Kortemme-Lab/klab
klab/bio/uniprot.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/uniprot.py#L892-L915
def get_common_PDB_IDs(pdb_id, cache_dir = None, exception_on_failure = True): '''This function takes a PDB ID, maps it to UniProt ACCs, then returns the common set of PDB IDs related to those ACCs. The purpose is to find any PDB files related to pdb_id, particularly for complexes, such that the other PDB fi...
[ "def", "get_common_PDB_IDs", "(", "pdb_id", ",", "cache_dir", "=", "None", ",", "exception_on_failure", "=", "True", ")", ":", "m", "=", "pdb_to_uniparc", "(", "[", "pdb_id", "]", ",", "cache_dir", "=", "cache_dir", ")", "UniProtACs", "=", "[", "]", "if", ...
This function takes a PDB ID, maps it to UniProt ACCs, then returns the common set of PDB IDs related to those ACCs. The purpose is to find any PDB files related to pdb_id, particularly for complexes, such that the other PDB files contain identical sequences or mutant complexes.
[ "This", "function", "takes", "a", "PDB", "ID", "maps", "it", "to", "UniProt", "ACCs", "then", "returns", "the", "common", "set", "of", "PDB", "IDs", "related", "to", "those", "ACCs", ".", "The", "purpose", "is", "to", "find", "any", "PDB", "files", "re...
python
train
opencobra/memote
memote/support/consistency_helpers.py
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/consistency_helpers.py#L216-L233
def get_internals(model): """ Return non-boundary reactions and their metabolites. Boundary reactions are unbalanced by their nature. They are excluded here and only the metabolites of the others are considered. Parameters ---------- model : cobra.Model The metabolic model under in...
[ "def", "get_internals", "(", "model", ")", ":", "biomass", "=", "set", "(", "find_biomass_reaction", "(", "model", ")", ")", "if", "len", "(", "biomass", ")", "==", "0", ":", "LOGGER", ".", "warning", "(", "\"No biomass reaction detected. Consistency test result...
Return non-boundary reactions and their metabolites. Boundary reactions are unbalanced by their nature. They are excluded here and only the metabolites of the others are considered. Parameters ---------- model : cobra.Model The metabolic model under investigation.
[ "Return", "non", "-", "boundary", "reactions", "and", "their", "metabolites", "." ]
python
train
borntyping/python-riemann-client
riemann_client/command.py
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L131-L134
def query(transport, query): """Query the Riemann server""" with CommandLineClient(transport) as client: echo_event(client.query(query))
[ "def", "query", "(", "transport", ",", "query", ")", ":", "with", "CommandLineClient", "(", "transport", ")", "as", "client", ":", "echo_event", "(", "client", ".", "query", "(", "query", ")", ")" ]
Query the Riemann server
[ "Query", "the", "Riemann", "server" ]
python
train
apache/spark
python/pyspark/sql/functions.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L1761-L1770
def regexp_replace(str, pattern, replacement): r"""Replace all substrings of the specified string value that match regexp with rep. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect() [Row(d=u'-----')] """ sc = SparkC...
[ "def", "regexp_replace", "(", "str", ",", "pattern", ",", "replacement", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "jc", "=", "sc", ".", "_jvm", ".", "functions", ".", "regexp_replace", "(", "_to_java_column", "(", "str", ")", ",", ...
r"""Replace all substrings of the specified string value that match regexp with rep. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect() [Row(d=u'-----')]
[ "r", "Replace", "all", "substrings", "of", "the", "specified", "string", "value", "that", "match", "regexp", "with", "rep", "." ]
python
train
pyviz/holoviews
holoviews/plotting/mpl/element.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/mpl/element.py#L527-L537
def update_handles(self, key, axis, element, ranges, style): """ Update the elements of the plot. """ self.teardown_handles() plot_data, plot_kwargs, axis_kwargs = self.get_data(element, ranges, style) with abbreviated_exception(): handles = self.init_artists...
[ "def", "update_handles", "(", "self", ",", "key", ",", "axis", ",", "element", ",", "ranges", ",", "style", ")", ":", "self", ".", "teardown_handles", "(", ")", "plot_data", ",", "plot_kwargs", ",", "axis_kwargs", "=", "self", ".", "get_data", "(", "elem...
Update the elements of the plot.
[ "Update", "the", "elements", "of", "the", "plot", "." ]
python
train
fhs/pyhdf
pyhdf/SD.py
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/SD.py#L2959-L3018
def getscale(self): """Obtain the scale values along a dimension. Args:: no argument Returns:: list with the scale values; the list length is equal to the dimension length; the element type is equal to the dimension data type, as set when the 'setdimsc...
[ "def", "getscale", "(", "self", ")", ":", "# Get dimension info. If data_type is 0, no scale have been set", "# on the dimension.", "status", ",", "dim_name", ",", "dim_size", ",", "data_type", ",", "n_attrs", "=", "_C", ".", "SDdiminfo", "(", "self", ".", "_id", ")...
Obtain the scale values along a dimension. Args:: no argument Returns:: list with the scale values; the list length is equal to the dimension length; the element type is equal to the dimension data type, as set when the 'setdimscale()' method was called. ...
[ "Obtain", "the", "scale", "values", "along", "a", "dimension", "." ]
python
train
PmagPy/PmagPy
programs/pmag_gui.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/pmag_gui.py#L765-L782
def on_menu_exit(self, event): """ Exit the GUI """ # also delete appropriate copy file try: self.help_window.Destroy() except: pass if '-i' in sys.argv: self.Destroy() try: sys.exit() # can raise TypeError i...
[ "def", "on_menu_exit", "(", "self", ",", "event", ")", ":", "# also delete appropriate copy file", "try", ":", "self", ".", "help_window", ".", "Destroy", "(", ")", "except", ":", "pass", "if", "'-i'", "in", "sys", ".", "argv", ":", "self", ".", "Destroy",...
Exit the GUI
[ "Exit", "the", "GUI" ]
python
train
apache/spark
python/pyspark/sql/functions.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L314-L329
def approx_count_distinct(col, rsd=None): """Aggregate function: returns a new :class:`Column` for approximate distinct count of column `col`. :param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more efficient to use :func:`countDistinct` >>> df.agg(approx_coun...
[ "def", "approx_count_distinct", "(", "col", ",", "rsd", "=", "None", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "if", "rsd", "is", "None", ":", "jc", "=", "sc", ".", "_jvm", ".", "functions", ".", "approx_count_distinct", "(", "_to_...
Aggregate function: returns a new :class:`Column` for approximate distinct count of column `col`. :param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more efficient to use :func:`countDistinct` >>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collec...
[ "Aggregate", "function", ":", "returns", "a", "new", ":", "class", ":", "Column", "for", "approximate", "distinct", "count", "of", "column", "col", "." ]
python
train
chaimleib/intervaltree
intervaltree/node.py
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L216-L223
def discard(self, interval): """ Returns self after removing interval and balancing. If interval is not present, do nothing. """ done = [] return self.remove_interval_helper(interval, done, should_raise_error=False)
[ "def", "discard", "(", "self", ",", "interval", ")", ":", "done", "=", "[", "]", "return", "self", ".", "remove_interval_helper", "(", "interval", ",", "done", ",", "should_raise_error", "=", "False", ")" ]
Returns self after removing interval and balancing. If interval is not present, do nothing.
[ "Returns", "self", "after", "removing", "interval", "and", "balancing", "." ]
python
train
neurodata/ndio
ndio/convert/tiff.py
https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/convert/tiff.py#L98-L133
def load_tiff_multipage(tiff_filename, dtype='float32'): """ Load a multipage tiff into a single variable in x,y,z format. Arguments: tiff_filename: Filename of source data dtype: data type to use for the returned tensor Returns: Array containing contents from i...
[ "def", "load_tiff_multipage", "(", "tiff_filename", ",", "dtype", "=", "'float32'", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "tiff_filename", ")", ":", "raise", "RuntimeError", "(", "'could not find file \"%s\"'", "%", "tiff_filename", ")", ...
Load a multipage tiff into a single variable in x,y,z format. Arguments: tiff_filename: Filename of source data dtype: data type to use for the returned tensor Returns: Array containing contents from input tiff file in xyz order
[ "Load", "a", "multipage", "tiff", "into", "a", "single", "variable", "in", "x", "y", "z", "format", "." ]
python
test
cherrypy/cheroot
cheroot/ssl/pyopenssl.py
https://github.com/cherrypy/cheroot/blob/2af3b1798d66da697957480d3a8b4831a405770b/cheroot/ssl/pyopenssl.py#L270-L278
def get_context(self): """Return an SSL.Context from self attributes.""" # See https://code.activestate.com/recipes/442473/ c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_c...
[ "def", "get_context", "(", "self", ")", ":", "# See https://code.activestate.com/recipes/442473/", "c", "=", "SSL", ".", "Context", "(", "SSL", ".", "SSLv23_METHOD", ")", "c", ".", "use_privatekey_file", "(", "self", ".", "private_key", ")", "if", "self", ".", ...
Return an SSL.Context from self attributes.
[ "Return", "an", "SSL", ".", "Context", "from", "self", "attributes", "." ]
python
train
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L9585-L9628
def set_final_values(self, enabled, v_box_values, extra_config_values): """This method allows the appliance's user to change the configuration for the virtual system descriptions. For each array item returned from :py:func:`get_description` , you must pass in one boolean value and one configurat...
[ "def", "set_final_values", "(", "self", ",", "enabled", ",", "v_box_values", ",", "extra_config_values", ")", ":", "if", "not", "isinstance", "(", "enabled", ",", "list", ")", ":", "raise", "TypeError", "(", "\"enabled can only be an instance of type list\"", ")", ...
This method allows the appliance's user to change the configuration for the virtual system descriptions. For each array item returned from :py:func:`get_description` , you must pass in one boolean value and one configuration value. Each item in the boolean array determines whether the p...
[ "This", "method", "allows", "the", "appliance", "s", "user", "to", "change", "the", "configuration", "for", "the", "virtual", "system", "descriptions", ".", "For", "each", "array", "item", "returned", "from", ":", "py", ":", "func", ":", "get_description", "...
python
train
tritemio/PyBroMo
pybromo/psflib.py
https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/psflib.py#L132-L137
def load_PSFLab_file(fname): """Load the array `data` in the .mat file `fname`.""" if os.path.exists(fname) or os.path.exists(fname + '.mat'): return loadmat(fname)['data'] else: raise IOError("Can't find PSF file '%s'" % fname)
[ "def", "load_PSFLab_file", "(", "fname", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "fname", ")", "or", "os", ".", "path", ".", "exists", "(", "fname", "+", "'.mat'", ")", ":", "return", "loadmat", "(", "fname", ")", "[", "'data'", "]",...
Load the array `data` in the .mat file `fname`.
[ "Load", "the", "array", "data", "in", "the", ".", "mat", "file", "fname", "." ]
python
valid
archman/beamline
beamline/lattice.py
https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/lattice.py#L580-L589
def getElementCtrlConf(self, elementKw): """ return keyword's EPICS control configs, if not setup, return {} """ try: retval = self.all_elements['_epics'][elementKw.upper()] except KeyError: retval = {} return retval
[ "def", "getElementCtrlConf", "(", "self", ",", "elementKw", ")", ":", "try", ":", "retval", "=", "self", ".", "all_elements", "[", "'_epics'", "]", "[", "elementKw", ".", "upper", "(", ")", "]", "except", "KeyError", ":", "retval", "=", "{", "}", "retu...
return keyword's EPICS control configs, if not setup, return {}
[ "return", "keyword", "s", "EPICS", "control", "configs", "if", "not", "setup", "return", "{}" ]
python
train
PyPSA/PyPSA
pypsa/geo.py
https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/geo.py#L36-L83
def haversine(a0,a1): """ Compute the distance in km between two sets of points in long/lat. One dimension of a* should be 2; longitude then latitude. Uses haversine formula. Parameters ---------- a0: array/list of at most 2 dimensions One dimension must be 2 a1: array/list of ...
[ "def", "haversine", "(", "a0", ",", "a1", ")", ":", "a", "=", "[", "np", ".", "asarray", "(", "a0", ",", "dtype", "=", "float", ")", ",", "np", ".", "asarray", "(", "a1", ",", "dtype", "=", "float", ")", "]", "for", "i", "in", "range", "(", ...
Compute the distance in km between two sets of points in long/lat. One dimension of a* should be 2; longitude then latitude. Uses haversine formula. Parameters ---------- a0: array/list of at most 2 dimensions One dimension must be 2 a1: array/list of at most 2 dimensions One d...
[ "Compute", "the", "distance", "in", "km", "between", "two", "sets", "of", "points", "in", "long", "/", "lat", "." ]
python
train
UDST/pandana
pandana/network.py
https://github.com/UDST/pandana/blob/961a7ef8d3b0144b190cb60bbd61845fca6fb314/pandana/network.py#L495-L581
def nearest_pois(self, distance, category, num_pois=1, max_distance=None, imp_name=None, include_poi_ids=False): """ Find the distance to the nearest pois from each source node. The bigger values in this case mean less accessibility. Parameters ---------- ...
[ "def", "nearest_pois", "(", "self", ",", "distance", ",", "category", ",", "num_pois", "=", "1", ",", "max_distance", "=", "None", ",", "imp_name", "=", "None", ",", "include_poi_ids", "=", "False", ")", ":", "if", "max_distance", "is", "None", ":", "max...
Find the distance to the nearest pois from each source node. The bigger values in this case mean less accessibility. Parameters ---------- distance : float The maximum distance to look for pois. This will usually be a distance unit in meters however if you have ...
[ "Find", "the", "distance", "to", "the", "nearest", "pois", "from", "each", "source", "node", ".", "The", "bigger", "values", "in", "this", "case", "mean", "less", "accessibility", "." ]
python
test
saltstack/salt
salt/utils/asynchronous.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/asynchronous.py#L15-L24
def current_ioloop(io_loop): ''' A context manager that will set the current ioloop to io_loop for the context ''' orig_loop = tornado.ioloop.IOLoop.current() io_loop.make_current() try: yield finally: orig_loop.make_current()
[ "def", "current_ioloop", "(", "io_loop", ")", ":", "orig_loop", "=", "tornado", ".", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "io_loop", ".", "make_current", "(", ")", "try", ":", "yield", "finally", ":", "orig_loop", ".", "make_current", "(", ...
A context manager that will set the current ioloop to io_loop for the context
[ "A", "context", "manager", "that", "will", "set", "the", "current", "ioloop", "to", "io_loop", "for", "the", "context" ]
python
train
ValvePython/steam
steam/util/binary.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/util/binary.py#L51-L61
def unpack(self, format_text): """Unpack bytes using struct modules format :param format_text: struct's module format :type format_text: :class:`str` :return data: result from :func:`struct.unpack_from` :rtype: :class:`tuple` """ data = _unpack_from(format_text,...
[ "def", "unpack", "(", "self", ",", "format_text", ")", ":", "data", "=", "_unpack_from", "(", "format_text", ",", "self", ".", "data", ",", "self", ".", "offset", ")", "self", ".", "offset", "+=", "_calcsize", "(", "format_text", ")", "return", "data" ]
Unpack bytes using struct modules format :param format_text: struct's module format :type format_text: :class:`str` :return data: result from :func:`struct.unpack_from` :rtype: :class:`tuple`
[ "Unpack", "bytes", "using", "struct", "modules", "format" ]
python
train
cltrudeau/django-flowr
flowr/models.py
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L226-L236
def ancestors(self): """Returns a list of the ancestors of this node.""" ancestors = set([]) self._depth_ascend(self, ancestors) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(...
[ "def", "ancestors", "(", "self", ")", ":", "ancestors", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_ascend", "(", "self", ",", "ancestors", ")", "try", ":", "ancestors", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "# we weren't...
Returns a list of the ancestors of this node.
[ "Returns", "a", "list", "of", "the", "ancestors", "of", "this", "node", "." ]
python
valid
numenta/nupic
src/nupic/database/connection.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L643-L656
def _getCommonSteadyDBArgsDict(): """ Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection constructor. """ return dict( creator = pymysql, host = Configuration.get('nupic.cluster.database.host'), port = int(Configuration.get('nupic.cluster.database.port')), user = ...
[ "def", "_getCommonSteadyDBArgsDict", "(", ")", ":", "return", "dict", "(", "creator", "=", "pymysql", ",", "host", "=", "Configuration", ".", "get", "(", "'nupic.cluster.database.host'", ")", ",", "port", "=", "int", "(", "Configuration", ".", "get", "(", "'...
Returns a dictionary of arguments for DBUtils.SteadyDB.SteadyDBConnection constructor.
[ "Returns", "a", "dictionary", "of", "arguments", "for", "DBUtils", ".", "SteadyDB", ".", "SteadyDBConnection", "constructor", "." ]
python
valid
pycontribs/pyrax
pyrax/cloudmonitoring.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L1321-L1327
def update_alarm(self, entity, alarm, criteria=None, disabled=False, label=None, name=None, metadata=None): """ Updates an existing alarm on the given entity. """ return entity.update_alarm(alarm, criteria=criteria, disabled=disabled, label=label, name=name, metad...
[ "def", "update_alarm", "(", "self", ",", "entity", ",", "alarm", ",", "criteria", "=", "None", ",", "disabled", "=", "False", ",", "label", "=", "None", ",", "name", "=", "None", ",", "metadata", "=", "None", ")", ":", "return", "entity", ".", "updat...
Updates an existing alarm on the given entity.
[ "Updates", "an", "existing", "alarm", "on", "the", "given", "entity", "." ]
python
train
gtalarico/airtable-python-wrapper
airtable/airtable.py
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L420-L445
def update_by_field(self, field_name, field_value, fields, typecast=False, **options): """ Updates the first record to match field name and value. Only Fields passed are updated, the rest are left as is. >>> record = {'Name': 'John', 'Tel': '540-255-5522'} >>> airtable.upd...
[ "def", "update_by_field", "(", "self", ",", "field_name", ",", "field_value", ",", "fields", ",", "typecast", "=", "False", ",", "*", "*", "options", ")", ":", "record", "=", "self", ".", "match", "(", "field_name", ",", "field_value", ",", "*", "*", "...
Updates the first record to match field name and value. Only Fields passed are updated, the rest are left as is. >>> record = {'Name': 'John', 'Tel': '540-255-5522'} >>> airtable.update_by_field('Name', 'John', record) Args: field_name (``str``): Name of field to mat...
[ "Updates", "the", "first", "record", "to", "match", "field", "name", "and", "value", ".", "Only", "Fields", "passed", "are", "updated", "the", "rest", "are", "left", "as", "is", ".", ">>>", "record", "=", "{", "Name", ":", "John", "Tel", ":", "540", ...
python
train
acrisci/i3ipc-python
i3ipc/i3ipc.py
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L534-L549
def get_bar_config(self, bar_id=None): """ Get the configuration of a single bar. Defaults to the first if none is specified. Use :meth:`get_bar_config_list` to obtain a list of valid IDs. :rtype: BarConfigReply """ if not bar_id: bar_config_list = se...
[ "def", "get_bar_config", "(", "self", ",", "bar_id", "=", "None", ")", ":", "if", "not", "bar_id", ":", "bar_config_list", "=", "self", ".", "get_bar_config_list", "(", ")", "if", "not", "bar_config_list", ":", "return", "None", "bar_id", "=", "bar_config_li...
Get the configuration of a single bar. Defaults to the first if none is specified. Use :meth:`get_bar_config_list` to obtain a list of valid IDs. :rtype: BarConfigReply
[ "Get", "the", "configuration", "of", "a", "single", "bar", ".", "Defaults", "to", "the", "first", "if", "none", "is", "specified", ".", "Use", ":", "meth", ":", "get_bar_config_list", "to", "obtain", "a", "list", "of", "valid", "IDs", "." ]
python
train
MillionIntegrals/vel
vel/util/intepolate.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/intepolate.py#L48-L50
def interpolate_series(start, end, steps, how='linear'): """ Interpolate series between start and end in given number of steps """ return INTERP_DICT[how](start, end, steps)
[ "def", "interpolate_series", "(", "start", ",", "end", ",", "steps", ",", "how", "=", "'linear'", ")", ":", "return", "INTERP_DICT", "[", "how", "]", "(", "start", ",", "end", ",", "steps", ")" ]
Interpolate series between start and end in given number of steps
[ "Interpolate", "series", "between", "start", "and", "end", "in", "given", "number", "of", "steps" ]
python
train
Qiskit/qiskit-terra
qiskit/visualization/text.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/text.py#L473-L481
def dump(self, filename, encoding="utf8"): """ Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8". """ with open(filename, mode='w', encoding=encoding) as text_file: text...
[ "def", "dump", "(", "self", ",", "filename", ",", "encoding", "=", "\"utf8\"", ")", ":", "with", "open", "(", "filename", ",", "mode", "=", "'w'", ",", "encoding", "=", "encoding", ")", "as", "text_file", ":", "text_file", ".", "write", "(", "self", ...
Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8".
[ "Dumps", "the", "ascii", "art", "in", "the", "file", ".", "Args", ":", "filename", "(", "str", ")", ":", "File", "to", "dump", "the", "ascii", "art", ".", "encoding", "(", "str", ")", ":", "Optional", ".", "Default", "utf", "-", "8", "." ]
python
test
raiden-network/raiden
raiden/transfer/merkle_tree.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/merkle_tree.py#L16-L33
def hash_pair(first: Keccak256, second: Optional[Keccak256]) -> Keccak256: """ Computes the keccak hash of the elements ordered topologically. Since a merkle proof will not include all the elements, but only the path starting from the leaves up to the root, the order of the elements is not known by the...
[ "def", "hash_pair", "(", "first", ":", "Keccak256", ",", "second", ":", "Optional", "[", "Keccak256", "]", ")", "->", "Keccak256", ":", "assert", "first", "is", "not", "None", "if", "second", "is", "None", ":", "return", "first", "if", "first", ">", "s...
Computes the keccak hash of the elements ordered topologically. Since a merkle proof will not include all the elements, but only the path starting from the leaves up to the root, the order of the elements is not known by the proof checker. The topological order is used as a deterministic way of orderin...
[ "Computes", "the", "keccak", "hash", "of", "the", "elements", "ordered", "topologically", "." ]
python
train
oz123/blogit
blogit/blogit.py
https://github.com/oz123/blogit/blob/15b94969fa43aaf8dc677a8184b144ae8c0f7700/blogit/blogit.py#L349-L354
def render_archive(entries): """Creates the archive page""" context = GLOBAL_TEMPLATE_CONTEXT.copy() context['entries'] = entries _render(context, 'archive_index.html', os.path.join(CONFIG['output_to'], 'archive/index.html')),
[ "def", "render_archive", "(", "entries", ")", ":", "context", "=", "GLOBAL_TEMPLATE_CONTEXT", ".", "copy", "(", ")", "context", "[", "'entries'", "]", "=", "entries", "_render", "(", "context", ",", "'archive_index.html'", ",", "os", ".", "path", ".", "join"...
Creates the archive page
[ "Creates", "the", "archive", "page" ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/textio.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L1799-L1814
def __logfile_error(self, e): """ Shows an error message to standard error if the log file can't be written to. Used internally. @type e: Exception @param e: Exception raised when trying to write to the log file. """ from sys import stderr msg =...
[ "def", "__logfile_error", "(", "self", ",", "e", ")", ":", "from", "sys", "import", "stderr", "msg", "=", "\"Warning, error writing log file %s: %s\\n\"", "msg", "=", "msg", "%", "(", "self", ".", "logfile", ",", "str", "(", "e", ")", ")", "stderr", ".", ...
Shows an error message to standard error if the log file can't be written to. Used internally. @type e: Exception @param e: Exception raised when trying to write to the log file.
[ "Shows", "an", "error", "message", "to", "standard", "error", "if", "the", "log", "file", "can", "t", "be", "written", "to", "." ]
python
train
rueckstiess/mtools
mtools/mlogfilter/filters/logline_filter.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mlogfilter/filters/logline_filter.py#L124-L152
def accept(self, logevent): """ Process line. Overwrite BaseFilter.accept() and return True if the provided logevent should be accepted (causing output), or False if not. """ # if several filters are active, all have to agree if self.components and logevent.compo...
[ "def", "accept", "(", "self", ",", "logevent", ")", ":", "# if several filters are active, all have to agree", "if", "self", ".", "components", "and", "logevent", ".", "component", "not", "in", "self", ".", "components", ":", "return", "False", "if", "self", "."...
Process line. Overwrite BaseFilter.accept() and return True if the provided logevent should be accepted (causing output), or False if not.
[ "Process", "line", "." ]
python
train
Qiskit/qiskit-terra
qiskit/providers/basicaer/basicaertools.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaertools.py#L127-L175
def _einsum_matmul_index_helper(gate_indices, number_of_qubits): """Return the index string for Numpy.eignsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices ...
[ "def", "_einsum_matmul_index_helper", "(", "gate_indices", ",", "number_of_qubits", ")", ":", "# Since we use ASCII alphabet for einsum index labels we are limited", "# to 26 total free left (lowercase) and 26 right (uppercase) indexes.", "# The rank of the contracted tensor reduces this as we n...
Return the index string for Numpy.eignsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args...
[ "Return", "the", "index", "string", "for", "Numpy", ".", "eignsum", "matrix", "multiplication", "." ]
python
test
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1385-L1416
def sepconv_relu_sepconv(inputs, filter_size, output_size, first_kernel_size=(1, 1), second_kernel_size=(1, 1), padding="LEFT", nonpadding_mask=None, ...
[ "def", "sepconv_relu_sepconv", "(", "inputs", ",", "filter_size", ",", "output_size", ",", "first_kernel_size", "=", "(", "1", ",", "1", ")", ",", "second_kernel_size", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "\"LEFT\"", ",", "nonpadding_mask", ...
Hidden layer with RELU activation followed by linear projection.
[ "Hidden", "layer", "with", "RELU", "activation", "followed", "by", "linear", "projection", "." ]
python
train
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/containers.py
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/containers.py#L165-L177
def update_widget(self, idx=None): """Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual c...
[ "def", "update_widget", "(", "self", ",", "idx", "=", "None", ")", ":", "if", "idx", "is", "None", ":", "for", "w", "in", "self", ".", "_widgets", ":", "idx", "=", "self", ".", "_get_idx_from_widget", "(", "w", ")", "self", ".", "_write_widget", "(",...
Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions.
[ "Forces", "the", "widget", "at", "given", "index", "to", "be", "updated", "from", "the", "property", "value", ".", "If", "index", "is", "not", "given", "all", "controlled", "widgets", "will", "be", "updated", ".", "This", "method", "should", "be", "called"...
python
train
androguard/androguard
androguard/core/bytecodes/apk.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/apk.py#L1082-L1093
def get_main_activity(self): """ Return the name of the main activity This value is read from the AndroidManifest.xml :rtype: str """ activities = self.get_main_activities() if len(activities) > 0: return self._format_value(activities.pop()) ...
[ "def", "get_main_activity", "(", "self", ")", ":", "activities", "=", "self", ".", "get_main_activities", "(", ")", "if", "len", "(", "activities", ")", ">", "0", ":", "return", "self", ".", "_format_value", "(", "activities", ".", "pop", "(", ")", ")", ...
Return the name of the main activity This value is read from the AndroidManifest.xml :rtype: str
[ "Return", "the", "name", "of", "the", "main", "activity" ]
python
train
saltstack/salt
salt/states/selinux.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/selinux.py#L318-L396
def fcontext_policy_present(name, sel_type, filetype='a', sel_user=None, sel_level=None): ''' .. versionadded:: 2017.7.0 Makes sure a SELinux policy for a given filespec (name), filetype and SELinux context type is present. name filespec of the file or directory. Regex syntax is allowed. ...
[ "def", "fcontext_policy_present", "(", "name", ",", "sel_type", ",", "filetype", "=", "'a'", ",", "sel_user", "=", "None", ",", "sel_level", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'changes'", ...
.. versionadded:: 2017.7.0 Makes sure a SELinux policy for a given filespec (name), filetype and SELinux context type is present. name filespec of the file or directory. Regex syntax is allowed. sel_type SELinux context type. There are many. filetype The SELinux filetype ...
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
python
train
jilljenn/tryalgo
tryalgo/dfs.py
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/dfs.py#L66-L82
def dfs_grid_recursive(grid, i, j, mark='X', free='.'): """DFS on a grid, mark connected component, iterative version :param grid: matrix, 4-neighborhood :param i,j: cell in this matrix, start of DFS exploration :param free: symbol for walkable cells :param mark: symbol to overwrite visited vertice...
[ "def", "dfs_grid_recursive", "(", "grid", ",", "i", ",", "j", ",", "mark", "=", "'X'", ",", "free", "=", "'.'", ")", ":", "height", "=", "len", "(", "grid", ")", "width", "=", "len", "(", "grid", "[", "0", "]", ")", "grid", "[", "i", "]", "["...
DFS on a grid, mark connected component, iterative version :param grid: matrix, 4-neighborhood :param i,j: cell in this matrix, start of DFS exploration :param free: symbol for walkable cells :param mark: symbol to overwrite visited vertices :complexity: linear
[ "DFS", "on", "a", "grid", "mark", "connected", "component", "iterative", "version" ]
python
train
ubyssey/dispatch
dispatch/api/views.py
https://github.com/ubyssey/dispatch/blob/8da6084fe61726f20e9cf675190480cfc45ee764/dispatch/api/views.py#L76-L112
def get_queryset(self): """Optionally restricts the returned articles by filtering against a `topic` query parameter in the URL.""" # Get base queryset from DispatchPublishableMixin queryset = self.get_publishable_queryset() # Optimize queries by prefetching related data ...
[ "def", "get_queryset", "(", "self", ")", ":", "# Get base queryset from DispatchPublishableMixin", "queryset", "=", "self", ".", "get_publishable_queryset", "(", ")", "# Optimize queries by prefetching related data", "queryset", "=", "queryset", ".", "select_related", "(", ...
Optionally restricts the returned articles by filtering against a `topic` query parameter in the URL.
[ "Optionally", "restricts", "the", "returned", "articles", "by", "filtering", "against", "a", "topic", "query", "parameter", "in", "the", "URL", "." ]
python
test
CEA-COSMIC/ModOpt
modopt/base/transform.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L16-L60
def cube2map(data_cube, layout): r"""Cube to Map This method transforms the input data from a 3D cube to a 2D map with a specified layout Parameters ---------- data_cube : np.ndarray Input data cube, 3D array of 2D images Layout : tuple 2D layout of 2D images Returns ...
[ "def", "cube2map", "(", "data_cube", ",", "layout", ")", ":", "if", "data_cube", ".", "ndim", "!=", "3", ":", "raise", "ValueError", "(", "'The input data must have 3 dimensions.'", ")", "if", "data_cube", ".", "shape", "[", "0", "]", "!=", "np", ".", "pro...
r"""Cube to Map This method transforms the input data from a 3D cube to a 2D map with a specified layout Parameters ---------- data_cube : np.ndarray Input data cube, 3D array of 2D images Layout : tuple 2D layout of 2D images Returns ------- np.ndarray 2D map ...
[ "r", "Cube", "to", "Map" ]
python
train
bcbio/bcbio-nextgen
bcbio/variation/vcfutils.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfutils.py#L326-L335
def _check_samples_nodups(fnames): """Ensure a set of input VCFs do not have duplicate samples. """ counts = defaultdict(int) for f in fnames: for s in get_samples(f): counts[s] += 1 duplicates = [s for s, c in counts.items() if c > 1] if duplicates: raise ValueError(...
[ "def", "_check_samples_nodups", "(", "fnames", ")", ":", "counts", "=", "defaultdict", "(", "int", ")", "for", "f", "in", "fnames", ":", "for", "s", "in", "get_samples", "(", "f", ")", ":", "counts", "[", "s", "]", "+=", "1", "duplicates", "=", "[", ...
Ensure a set of input VCFs do not have duplicate samples.
[ "Ensure", "a", "set", "of", "input", "VCFs", "do", "not", "have", "duplicate", "samples", "." ]
python
train
iotile/coretools
transport_plugins/native_ble/iotile_transport_native_ble/connection_manager.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/connection_manager.py#L491-L524
def _force_disconnect_action(self, action): """Forcibly disconnect a device. Args: action (ConnectionAction): the action object describing what we are forcibly disconnecting """ conn_key = action.data['id'] if self._get_connection_state(conn_key) == ...
[ "def", "_force_disconnect_action", "(", "self", ",", "action", ")", ":", "conn_key", "=", "action", ".", "data", "[", "'id'", "]", "if", "self", ".", "_get_connection_state", "(", "conn_key", ")", "==", "self", ".", "Disconnected", ":", "return", "data", "...
Forcibly disconnect a device. Args: action (ConnectionAction): the action object describing what we are forcibly disconnecting
[ "Forcibly", "disconnect", "a", "device", "." ]
python
train
SoCo/SoCo
dev_tools/analyse_ws.py
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L434-L489
def __build_option_parser(): """ Build the option parser for this script """ description = """ Tool to analyze Wireshark dumps of Sonos traffic. The files that are input to this script must be in the "Wireshark/tcpdump/...-libpcap" format, which can be exported from Wireshark. To use the o...
[ "def", "__build_option_parser", "(", ")", ":", "description", "=", "\"\"\"\n Tool to analyze Wireshark dumps of Sonos traffic.\n\n The files that are input to this script must be in the\n \"Wireshark/tcpdump/...-libpcap\" format, which can be exported from\n Wireshark.\n\n To use the op...
Build the option parser for this script
[ "Build", "the", "option", "parser", "for", "this", "script" ]
python
train
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L867-L872
def get_sh_ids(self, identity, backend_name): """ Return the Sorting Hat id and uuid for an identity """ # Convert the dict to tuple so it is hashable identity_tuple = tuple(identity.items()) sh_ids = self.__get_sh_ids_cache(identity_tuple, backend_name) return sh_ids
[ "def", "get_sh_ids", "(", "self", ",", "identity", ",", "backend_name", ")", ":", "# Convert the dict to tuple so it is hashable", "identity_tuple", "=", "tuple", "(", "identity", ".", "items", "(", ")", ")", "sh_ids", "=", "self", ".", "__get_sh_ids_cache", "(", ...
Return the Sorting Hat id and uuid for an identity
[ "Return", "the", "Sorting", "Hat", "id", "and", "uuid", "for", "an", "identity" ]
python
train
ActivisionGameScience/assertpy
assertpy/assertpy.py
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L653-L663
def matches(self, pattern): """Asserts that val is string and matches regex pattern.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(pattern, str_types): raise TypeError('given pattern arg must be a string') if l...
[ "def", "matches", "(", "self", ",", "pattern", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val is not a string'", ")", "if", "not", "isinstance", "(", "pattern", ",", "str_types", ...
Asserts that val is string and matches regex pattern.
[ "Asserts", "that", "val", "is", "string", "and", "matches", "regex", "pattern", "." ]
python
valid
NoviceLive/intellicoder
intellicoder/utils.py
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/utils.py#L181-L186
def read_files(filenames, with_name=False): """Read many files.""" text = [read_file(filename) for filename in filenames] if with_name: return dict(zip(filenames, text)) return text
[ "def", "read_files", "(", "filenames", ",", "with_name", "=", "False", ")", ":", "text", "=", "[", "read_file", "(", "filename", ")", "for", "filename", "in", "filenames", "]", "if", "with_name", ":", "return", "dict", "(", "zip", "(", "filenames", ",", ...
Read many files.
[ "Read", "many", "files", "." ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L181-L190
def move(self, move): """Change the translation of this transform by the amount given. Parameters ---------- move : array-like The values to be added to the current translation of the transform. """ move = as_vec4(move, default=(0, 0, 0, 0)) self.tran...
[ "def", "move", "(", "self", ",", "move", ")", ":", "move", "=", "as_vec4", "(", "move", ",", "default", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "self", ".", "translate", "=", "self", ".", "translate", "+", "move" ]
Change the translation of this transform by the amount given. Parameters ---------- move : array-like The values to be added to the current translation of the transform.
[ "Change", "the", "translation", "of", "this", "transform", "by", "the", "amount", "given", "." ]
python
train
python/core-workflow
blurb/blurb.py
https://github.com/python/core-workflow/blob/b93c76195f6db382cfcefee334380fb4c68d4e21/blurb/blurb.py#L1204-L1584
def split(*, released=False): """ Split the current Misc/NEWS into a zillion little blurb files. Assumes that the newest version section in Misc/NEWS is under development, and splits those entries into the "next" subdirectory. If the current version has actually been released, use the --released flag. Also runs "...
[ "def", "split", "(", "*", ",", "released", "=", "False", ")", ":", "# note: populate also does chdir $python_root/Misc for you", "populate", "(", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "\"NEWS\"", ")", ":", "error", "(", "\"You don't have a Mis...
Split the current Misc/NEWS into a zillion little blurb files. Assumes that the newest version section in Misc/NEWS is under development, and splits those entries into the "next" subdirectory. If the current version has actually been released, use the --released flag. Also runs "blurb populate" for you.
[ "Split", "the", "current", "Misc", "/", "NEWS", "into", "a", "zillion", "little", "blurb", "files", "." ]
python
train
pandas-dev/pandas
pandas/core/series.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/series.py#L523-L538
def compress(self, condition, *args, **kwargs): """ Return selected slices of an array along given axis as a Series. .. deprecated:: 0.24.0 See Also -------- numpy.ndarray.compress """ msg = ("Series.compress(condition) is deprecated. " "U...
[ "def", "compress", "(", "self", ",", "condition", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "(", "\"Series.compress(condition) is deprecated. \"", "\"Use 'Series[condition]' or \"", "\"'np.asarray(series).compress(condition)' instead.\"", ")", "warn...
Return selected slices of an array along given axis as a Series. .. deprecated:: 0.24.0 See Also -------- numpy.ndarray.compress
[ "Return", "selected", "slices", "of", "an", "array", "along", "given", "axis", "as", "a", "Series", "." ]
python
train
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/viewport.py
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L147-L246
def get_viewport_profile(request_envelope): # type: (RequestEnvelope) -> ViewportProfile """Utility method, to get viewport profile. The viewport profile is calculated using the shape, current pixel width and height, along with the dpi. If there is no `viewport` value in `request_envelope.cont...
[ "def", "get_viewport_profile", "(", "request_envelope", ")", ":", "# type: (RequestEnvelope) -> ViewportProfile", "viewport_state", "=", "request_envelope", ".", "context", ".", "viewport", "if", "viewport_state", ":", "shape", "=", "viewport_state", ".", "shape", "curren...
Utility method, to get viewport profile. The viewport profile is calculated using the shape, current pixel width and height, along with the dpi. If there is no `viewport` value in `request_envelope.context`, then an `ViewportProfile.UNKNOWN_VIEWPORT_PROFILE` is returned. :param request_envelo...
[ "Utility", "method", "to", "get", "viewport", "profile", "." ]
python
train
quantopian/zipline
zipline/pipeline/loaders/earnings_estimates.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1294-L1336
def merge_split_adjustments_with_overwrites( self, pre, post, overwrites, requested_split_adjusted_columns ): """ Merge split adjustments with the dict containing overwrites. Parameters ---------- pre : dict[str -> dict[int -> list]] ...
[ "def", "merge_split_adjustments_with_overwrites", "(", "self", ",", "pre", ",", "post", ",", "overwrites", ",", "requested_split_adjusted_columns", ")", ":", "for", "column_name", "in", "requested_split_adjusted_columns", ":", "# We can do a merge here because the timestamps in...
Merge split adjustments with the dict containing overwrites. Parameters ---------- pre : dict[str -> dict[int -> list]] The adjustments that occur before the split-adjusted-asof-date. post : dict[str -> dict[int -> list]] The adjustments that occur after the spli...
[ "Merge", "split", "adjustments", "with", "the", "dict", "containing", "overwrites", "." ]
python
train
calmjs/calmjs
src/calmjs/dist.py
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/dist.py#L219-L227
def read_egginfo_json(pkg_name, filename=DEFAULT_JSON, working_set=None): """ Read json from egginfo of a package identified by `pkg_name` that's already installed within the current Python environment. """ working_set = working_set or default_working_set dist = find_pkg_dist(pkg_name, working_...
[ "def", "read_egginfo_json", "(", "pkg_name", ",", "filename", "=", "DEFAULT_JSON", ",", "working_set", "=", "None", ")", ":", "working_set", "=", "working_set", "or", "default_working_set", "dist", "=", "find_pkg_dist", "(", "pkg_name", ",", "working_set", "=", ...
Read json from egginfo of a package identified by `pkg_name` that's already installed within the current Python environment.
[ "Read", "json", "from", "egginfo", "of", "a", "package", "identified", "by", "pkg_name", "that", "s", "already", "installed", "within", "the", "current", "Python", "environment", "." ]
python
train
ECESeniorDesign/lazy_record
lazy_record/repo.py
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L93-L99
def _standard_items(self, restrictions): """Generate argument pairs for queries like where(id=2)""" standard_items = self._build_where(restrictions, for_in=False) names = ["{}.{} == ?".format(pair[0], pair[1]) for pair in standard_items] values = [item[2] for item in sta...
[ "def", "_standard_items", "(", "self", ",", "restrictions", ")", ":", "standard_items", "=", "self", ".", "_build_where", "(", "restrictions", ",", "for_in", "=", "False", ")", "names", "=", "[", "\"{}.{} == ?\"", ".", "format", "(", "pair", "[", "0", "]",...
Generate argument pairs for queries like where(id=2)
[ "Generate", "argument", "pairs", "for", "queries", "like", "where", "(", "id", "=", "2", ")" ]
python
train
kervi/kervi-core
kervi/displays/__init__.py
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/displays/__init__.py#L69-L83
def add_page(self, page, default = True): r""" Add a display page to the display. :param page: Page to be added :type display_id: ``DisplayPage`` :param default: True if this page should be shown upon initialization. :type name: ``bool`` """ ...
[ "def", "add_page", "(", "self", ",", "page", ",", "default", "=", "True", ")", ":", "self", ".", "_pages", "[", "page", ".", "page_id", "]", "=", "page", "page", ".", "_add_display", "(", "self", ")", "if", "default", "or", "not", "self", ".", "_ac...
r""" Add a display page to the display. :param page: Page to be added :type display_id: ``DisplayPage`` :param default: True if this page should be shown upon initialization. :type name: ``bool``
[ "r", "Add", "a", "display", "page", "to", "the", "display", "." ]
python
train
osrg/ryu
ryu/lib/packet/packet_utils.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/packet/packet_utils.py#L106-L138
def fletcher_checksum(data, offset): """ Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0. """ c0 = 0 c1 = 0 pos = 0 length = len(data) data = bytearray(da...
[ "def", "fletcher_checksum", "(", "data", ",", "offset", ")", ":", "c0", "=", "0", "c1", "=", "0", "pos", "=", "0", "length", "=", "len", "(", "data", ")", "data", "=", "bytearray", "(", "data", ")", "data", "[", "offset", ":", "offset", "+", "2",...
Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0.
[ "Fletcher", "Checksum", "--", "Refer", "to", "RFC1008" ]
python
train
StackStorm/pybind
pybind/nos/v6_0_2f/rbridge_id/crypto/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/rbridge_id/crypto/__init__.py#L127-L148
def _set_ca(self, v, load=False): """ Setter method for ca, mapped from YANG variable /rbridge_id/crypto/ca (list) If this variable is read-only (config: false) in the source YANG file, then _set_ca is considered as a private method. Backends looking to populate this variable should do so via ca...
[ "def", "_set_ca", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", "=...
Setter method for ca, mapped from YANG variable /rbridge_id/crypto/ca (list) If this variable is read-only (config: false) in the source YANG file, then _set_ca is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ca() directly.
[ "Setter", "method", "for", "ca", "mapped", "from", "YANG", "variable", "/", "rbridge_id", "/", "crypto", "/", "ca", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", ...
python
train
thespacedoctor/tastic
tastic/tastic.py
https://github.com/thespacedoctor/tastic/blob/a0a16cf329a50057906ac3f696bb60b6fcee25e0/tastic/tastic.py#L1197-L1247
def add_note( self, note): """*Add a note to this taskpaper object* **Key Arguments:** - ``note`` -- the note (string) **Return:** - None **Usage:** To add a note to a document, project or task object: .. code-b...
[ "def", "add_note", "(", "self", ",", "note", ")", ":", "self", ".", "refresh", "note", "=", "note", ".", "strip", "(", ")", "newNote", "=", "self", ".", "_get_object", "(", "regex", "=", "re", ".", "compile", "(", "r'((?<=\\n)|(?<=^))(?P<title>\\S(?<!-)((?...
*Add a note to this taskpaper object* **Key Arguments:** - ``note`` -- the note (string) **Return:** - None **Usage:** To add a note to a document, project or task object: .. code-block:: python newNote = doc.add_note(And anot...
[ "*", "Add", "a", "note", "to", "this", "taskpaper", "object", "*" ]
python
train
ivbeg/qddate
qddate/qdparser.py
https://github.com/ivbeg/qddate/blob/f7730610611f2509ab264bc8d77a902742daf08c/qddate/qdparser.py#L79-L122
def match(self, text, noprefix=False): """Matches date/datetime string against date patterns and returns pattern and parsed date if matched. It's not indeded for common usage, since if successful it returns date as array of numbers and pattern that matched this date :param text: ...
[ "def", "match", "(", "self", ",", "text", ",", "noprefix", "=", "False", ")", ":", "n", "=", "len", "(", "text", ")", "if", "self", ".", "cachedpats", "is", "not", "None", ":", "pats", "=", "self", ".", "cachedpats", "else", ":", "pats", "=", "se...
Matches date/datetime string against date patterns and returns pattern and parsed date if matched. It's not indeded for common usage, since if successful it returns date as array of numbers and pattern that matched this date :param text: Any human readable string :type date_...
[ "Matches", "date", "/", "datetime", "string", "against", "date", "patterns", "and", "returns", "pattern", "and", "parsed", "date", "if", "matched", ".", "It", "s", "not", "indeded", "for", "common", "usage", "since", "if", "successful", "it", "returns", "dat...
python
train
CGATOxford/UMI-tools
umi_tools/sam_methods.py
https://github.com/CGATOxford/UMI-tools/blob/c4b5d84aac391d59916d294f8f4f8f5378abcfbe/umi_tools/sam_methods.py#L520-L558
def get_gene_count_tab(infile, bc_getter=None): ''' Yields the counts per umi for each gene bc_getter: method to get umi (plus optionally, cell barcode) from read, e.g get_umi_read_id or get_umi_tag TODO: ADD FOLLOWING OPTION skip_regex: skip genes matching this regex. Us...
[ "def", "get_gene_count_tab", "(", "infile", ",", "bc_getter", "=", "None", ")", ":", "gene", "=", "None", "counts", "=", "collections", ".", "Counter", "(", ")", "for", "line", "in", "infile", ":", "values", "=", "line", ".", "strip", "(", ")", ".", ...
Yields the counts per umi for each gene bc_getter: method to get umi (plus optionally, cell barcode) from read, e.g get_umi_read_id or get_umi_tag TODO: ADD FOLLOWING OPTION skip_regex: skip genes matching this regex. Useful to ignore unassigned reads (as per get_bundles class above)
[ "Yields", "the", "counts", "per", "umi", "for", "each", "gene" ]
python
train
GoogleCloudPlatform/datastore-ndb-python
ndb/context.py
https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/context.py#L908-L928
def call_on_commit(self, callback): """Call a callback upon successful commit of a transaction. If not in a transaction, the callback is called immediately. In a transaction, multiple callbacks may be registered and will be called once the transaction commits, in the order in which they were regis...
[ "def", "call_on_commit", "(", "self", ",", "callback", ")", ":", "if", "not", "self", ".", "in_transaction", "(", ")", ":", "callback", "(", ")", "else", ":", "self", ".", "_on_commit_queue", ".", "append", "(", "callback", ")" ]
Call a callback upon successful commit of a transaction. If not in a transaction, the callback is called immediately. In a transaction, multiple callbacks may be registered and will be called once the transaction commits, in the order in which they were registered. If the transaction fails, the callb...
[ "Call", "a", "callback", "upon", "successful", "commit", "of", "a", "transaction", "." ]
python
train
click-contrib/click-repl
click_repl/__init__.py
https://github.com/click-contrib/click-repl/blob/2d78dc520eb0bb5b813bad3b72344edbd22a7f4e/click_repl/__init__.py#L146-L165
def bootstrap_prompt(prompt_kwargs, group): """ Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs. """ prompt_kwargs = prompt_kwargs or {} defaults = { "history": InMemoryHistory(), "completer": ClickCompleter(gro...
[ "def", "bootstrap_prompt", "(", "prompt_kwargs", ",", "group", ")", ":", "prompt_kwargs", "=", "prompt_kwargs", "or", "{", "}", "defaults", "=", "{", "\"history\"", ":", "InMemoryHistory", "(", ")", ",", "\"completer\"", ":", "ClickCompleter", "(", "group", ")...
Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs.
[ "Bootstrap", "prompt_toolkit", "kwargs", "or", "use", "user", "defined", "values", "." ]
python
train
titusjan/argos
argos/repo/baserti.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L60-L66
def createFromFileName(cls, fileName): """ Creates a BaseRti (or descendant), given a file name. """ # See https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods #logger.debug("Trying to create object of class: {!r}".format(cls)) basename = os.path.basena...
[ "def", "createFromFileName", "(", "cls", ",", "fileName", ")", ":", "# See https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods", "#logger.debug(\"Trying to create object of class: {!r}\".format(cls))", "basename", "=", "os", ".", "path", ".", "basename", ...
Creates a BaseRti (or descendant), given a file name.
[ "Creates", "a", "BaseRti", "(", "or", "descendant", ")", "given", "a", "file", "name", "." ]
python
train
saltstack/salt
salt/modules/openbsdpkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsdpkg.py#L57-L98
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet imple...
[ "def", "list_pkgs", "(", "versions_as_list", "=", "False", ",", "*", "*", "kwargs", ")", ":", "versions_as_list", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "versions_as_list", ")", "# not yet implemented or not applicable", "if", "any", "(", ...
List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
[ "List", "the", "packages", "currently", "installed", "as", "a", "dict", "::" ]
python
train
bohea/sanic-limiter
sanic_limiter/extension.py
https://github.com/bohea/sanic-limiter/blob/54c9fc4a3a3f1a9bb69367262637d07701ae5694/sanic_limiter/extension.py#L116-L147
def init_app(self, app): """ :param app: :class:`sanic.Sanic` instance to rate limit. """ self.enabled = app.config.setdefault(C.ENABLED, True) self._swallow_errors = app.config.setdefault( C.SWALLOW_ERRORS, self._swallow_errors ) self._storage_options...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "enabled", "=", "app", ".", "config", ".", "setdefault", "(", "C", ".", "ENABLED", ",", "True", ")", "self", ".", "_swallow_errors", "=", "app", ".", "config", ".", "setdefault", "(",...
:param app: :class:`sanic.Sanic` instance to rate limit.
[ ":", "param", "app", ":", ":", "class", ":", "sanic", ".", "Sanic", "instance", "to", "rate", "limit", "." ]
python
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/alarms.py
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/alarms.py#L102-L138
def get_alarms(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usuall...
[ "def", "get_alarms", "(", "username", ",", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "\"/imcrs/fault/alarm?operatorName=\"", "+", "username", "+", "\"&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true\"", "response", "=", "requests", ".", "get", "(",...
Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class ...
[ "Takes", "in", "no", "param", "as", "input", "to", "fetch", "RealTime", "Alarms", "from", "HP", "IMC", "RESTFUL", "API" ]
python
train
materialsproject/pymatgen
pymatgen/optimization/linear_assignment_numpy.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/optimization/linear_assignment_numpy.py#L187-L244
def _build_tree(self): """ Builds the tree finding an augmenting path. Alternates along matched and unmatched edges between X and Y. The paths are stored in _pred (new predecessor of nodes in Y), and self._x and self._y """ #find unassigned i* istar = np.a...
[ "def", "_build_tree", "(", "self", ")", ":", "#find unassigned i*", "istar", "=", "np", ".", "argmin", "(", "self", ".", "_x", ")", "#compute distances", "self", ".", "_d", "=", "self", ".", "c", "[", "istar", "]", "-", "self", ".", "_v", "_pred", "=...
Builds the tree finding an augmenting path. Alternates along matched and unmatched edges between X and Y. The paths are stored in _pred (new predecessor of nodes in Y), and self._x and self._y
[ "Builds", "the", "tree", "finding", "an", "augmenting", "path", ".", "Alternates", "along", "matched", "and", "unmatched", "edges", "between", "X", "and", "Y", ".", "The", "paths", "are", "stored", "in", "_pred", "(", "new", "predecessor", "of", "nodes", "...
python
train
kata198/python-subprocess2
subprocess2/__init__.py
https://github.com/kata198/python-subprocess2/blob/8544b0b651d8e14de9fdd597baa704182e248b01/subprocess2/__init__.py#L63-L85
def waitUpTo(self, timeoutSeconds, pollInterval=DEFAULT_POLL_INTERVAL): ''' Popen.waitUpTo - Wait up to a certain number of seconds for the process to end. @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05) - Number of seconds in bet...
[ "def", "waitUpTo", "(", "self", ",", "timeoutSeconds", ",", "pollInterval", "=", "DEFAULT_POLL_INTERVAL", ")", ":", "i", "=", "0", "numWaits", "=", "timeoutSeconds", "/", "float", "(", "pollInterval", ")", "ret", "=", "self", ".", "poll", "(", ")", "if", ...
Popen.waitUpTo - Wait up to a certain number of seconds for the process to end. @param timeoutSeconds <float> - Number of seconds to wait @param pollInterval <float> (default .05) - Number of seconds in between each poll @return - Returncode of application, or None if did not term...
[ "Popen", ".", "waitUpTo", "-", "Wait", "up", "to", "a", "certain", "number", "of", "seconds", "for", "the", "process", "to", "end", "." ]
python
train
Azure/azure-storage-python
azure-storage-queue/azure/storage/queue/queueservice.py
https://github.com/Azure/azure-storage-python/blob/52327354b192cbcf6b7905118ec6b5d57fa46275/azure-storage-queue/azure/storage/queue/queueservice.py#L894-L929
def delete_message(self, queue_name, message_id, pop_receipt, timeout=None): ''' Deletes the specified message. Normally after a client retrieves a message with the get_messages operation, the client is expected to process and delete the message. To delete the message, you mus...
[ "def", "delete_message", "(", "self", ",", "queue_name", ",", "message_id", ",", "pop_receipt", ",", "timeout", "=", "None", ")", ":", "_validate_not_none", "(", "'queue_name'", ",", "queue_name", ")", "_validate_not_none", "(", "'message_id'", ",", "message_id", ...
Deletes the specified message. Normally after a client retrieves a message with the get_messages operation, the client is expected to process and delete the message. To delete the message, you must have two items of data: id and pop_receipt. The id is returned from the previous get_m...
[ "Deletes", "the", "specified", "message", "." ]
python
train
houtianze/bypy
bypy/bypy.py
https://github.com/houtianze/bypy/blob/c59b6183e2fca45f11138bbcdec6247449b2eaad/bypy/bypy.py#L2922-L2937
def cleancache(self): ''' Usage: cleancache - remove invalid entries from hash cache file''' if os.path.exists(self.__hashcachepath): try: # backup first backup = self.__hashcachepath + '.lastclean' shutil.copy(self.__hashcachepath, backup) self.pd("Hash Cache file '{}' backed up as '{}".format( ...
[ "def", "cleancache", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "__hashcachepath", ")", ":", "try", ":", "# backup first", "backup", "=", "self", ".", "__hashcachepath", "+", "'.lastclean'", "shutil", ".", "copy", "(...
Usage: cleancache - remove invalid entries from hash cache file
[ "Usage", ":", "cleancache", "-", "remove", "invalid", "entries", "from", "hash", "cache", "file" ]
python
train
klmitch/bark
bark/format.py
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L381-L393
def append_text(self, text): """ Append static text to the Format. :param text: The text to append. """ if (self.conversions and isinstance(self.conversions[-1], conversions.StringConversion)): self.conversions[-1].append(t...
[ "def", "append_text", "(", "self", ",", "text", ")", ":", "if", "(", "self", ".", "conversions", "and", "isinstance", "(", "self", ".", "conversions", "[", "-", "1", "]", ",", "conversions", ".", "StringConversion", ")", ")", ":", "self", ".", "convers...
Append static text to the Format. :param text: The text to append.
[ "Append", "static", "text", "to", "the", "Format", "." ]
python
train
inveniosoftware-attic/invenio-utils
invenio_utils/filedownload.py
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/filedownload.py#L253-L295
def download_local_file(filename, download_to_file): """ Copies a local file to Invenio's temporary directory. @param filename: the name of the file to copy @type filename: string @param download_to_file: the path to save the file to @type download_to_file: string @return: the path of the...
[ "def", "download_local_file", "(", "filename", ",", "download_to_file", ")", ":", "# Try to copy.", "try", ":", "path", "=", "urllib2", ".", "urlparse", ".", "urlsplit", "(", "urllib", ".", "unquote", "(", "filename", ")", ")", "[", "2", "]", "if", "os", ...
Copies a local file to Invenio's temporary directory. @param filename: the name of the file to copy @type filename: string @param download_to_file: the path to save the file to @type download_to_file: string @return: the path of the temporary file created @rtype: string @raise StandardErr...
[ "Copies", "a", "local", "file", "to", "Invenio", "s", "temporary", "directory", "." ]
python
train
pip-services3-python/pip-services3-components-python
pip_services3_components/log/CachedLogger.py
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/log/CachedLogger.py#L55-L77
def _write(self, level, correlation_id, ex, message): """ Writes a log message to the logger destination. :param level: a log level. :param correlation_id: (optional) transaction id to trace execution through call chain. :param ex: an error object associated with this message....
[ "def", "_write", "(", "self", ",", "level", ",", "correlation_id", ",", "ex", ",", "message", ")", ":", "error", "=", "ErrorDescriptionFactory", ".", "create", "(", "ex", ")", "if", "ex", "!=", "None", "else", "None", "source", "=", "socket", ".", "get...
Writes a log message to the logger destination. :param level: a log level. :param correlation_id: (optional) transaction id to trace execution through call chain. :param ex: an error object associated with this message. :param message: a human-readable message to log.
[ "Writes", "a", "log", "message", "to", "the", "logger", "destination", "." ]
python
train
SKA-ScienceDataProcessor/integration-prototype
sip/execution_control/docker_api/sip_docker_swarm/docker_swarm_client.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/docker_api/sip_docker_swarm/docker_swarm_client.py#L310-L330
def get_node_list(self) -> list: """Get a list of nodes. Only the manager nodes can retrieve all the nodes Returns: list, all the ids of the nodes in swarm """ # Initialising empty list nodes = [] # Raise an exception if we are not a manager ...
[ "def", "get_node_list", "(", "self", ")", "->", "list", ":", "# Initialising empty list", "nodes", "=", "[", "]", "# Raise an exception if we are not a manager", "if", "not", "self", ".", "_manager", ":", "raise", "RuntimeError", "(", "'Only the Swarm manager node '", ...
Get a list of nodes. Only the manager nodes can retrieve all the nodes Returns: list, all the ids of the nodes in swarm
[ "Get", "a", "list", "of", "nodes", "." ]
python
train
expfactory/expfactory
expfactory/database/filesystem.py
https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/database/filesystem.py#L188-L199
def validate_token(self, token): '''retrieve a subject based on a token. Valid means we return a participant invalid means we return None ''' # A token that is finished or revoked is not valid subid = None if not token.endswith(('finished','revoked')): subid = self.generate_subid(toke...
[ "def", "validate_token", "(", "self", ",", "token", ")", ":", "# A token that is finished or revoked is not valid", "subid", "=", "None", "if", "not", "token", ".", "endswith", "(", "(", "'finished'", ",", "'revoked'", ")", ")", ":", "subid", "=", "self", ".",...
retrieve a subject based on a token. Valid means we return a participant invalid means we return None
[ "retrieve", "a", "subject", "based", "on", "a", "token", ".", "Valid", "means", "we", "return", "a", "participant", "invalid", "means", "we", "return", "None" ]
python
train
klen/starter
starter/core.py
https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L42-L50
def make_directory(path): """ Create directory if that not exists. """ try: makedirs(path) logging.debug('Directory created: {0}'.format(path)) except OSError as e: if e.errno != errno.EEXIST: raise
[ "def", "make_directory", "(", "path", ")", ":", "try", ":", "makedirs", "(", "path", ")", "logging", ".", "debug", "(", "'Directory created: {0}'", ".", "format", "(", "path", ")", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!="...
Create directory if that not exists.
[ "Create", "directory", "if", "that", "not", "exists", "." ]
python
train
scheibler/khard
khard/khard.py
https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/khard.py#L921-L982
def phone_subcommand(search_terms, vcard_list, parsable): """Print a phone application friendly contact table. :param search_terms: used as search term to filter the contacts before printing :type search_terms: str :param vcard_list: the vcards to search for matching entries which should ...
[ "def", "phone_subcommand", "(", "search_terms", ",", "vcard_list", ",", "parsable", ")", ":", "all_phone_numbers_list", "=", "[", "]", "matching_phone_number_list", "=", "[", "]", "for", "vcard", "in", "vcard_list", ":", "for", "type", ",", "number_list", "in", ...
Print a phone application friendly contact table. :param search_terms: used as search term to filter the contacts before printing :type search_terms: str :param vcard_list: the vcards to search for matching entries which should be printed :type vcard_list: list of carddav_object.Carddav...
[ "Print", "a", "phone", "application", "friendly", "contact", "table", "." ]
python
test
streamlink/streamlink
src/streamlink_cli/main.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink_cli/main.py#L504-L534
def format_valid_streams(plugin, streams): """Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight). """ delimiter = ", " validstreams = [] for name, strea...
[ "def", "format_valid_streams", "(", "plugin", ",", "streams", ")", ":", "delimiter", "=", "\", \"", "validstreams", "=", "[", "]", "for", "name", ",", "stream", "in", "sorted", "(", "streams", ".", "items", "(", ")", ",", "key", "=", "lambda", "stream", ...
Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight).
[ "Formats", "a", "dict", "of", "streams", "." ]
python
test
DarkEnergySurvey/ugali
ugali/isochrone/model.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L389-L444
def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None): """ Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits ...
[ "def", "absolute_magnitude_martin", "(", "self", ",", "richness", "=", "1", ",", "steps", "=", "1e4", ",", "n_trials", "=", "1000", ",", "mag_bright", "=", "None", ",", "mag_faint", "=", "23.", ",", "alpha", "=", "0.32", ",", "seed", "=", "None", ")", ...
Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits should depend on the survey maglim? Parameters: ----------- richness : Isochrone nomalization factor steps : N...
[ "Calculate", "the", "absolute", "magnitude", "(", "Mv", ")", "of", "the", "isochrone", "using", "the", "prescription", "of", "Martin", "et", "al", ".", "2008", ".", "ADW", ":", "Seems", "like", "the", "faint", "and", "bright", "limits", "should", "depend",...
python
train
ambitioninc/rabbitmq-admin
rabbitmq_admin/api.py
https://github.com/ambitioninc/rabbitmq-admin/blob/ff65054115f19991da153f0e4f4e45e526545fea/rabbitmq_admin/api.py#L476-L488
def get_policy_for_vhost(self, vhost, name): """ Get a specific policy for a vhost. :param vhost: The virtual host the policy is for :type vhost: str :param name: The name of the policy :type name: str """ return self._api_get('/api/policies/{0}/{1}'.form...
[ "def", "get_policy_for_vhost", "(", "self", ",", "vhost", ",", "name", ")", ":", "return", "self", ".", "_api_get", "(", "'/api/policies/{0}/{1}'", ".", "format", "(", "urllib", ".", "parse", ".", "quote_plus", "(", "vhost", ")", ",", "urllib", ".", "parse...
Get a specific policy for a vhost. :param vhost: The virtual host the policy is for :type vhost: str :param name: The name of the policy :type name: str
[ "Get", "a", "specific", "policy", "for", "a", "vhost", "." ]
python
train
senaite/senaite.core
bika/lims/browser/analysisservice.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analysisservice.py#L131-L140
def analysis_log_view(self): """Get the log view of the requested analysis """ service = self.get_analysis_or_service() if not self.can_view_logs_of(service): return None view = api.get_view("auditlog", context=service, request=self.request) view.update() ...
[ "def", "analysis_log_view", "(", "self", ")", ":", "service", "=", "self", ".", "get_analysis_or_service", "(", ")", "if", "not", "self", ".", "can_view_logs_of", "(", "service", ")", ":", "return", "None", "view", "=", "api", ".", "get_view", "(", "\"audi...
Get the log view of the requested analysis
[ "Get", "the", "log", "view", "of", "the", "requested", "analysis" ]
python
train
alimanfoo/csvvalidator
csvvalidator.py
https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L591-L629
def _apply_value_predicates(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None): """Apply value predicates on the given record `r`.""" for field_name, predicate, code, message, modu...
[ "def", "_apply_value_predicates", "(", "self", ",", "i", ",", "r", ",", "summarize", "=", "False", ",", "report_unexpected_exceptions", "=", "True", ",", "context", "=", "None", ")", ":", "for", "field_name", ",", "predicate", ",", "code", ",", "message", ...
Apply value predicates on the given record `r`.
[ "Apply", "value", "predicates", "on", "the", "given", "record", "r", "." ]
python
valid