repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
allenai/allennlp
allennlp/common/util.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L83-L95
def group_by_count(iterable: List[Any], count: int, default_value: Any) -> List[List[Any]]: """ Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the list at the end if the list is not divisable by ``count``. For example: >>> group_by_count([1, 2, 3, 4, 5, 6...
[ "def", "group_by_count", "(", "iterable", ":", "List", "[", "Any", "]", ",", "count", ":", "int", ",", "default_value", ":", "Any", ")", "->", "List", "[", "List", "[", "Any", "]", "]", ":", "return", "[", "list", "(", "l", ")", "for", "l", "in",...
Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the list at the end if the list is not divisable by ``count``. For example: >>> group_by_count([1, 2, 3, 4, 5, 6, 7], 3, 0) [[1, 2, 3], [4, 5, 6], [7, 0, 0]] This is a short method, but it's complicated and ...
[ "Takes", "a", "list", "and", "groups", "it", "into", "sublists", "of", "size", "count", "using", "default_value", "to", "pad", "the", "list", "at", "the", "end", "if", "the", "list", "is", "not", "divisable", "by", "count", "." ]
python
train
45.230769
raiden-network/raiden
raiden/tasks.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L224-L269
def _maybe_run_callbacks(self, latest_block): """ Run the callbacks if there is at least one new block. The callbacks are executed only if there is a new block, otherwise the filters may try to poll for an inexisting block number and the Ethereum client can return an JSON-RPC error. ...
[ "def", "_maybe_run_callbacks", "(", "self", ",", "latest_block", ")", ":", "assert", "self", ".", "known_block_number", "is", "not", "None", ",", "'known_block_number not set'", "latest_block_number", "=", "latest_block", "[", "'number'", "]", "missed_blocks", "=", ...
Run the callbacks if there is at least one new block. The callbacks are executed only if there is a new block, otherwise the filters may try to poll for an inexisting block number and the Ethereum client can return an JSON-RPC error.
[ "Run", "the", "callbacks", "if", "there", "is", "at", "least", "one", "new", "block", "." ]
python
train
38.347826
caseyjlaw/activegit
activegit/activegit.py
https://github.com/caseyjlaw/activegit/blob/2b4a0ee0fecf13345b5257130ba98b48f46e1098/activegit/activegit.py#L183-L187
def write_classifier(self, clf): """ Writes classifier object to pickle file """ with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp: pickle.dump(clf, fp)
[ "def", "write_classifier", "(", "self", ",", "clf", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "repopath", ",", "'classifier.pkl'", ")", ",", "'w'", ")", "as", "fp", ":", "pickle", ".", "dump", "(", "clf", ",",...
Writes classifier object to pickle file
[ "Writes", "classifier", "object", "to", "pickle", "file" ]
python
train
39
bcbio/bcbio-nextgen
bcbio/bam/__init__.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L282-L315
def _check_bam_contigs(in_bam, ref_file, config): """Ensure a pre-aligned BAM file matches the expected reference genome. """ # GATK allows chromosome M to be in multiple locations, skip checking it allowed_outoforder = ["chrM", "MT"] ref_contigs = [c.name for c in ref.file_contigs(ref_file, config)...
[ "def", "_check_bam_contigs", "(", "in_bam", ",", "ref_file", ",", "config", ")", ":", "# GATK allows chromosome M to be in multiple locations, skip checking it", "allowed_outoforder", "=", "[", "\"chrM\"", ",", "\"MT\"", "]", "ref_contigs", "=", "[", "c", ".", "name", ...
Ensure a pre-aligned BAM file matches the expected reference genome.
[ "Ensure", "a", "pre", "-", "aligned", "BAM", "file", "matches", "the", "expected", "reference", "genome", "." ]
python
train
54.588235
obulpathi/cdn-fastly-python
fastly/__init__.py
https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L235-L238
def delete_cache_settings(self, service_id, version_number, name): """Delete a specific cache settings object.""" content = self._fetch("/service/%s/version/%d/cache_settings/%s" % (service_id, version_number, name), method="DELETE") return self._status(content)
[ "def", "delete_cache_settings", "(", "self", ",", "service_id", ",", "version_number", ",", "name", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/cache_settings/%s\"", "%", "(", "service_id", ",", "version_number", ",", "name", ")...
Delete a specific cache settings object.
[ "Delete", "a", "specific", "cache", "settings", "object", "." ]
python
train
66.25
Accelize/pycosio
pycosio/_core/functions_os.py
https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L292-L319
def is_dir(self, follow_symlinks=True): """ Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. ...
[ "def", "is_dir", "(", "self", ",", "follow_symlinks", "=", "True", ")", ":", "try", ":", "return", "(", "self", ".", "_system", ".", "isdir", "(", "path", "=", "self", ".", "_path", ",", "client_kwargs", "=", "self", ".", "_client_kwargs", ",", "virtua...
Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. Args: follow_symlinks (bool): Follow symlin...
[ "Return", "True", "if", "this", "entry", "is", "a", "directory", "or", "a", "symbolic", "link", "pointing", "to", "a", "directory", ";", "return", "False", "if", "the", "entry", "is", "or", "points", "to", "any", "other", "kind", "of", "file", "or", "i...
python
train
34.857143
dadadel/pyment
pyment/docstring.py
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1702-L1709
def _set_other(self): """Sets other specific sections""" # manage not setting if not mandatory for numpy if self.dst.style['in'] == 'numpydoc': if self.docs['in']['raw'] is not None: self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw...
[ "def", "_set_other", "(", "self", ")", ":", "# manage not setting if not mandatory for numpy", "if", "self", ".", "dst", ".", "style", "[", "'in'", "]", "==", "'numpydoc'", ":", "if", "self", ".", "docs", "[", "'in'", "]", "[", "'raw'", "]", "is", "not", ...
Sets other specific sections
[ "Sets", "other", "specific", "sections" ]
python
train
55.875
VIVelev/PyDojoML
dojo/statistics.py
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/statistics.py#L57-L80
def calculate_between_class_scatter_matrix(X, y): """Calculates the Between-Class Scatter matrix Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- between_class_scatter_matrix : array-like, shape (n, ...
[ "def", "calculate_between_class_scatter_matrix", "(", "X", ",", "y", ")", ":", "mean_vectors", "=", "calculate_mean_vectors", "(", "X", ",", "y", ")", "n_features", "=", "X", ".", "shape", "[", "1", "]", "Sb", "=", "np", ".", "zeros", "(", "(", "n_featur...
Calculates the Between-Class Scatter matrix Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- between_class_scatter_matrix : array-like, shape (n, n)
[ "Calculates", "the", "Between", "-", "Class", "Scatter", "matrix", "Parameters", ":", "-----------", "X", ":", "array", "-", "like", "shape", "(", "m", "n", ")", "-", "the", "samples", "y", ":", "array", "-", "like", "shape", "(", "m", ")", "-", "the...
python
train
26.708333
williamgilpin/pypdb
pypdb/pypdb.py
https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L531-L576
def get_blast2(pdb_id, chain_id='A', output_form='HTML'): '''Alternative way to look up BLAST for a given PDB ID. This function is a wrapper for get_raw_blast and parse_blast Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest chain_id : string ...
[ "def", "get_blast2", "(", "pdb_id", ",", "chain_id", "=", "'A'", ",", "output_form", "=", "'HTML'", ")", ":", "raw_results", "=", "get_raw_blast", "(", "pdb_id", ",", "chain_id", "=", "chain_id", ",", "output_form", "=", "output_form", ")", "out", "=", "pa...
Alternative way to look up BLAST for a given PDB ID. This function is a wrapper for get_raw_blast and parse_blast Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest chain_id : string A single character designating the chain ID of interest ...
[ "Alternative", "way", "to", "look", "up", "BLAST", "for", "a", "given", "PDB", "ID", ".", "This", "function", "is", "a", "wrapper", "for", "get_raw_blast", "and", "parse_blast" ]
python
train
31.347826
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7297-L7301
def setContextNode(self, node): """Set the current node of an xpathContext """ if node is None: node__o = None else: node__o = node._o libxml2mod.xmlXPathSetContextNode(self._o, node__o)
[ "def", "setContextNode", "(", "self", ",", "node", ")", ":", "if", "node", "is", "None", ":", "node__o", "=", "None", "else", ":", "node__o", "=", "node", ".", "_o", "libxml2mod", ".", "xmlXPathSetContextNode", "(", "self", ".", "_o", ",", "node__o", "...
Set the current node of an xpathContext
[ "Set", "the", "current", "node", "of", "an", "xpathContext" ]
python
train
42.8
brews/snakebacon
snakebacon/utils.py
https://github.com/brews/snakebacon/blob/f5363d0d1225912adc30031bf2c13b54000de8f2/snakebacon/utils.py#L5-L15
def suggest_accumulation_rate(chron): """From core age-depth data, suggest mean accumulation rate (cm/y) """ # Follow's Bacon's method @ Bacon.R ln 30 - 44 # Suggested round vals. sugg = np.tile([1, 2, 5], (4, 1)) * np.reshape(np.repeat([0.1, 1.0, 10, 100], 3), (4, 3)) # Get ballpark accumulatio...
[ "def", "suggest_accumulation_rate", "(", "chron", ")", ":", "# Follow's Bacon's method @ Bacon.R ln 30 - 44", "# Suggested round vals.", "sugg", "=", "np", ".", "tile", "(", "[", "1", ",", "2", ",", "5", "]", ",", "(", "4", ",", "1", ")", ")", "*", "np", "...
From core age-depth data, suggest mean accumulation rate (cm/y)
[ "From", "core", "age", "-", "depth", "data", "suggest", "mean", "accumulation", "rate", "(", "cm", "/", "y", ")" ]
python
train
50.454545
eamigo86/graphene-django-extras
graphene_django_extras/directives/date.py
https://github.com/eamigo86/graphene-django-extras/blob/b27fd6b5128f6b6a500a8b7a497d76be72d6a232/graphene_django_extras/directives/date.py#L73-L94
def _parse(partial_dt): """ parse a partial datetime object to a complete datetime object """ dt = None try: if isinstance(partial_dt, datetime): dt = partial_dt if isinstance(partial_dt, date): dt = _combine_date_time(partial_dt, time(0, 0, 0)) if isi...
[ "def", "_parse", "(", "partial_dt", ")", ":", "dt", "=", "None", "try", ":", "if", "isinstance", "(", "partial_dt", ",", "datetime", ")", ":", "dt", "=", "partial_dt", "if", "isinstance", "(", "partial_dt", ",", "date", ")", ":", "dt", "=", "_combine_d...
parse a partial datetime object to a complete datetime object
[ "parse", "a", "partial", "datetime", "object", "to", "a", "complete", "datetime", "object" ]
python
train
34.5
htm-community/menorah
menorah/riverstream.py
https://github.com/htm-community/menorah/blob/1991b01eda3f6361b22ed165b4a688ae3fb2deaf/menorah/riverstream.py#L124-L154
def advance(self, myDateTime): """ Advances to the next value and returns an appropriate value for the given time. :param myDateTime: (datetime) when to fetch the value for :return: (float|int) value for given time """ if self.getTime() == myDateTime: out = self.next() # Someti...
[ "def", "advance", "(", "self", ",", "myDateTime", ")", ":", "if", "self", ".", "getTime", "(", ")", "==", "myDateTime", ":", "out", "=", "self", ".", "next", "(", ")", "# Sometimes, the stream has no value for this field and returns None, in ", "# this case we'll us...
Advances to the next value and returns an appropriate value for the given time. :param myDateTime: (datetime) when to fetch the value for :return: (float|int) value for given time
[ "Advances", "to", "the", "next", "value", "and", "returns", "an", "appropriate", "value", "for", "the", "given", "time", ".", ":", "param", "myDateTime", ":", "(", "datetime", ")", "when", "to", "fetch", "the", "value", "for", ":", "return", ":", "(", ...
python
train
26.870968
wiheto/teneto
teneto/classes/bids.py
https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L1433-L1443
def set_pipeline(self, pipeline): """ Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string. """ self.add_history(inspect.stack()[0][3], locals(), 1) if not os.path.exists(self.BIDS_dir + '/derivatives/' + pipeline): p...
[ "def", "set_pipeline", "(", "self", ",", "pipeline", ")", ":", "self", ".", "add_history", "(", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ",", "locals", "(", ")", ",", "1", ")", "if", "not", "os", ".", "path", ".", "exist...
Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string.
[ "Specify", "the", "pipeline", ".", "See", "get_pipeline_alternatives", "to", "see", "what", "are", "avaialble", ".", "Input", "should", "be", "a", "string", "." ]
python
train
46.545455
dourvaris/nano-python
src/nano/rpc.py
https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L2408-L2429
def wallet_export(self, wallet): """ Return a json representation of **wallet** :param wallet: Wallet to export :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_export(wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F") ...
[ "def", "wallet_export", "(", "self", ",", "wallet", ")", ":", "wallet", "=", "self", ".", "_process_value", "(", "wallet", ",", "'wallet'", ")", "payload", "=", "{", "\"wallet\"", ":", "wallet", "}", "resp", "=", "self", ".", "call", "(", "'wallet_export...
Return a json representation of **wallet** :param wallet: Wallet to export :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_export(wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F") { "0000000000000000000000000000000...
[ "Return", "a", "json", "representation", "of", "**", "wallet", "**" ]
python
train
30.136364
MichaelAquilina/hashedindex
hashedindex/textparser.py
https://github.com/MichaelAquilina/hashedindex/blob/5a84dcd6c697ea04162cf7b2683fa2723845b51c/hashedindex/textparser.py#L67-L89
def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True): """ Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character. """ if ngrams is None: ngrams = 1 ...
[ "def", "word_tokenize", "(", "text", ",", "stopwords", "=", "_stopwords", ",", "ngrams", "=", "None", ",", "min_length", "=", "0", ",", "ignore_numeric", "=", "True", ")", ":", "if", "ngrams", "is", "None", ":", "ngrams", "=", "1", "text", "=", "re", ...
Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character.
[ "Parses", "the", "given", "text", "and", "yields", "tokens", "which", "represent", "words", "within", "the", "given", "text", ".", "Tokens", "are", "assumed", "to", "be", "divided", "by", "any", "form", "of", "whitespace", "character", "." ]
python
train
36.043478
draios/python-sdc-client
sdcclient/_secure.py
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L836-L847
def delete_compliance_task(self, id): '''**Description** Delete the compliance task with the given id **Arguments** - id: the id of the compliance task to delete ''' res = requests.delete(self.url + '/api/complianceTasks/{}'.format(id), headers=self.hdrs, verify=...
[ "def", "delete_compliance_task", "(", "self", ",", "id", ")", ":", "res", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "'/api/complianceTasks/{}'", ".", "format", "(", "id", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", ...
**Description** Delete the compliance task with the given id **Arguments** - id: the id of the compliance task to delete
[ "**", "Description", "**", "Delete", "the", "compliance", "task", "with", "the", "given", "id" ]
python
test
36
fracpete/python-weka-wrapper3
python/weka/clusterers.py
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L297-L308
def cluster_assignments(self): """ Return an array of cluster assignments corresponding to the most recent set of instances clustered. :return: the cluster assignments :rtype: ndarray """ array = javabridge.call(self.jobject, "getClusterAssignments", "()[D") if a...
[ "def", "cluster_assignments", "(", "self", ")", ":", "array", "=", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"getClusterAssignments\"", ",", "\"()[D\"", ")", "if", "array", "is", "None", ":", "return", "None", "else", ":", "return", "j...
Return an array of cluster assignments corresponding to the most recent set of instances clustered. :return: the cluster assignments :rtype: ndarray
[ "Return", "an", "array", "of", "cluster", "assignments", "corresponding", "to", "the", "most", "recent", "set", "of", "instances", "clustered", "." ]
python
train
36.083333
titusjan/argos
argos/application.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L191-L197
def deleteProfile(self, profile): """ Removes a profile from the persistent settings """ profGroupName = self.profileGroupName(profile) logger.debug("Resetting profile settings: {}".format(profGroupName)) settings = QtCore.QSettings() settings.remove(profGroupName)
[ "def", "deleteProfile", "(", "self", ",", "profile", ")", ":", "profGroupName", "=", "self", ".", "profileGroupName", "(", "profile", ")", "logger", ".", "debug", "(", "\"Resetting profile settings: {}\"", ".", "format", "(", "profGroupName", ")", ")", "settings...
Removes a profile from the persistent settings
[ "Removes", "a", "profile", "from", "the", "persistent", "settings" ]
python
train
43.857143
allenai/allennlp
allennlp/semparse/domain_languages/nlvr_language.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L275-L284
def same_color(self, objects: Set[Object]) -> Set[Object]: """ Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual na...
[ "def", "same_color", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "return", "self", ".", "_get_objects_with_same_attribute", "(", "objects", ",", "lambda", "x", ":", "x", ".", "color", ")" ]
Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual name for what the method does, but just as ``blue`` filters objects to th...
[ "Filters", "the", "set", "of", "objects", "and", "returns", "those", "objects", "whose", "color", "is", "the", "most", "frequent", "color", "in", "the", "initial", "set", "of", "objects", "if", "the", "highest", "frequency", "is", "greater", "than", "1", "...
python
train
55.9
ECESeniorDesign/lazy_record
lazy_record/query.py
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/query.py#L298-L347
def append(self, record): """ Adds the passed +record+ to satisfy the query. Only intended to be used in conjunction with associations (i.e. do not use if self.record is None). Intended use case (DO THIS): post.comments.append(comment) NOT THIS: Query(...
[ "def", "append", "(", "self", ",", "record", ")", ":", "if", "self", ".", "record", ":", "self", ".", "_validate_record", "(", "record", ")", "if", "self", ".", "join_args", ":", "# As always, the related record is created when the primary", "# record is saved", "...
Adds the passed +record+ to satisfy the query. Only intended to be used in conjunction with associations (i.e. do not use if self.record is None). Intended use case (DO THIS): post.comments.append(comment) NOT THIS: Query(Post).where(content="foo").append(post)
[ "Adds", "the", "passed", "+", "record", "+", "to", "satisfy", "the", "query", ".", "Only", "intended", "to", "be", "used", "in", "conjunction", "with", "associations", "(", "i", ".", "e", ".", "do", "not", "use", "if", "self", ".", "record", "is", "N...
python
train
46.36
boriel/zxbasic
zxbparser.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L895-L901
def p_statement_draw3_attr(p): """ statement : DRAW attr_list expr COMMA expr COMMA expr """ p[0] = make_sentence('DRAW3', make_typecast(TYPE.integer, p[3], p.lineno(4)), make_typecast(TYPE.integer, p[5], p.lineno(6)), make_typecast(...
[ "def", "p_statement_draw3_attr", "(", "p", ")", ":", "p", "[", "0", "]", "=", "make_sentence", "(", "'DRAW3'", ",", "make_typecast", "(", "TYPE", ".", "integer", ",", "p", "[", "3", "]", ",", "p", ".", "lineno", "(", "4", ")", ")", ",", "make_typec...
statement : DRAW attr_list expr COMMA expr COMMA expr
[ "statement", ":", "DRAW", "attr_list", "expr", "COMMA", "expr", "COMMA", "expr" ]
python
train
50.285714
Spinmob/spinmob
_pylab_colormap.py
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_colormap.py#L98-L120
def save_colormap(self, name=None): """ Saves the colormap with the specified name. None means use internal name. (See get_name()) """ if name == None: name = self.get_name() if name == "" or not type(name)==str: return "Error: invalid name." # get the colormaps ...
[ "def", "save_colormap", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "==", "None", ":", "name", "=", "self", ".", "get_name", "(", ")", "if", "name", "==", "\"\"", "or", "not", "type", "(", "name", ")", "==", "str", ":", "return...
Saves the colormap with the specified name. None means use internal name. (See get_name())
[ "Saves", "the", "colormap", "with", "the", "specified", "name", ".", "None", "means", "use", "internal", "name", ".", "(", "See", "get_name", "()", ")" ]
python
train
32.043478
steffann/pylisp
pylisp/packet/lisp/control/encapsulated_control_message.py
https://github.com/steffann/pylisp/blob/907340f0c7ef2c4d4fe0c8e0a48df5be0d969407/pylisp/packet/lisp/control/encapsulated_control_message.py#L35-L70
def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix them where possible. ''' super(EncapsulatedControlMessage, self).sanitize() # S: This is the Security bit. When set to 1 the following # authentication information w...
[ "def", "sanitize", "(", "self", ")", ":", "super", "(", "EncapsulatedControlMessage", ",", "self", ")", ".", "sanitize", "(", ")", "# S: This is the Security bit. When set to 1 the following", "# authentication information will be appended to the end of the Map-", "# Reply. The...
Check if the current settings conform to the LISP specifications and fix them where possible.
[ "Check", "if", "the", "current", "settings", "conform", "to", "the", "LISP", "specifications", "and", "fix", "them", "where", "possible", "." ]
python
train
46.611111
DataBiosphere/toil
src/toil/batchSystems/mesos/executor.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/mesos/executor.py#L69-L81
def registered(self, driver, executorInfo, frameworkInfo, agentInfo): """ Invoked once the executor driver has been able to successfully connect with Mesos. """ # Get the ID we have been assigned, if we have it self.id = executorInfo.executor_id.get('value', None) ...
[ "def", "registered", "(", "self", ",", "driver", ",", "executorInfo", ",", "frameworkInfo", ",", "agentInfo", ")", ":", "# Get the ID we have been assigned, if we have it", "self", ".", "id", "=", "executorInfo", ".", "executor_id", ".", "get", "(", "'value'", ","...
Invoked once the executor driver has been able to successfully connect with Mesos.
[ "Invoked", "once", "the", "executor", "driver", "has", "been", "able", "to", "successfully", "connect", "with", "Mesos", "." ]
python
train
46.307692
markovmodel/PyEMMA
pyemma/datasets/api.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/api.py#L57-L86
def get_umbrella_sampling_data(ntherm=11, us_fc=20.0, us_length=500, md_length=1000, nmd=20): """ Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, opt...
[ "def", "get_umbrella_sampling_data", "(", "ntherm", "=", "11", ",", "us_fc", "=", "20.0", ",", "us_length", "=", "500", ",", "md_length", "=", "1000", ",", "nmd", "=", "20", ")", ":", "dws", "=", "_DWS", "(", ")", "us_data", "=", "dws", ".", "us_samp...
Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, optional, default=20.0 Force constant in kT/length^2 for each umbrella. us_length: int, optional,...
[ "Continuous", "MCMC", "process", "in", "an", "asymmetric", "double", "well", "potential", "using", "umbrella", "sampling", "." ]
python
train
42.233333
openpaperwork/paperwork-backend
paperwork_backend/index.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/index.py#L495-L504
def get(self, obj_id): """ Get a document or a page using its ID Won't instantiate them if they are not yet available """ if BasicPage.PAGE_ID_SEPARATOR in obj_id: (docid, page_nb) = obj_id.split(BasicPage.PAGE_ID_SEPARATOR) page_nb = int(page_nb) ...
[ "def", "get", "(", "self", ",", "obj_id", ")", ":", "if", "BasicPage", ".", "PAGE_ID_SEPARATOR", "in", "obj_id", ":", "(", "docid", ",", "page_nb", ")", "=", "obj_id", ".", "split", "(", "BasicPage", ".", "PAGE_ID_SEPARATOR", ")", "page_nb", "=", "int", ...
Get a document or a page using its ID Won't instantiate them if they are not yet available
[ "Get", "a", "document", "or", "a", "page", "using", "its", "ID", "Won", "t", "instantiate", "them", "if", "they", "are", "not", "yet", "available" ]
python
train
40
rochacbruno/dynaconf
dynaconf/loaders/__init__.py
https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/__init__.py#L15-L56
def default_loader(obj, defaults=None): """Loads default settings and check if there are overridings exported as environment variables""" defaults = defaults or {} default_settings_values = { key: value for key, value in default_settings.__dict__.items() # noqa if key.isupper() ...
[ "def", "default_loader", "(", "obj", ",", "defaults", "=", "None", ")", ":", "defaults", "=", "defaults", "or", "{", "}", "default_settings_values", "=", "{", "key", ":", "value", "for", "key", ",", "value", "in", "default_settings", ".", "__dict__", ".", ...
Loads default settings and check if there are overridings exported as environment variables
[ "Loads", "default", "settings", "and", "check", "if", "there", "are", "overridings", "exported", "as", "environment", "variables" ]
python
train
32.166667
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L209-L233
def __parse_enrollments(self, user): """Parse user enrollments""" enrollments = [] for company in user['companies']: name = company['company_name'] org = self._organizations.get(name, None) if not org: org = Organization(name=name) ...
[ "def", "__parse_enrollments", "(", "self", ",", "user", ")", ":", "enrollments", "=", "[", "]", "for", "company", "in", "user", "[", "'companies'", "]", ":", "name", "=", "company", "[", "'company_name'", "]", "org", "=", "self", ".", "_organizations", "...
Parse user enrollments
[ "Parse", "user", "enrollments" ]
python
train
27.6
commontk/ctk-cli
ctk_cli/module.py
https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/module.py#L134-L159
def classifyParameters(self): """Return (arguments, options, outputs) tuple. Together, the three lists contain all parameters (recursively fetched from all parameter groups), classified into optional parameters, required ones (with an index), and simple output parameters (that w...
[ "def", "classifyParameters", "(", "self", ")", ":", "arguments", "=", "[", "]", "options", "=", "[", "]", "outputs", "=", "[", "]", "for", "parameter", "in", "self", ".", "parameters", "(", ")", ":", "if", "parameter", ".", "channel", "==", "'output'",...
Return (arguments, options, outputs) tuple. Together, the three lists contain all parameters (recursively fetched from all parameter groups), classified into optional parameters, required ones (with an index), and simple output parameters (that would get written to a file using ...
[ "Return", "(", "arguments", "options", "outputs", ")", "tuple", ".", "Together", "the", "three", "lists", "contain", "all", "parameters", "(", "recursively", "fetched", "from", "all", "parameter", "groups", ")", "classified", "into", "optional", "parameters", "r...
python
train
51.615385
bitesofcode/projexui
projexui/widgets/xtablewidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtablewidget.py#L56-L67
def columnNameAt( self, index ): """ Returns the name of the column at the inputed index. :param index | <int> :return <str> """ columns = self.columns() if ( 0 <= index and index < len(columns) ): return columns[index] ...
[ "def", "columnNameAt", "(", "self", ",", "index", ")", ":", "columns", "=", "self", ".", "columns", "(", ")", "if", "(", "0", "<=", "index", "and", "index", "<", "len", "(", "columns", ")", ")", ":", "return", "columns", "[", "index", "]", "return"...
Returns the name of the column at the inputed index. :param index | <int> :return <str>
[ "Returns", "the", "name", "of", "the", "column", "at", "the", "inputed", "index", ".", ":", "param", "index", "|", "<int", ">", ":", "return", "<str", ">" ]
python
train
26.75
PMEAL/porespy
porespy/generators/__imgen__.py
https://github.com/PMEAL/porespy/blob/1e13875b56787d8f5b7ffdabce8c4342c33ba9f8/porespy/generators/__imgen__.py#L499-L574
def overlapping_spheres(shape: List[int], radius: int, porosity: float, iter_max: int = 10, tol: float = 0.01): r""" Generate a packing of overlapping mono-disperse spheres Parameters ---------- shape : list The size of the image to generate in [Nx, Ny, Nz] where Ni ...
[ "def", "overlapping_spheres", "(", "shape", ":", "List", "[", "int", "]", ",", "radius", ":", "int", ",", "porosity", ":", "float", ",", "iter_max", ":", "int", "=", "10", ",", "tol", ":", "float", "=", "0.01", ")", ":", "shape", "=", "sp", ".", ...
r""" Generate a packing of overlapping mono-disperse spheres Parameters ---------- shape : list The size of the image to generate in [Nx, Ny, Nz] where Ni is the number of voxels in the i-th direction. radius : scalar The radius of spheres in the packing. porosity : sc...
[ "r", "Generate", "a", "packing", "of", "overlapping", "mono", "-", "disperse", "spheres" ]
python
train
31.052632
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/schema.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L956-L964
def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a binary type? """ # Several binary types inherit internally from _Binary, making that the # easiest to check. coltype = _coltype_to_typeengine(coltype) # noinspection PyProtectedMemb...
[ "def", "is_sqlatype_binary", "(", "coltype", ":", "Union", "[", "TypeEngine", ",", "VisitableType", "]", ")", "->", "bool", ":", "# Several binary types inherit internally from _Binary, making that the", "# easiest to check.", "coltype", "=", "_coltype_to_typeengine", "(", ...
Is the SQLAlchemy column type a binary type?
[ "Is", "the", "SQLAlchemy", "column", "type", "a", "binary", "type?" ]
python
train
40.333333
moonso/ped_parser
ped_parser/parser.py
https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/parser.py#L205-L238
def ped_parser(self, family_info): """ Parse .ped formatted family info. Add all family info to the parser object Arguments: family_info (iterator): An iterator with family info """ for line in family_info: # Che...
[ "def", "ped_parser", "(", "self", ",", "family_info", ")", ":", "for", "line", "in", "family_info", ":", "# Check if commented line or empty line:", "if", "not", "line", ".", "startswith", "(", "'#'", ")", "and", "not", "all", "(", "c", "in", "whitespace", "...
Parse .ped formatted family info. Add all family info to the parser object Arguments: family_info (iterator): An iterator with family info
[ "Parse", ".", "ped", "formatted", "family", "info", ".", "Add", "all", "family", "info", "to", "the", "parser", "object", "Arguments", ":", "family_info", "(", "iterator", ")", ":", "An", "iterator", "with", "family", "info" ]
python
train
41.941176
gem/oq-engine
openquake/commonlib/writers.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L301-L333
def parse_header(header): """ Convert a list of the form `['fieldname:fieldtype:fieldsize',...]` into a numpy composite dtype. The parser understands headers generated by :func:`openquake.commonlib.writers.build_header`. Here is an example: >>> parse_header(['PGA:float32', 'PGV', 'avg:float32:2...
[ "def", "parse_header", "(", "header", ")", ":", "triples", "=", "[", "]", "fields", "=", "[", "]", "for", "col_str", "in", "header", ":", "col", "=", "col_str", ".", "strip", "(", ")", ".", "split", "(", "':'", ")", "n", "=", "len", "(", "col", ...
Convert a list of the form `['fieldname:fieldtype:fieldsize',...]` into a numpy composite dtype. The parser understands headers generated by :func:`openquake.commonlib.writers.build_header`. Here is an example: >>> parse_header(['PGA:float32', 'PGV', 'avg:float32:2']) (['PGA', 'PGV', 'avg'], dtype(...
[ "Convert", "a", "list", "of", "the", "form", "[", "fieldname", ":", "fieldtype", ":", "fieldsize", "...", "]", "into", "a", "numpy", "composite", "dtype", ".", "The", "parser", "understands", "headers", "generated", "by", ":", "func", ":", "openquake", "."...
python
train
38.212121
Chilipp/psyplot
psyplot/plotter.py
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L1298-L1369
def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False, draw=False, remove=False, priority=None): """ Initialize the plot for a data array Parameters ---------- data: InteractiveArray or ArrayList, optional Data object that ...
[ "def", "initialize_plot", "(", "self", ",", "data", "=", "None", ",", "ax", "=", "None", ",", "make_plot", "=", "True", ",", "clear", "=", "False", ",", "draw", "=", "False", ",", "remove", "=", "False", ",", "priority", "=", "None", ")", ":", "if"...
Initialize the plot for a data array Parameters ---------- data: InteractiveArray or ArrayList, optional Data object that shall be visualized. - If not None and `plot` is True, the given data is visualized. - If None and the :attr:`data` attribute is not Non...
[ "Initialize", "the", "plot", "for", "a", "data", "array" ]
python
train
39.958333
pvlib/pvlib-python
pvlib/pvsystem.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L1067-L1282
def calcparams_desoto(effective_irradiance, temp_cell, alpha_sc, a_ref, I_L_ref, I_o_ref, R_sh_ref, R_s, EgRef=1.121, dEgdT=-0.0002677, irrad_ref=1000, temp_ref=25): ''' Calculates five parameter values for the single diode equation at effect...
[ "def", "calcparams_desoto", "(", "effective_irradiance", ",", "temp_cell", ",", "alpha_sc", ",", "a_ref", ",", "I_L_ref", ",", "I_o_ref", ",", "R_sh_ref", ",", "R_s", ",", "EgRef", "=", "1.121", ",", "dEgdT", "=", "-", "0.0002677", ",", "irrad_ref", "=", "...
Calculates five parameter values for the single diode equation at effective irradiance and cell temperature using the De Soto et al. model described in [1]. The five values returned by calcparams_desoto can be used by singlediode to calculate an IV curve. Parameters ---------- effective_irradia...
[ "Calculates", "five", "parameter", "values", "for", "the", "single", "diode", "equation", "at", "effective", "irradiance", "and", "cell", "temperature", "using", "the", "De", "Soto", "et", "al", ".", "model", "described", "in", "[", "1", "]", ".", "The", "...
python
train
36.314815
icgood/pymap
pymap/backend/mailbox.py
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L158-L168
async def update_flags(self, messages: Sequence[MessageT], flag_set: FrozenSet[Flag], mode: FlagOp) -> None: """Update the permanent flags of each messages. Args: messages: The message objects. flag_set: The set of flags for the update operation. ...
[ "async", "def", "update_flags", "(", "self", ",", "messages", ":", "Sequence", "[", "MessageT", "]", ",", "flag_set", ":", "FrozenSet", "[", "Flag", "]", ",", "mode", ":", "FlagOp", ")", "->", "None", ":", "..." ]
Update the permanent flags of each messages. Args: messages: The message objects. flag_set: The set of flags for the update operation. flag_op: The mode to change the flags.
[ "Update", "the", "permanent", "flags", "of", "each", "messages", "." ]
python
train
34.545455
intake/intake
intake/__init__.py
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/__init__.py#L57-L76
def output_notebook(inline=True, logo=False): """ Load the notebook extension Parameters ---------- inline : boolean (optional) Whether to inline JS code or load it from a CDN logo : boolean (optional) Whether to show the logo(s) """ try: import hvplot except...
[ "def", "output_notebook", "(", "inline", "=", "True", ",", "logo", "=", "False", ")", ":", "try", ":", "import", "hvplot", "except", "ImportError", ":", "raise", "ImportError", "(", "\"The intake plotting API requires hvplot.\"", "\"hvplot may be installed with:\\n\\n\"...
Load the notebook extension Parameters ---------- inline : boolean (optional) Whether to inline JS code or load it from a CDN logo : boolean (optional) Whether to show the logo(s)
[ "Load", "the", "notebook", "extension" ]
python
train
32.3
DarkEnergySurvey/ugali
ugali/utils/projector.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/projector.py#L399-L420
def dec2dms(dec): """ ADW: This should really be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. dec = float(dec) sign = np.copysign(1.0,dec) fdeg = np.abs(dec) deg = int(fdeg) fminute = (fdeg - deg)*MINUTE minute = int(fminute) ...
[ "def", "dec2dms", "(", "dec", ")", ":", "DEGREE", "=", "360.", "HOUR", "=", "24.", "MINUTE", "=", "60.", "SECOND", "=", "3600.", "dec", "=", "float", "(", "dec", ")", "sign", "=", "np", ".", "copysign", "(", "1.0", ",", "dec", ")", "fdeg", "=", ...
ADW: This should really be replaced by astropy
[ "ADW", ":", "This", "should", "really", "be", "replaced", "by", "astropy" ]
python
train
18.136364
pyviz/holoviews
holoviews/core/sheetcoords.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/sheetcoords.py#L404-L415
def positionlesscrop(self,x,y,sheet_coord_system): """ Return the correct slice for a weights/mask matrix at this ConnectionField's location on the sheet (i.e. for getting the correct submatrix of the weights or mask in case the unit is near the edge of the sheet). """ ...
[ "def", "positionlesscrop", "(", "self", ",", "x", ",", "y", ",", "sheet_coord_system", ")", ":", "slice_inds", "=", "self", ".", "findinputslice", "(", "sheet_coord_system", ".", "sheet2matrixidx", "(", "x", ",", "y", ")", ",", "self", ".", "shape_on_sheet",...
Return the correct slice for a weights/mask matrix at this ConnectionField's location on the sheet (i.e. for getting the correct submatrix of the weights or mask in case the unit is near the edge of the sheet).
[ "Return", "the", "correct", "slice", "for", "a", "weights", "/", "mask", "matrix", "at", "this", "ConnectionField", "s", "location", "on", "the", "sheet", "(", "i", ".", "e", ".", "for", "getting", "the", "correct", "submatrix", "of", "the", "weights", "...
python
train
41
greenbender/pynntp
nntp/date.py
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L160-L186
def timestamp_YmdHMS(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an...
[ "def", "timestamp_YmdHMS", "(", "value", ")", ":", "i", "=", "int", "(", "value", ")", "S", "=", "i", "M", "=", "S", "//", "100", "H", "=", "M", "//", "100", "d", "=", "H", "//", "100", "m", "=", "d", "//", "100", "Y", "=", "m", "//", "10...
Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an integer. Raises: Value...
[ "Convert", "timestamp", "string", "to", "time", "in", "seconds", "since", "epoch", "." ]
python
test
23.555556
zenodo/zenodo-accessrequests
zenodo_accessrequests/models.py
https://github.com/zenodo/zenodo-accessrequests/blob/ce2cf3f1425d02ba4f3ad3202cfca43a1892558a/zenodo_accessrequests/models.py#L360-L369
def create_secret_link(self, title, description=None, expires_at=None): """Create a secret link from request.""" self.link = SecretLink.create( title, self.receiver, extra_data=dict(recid=self.recid), description=description, expires_at=expires...
[ "def", "create_secret_link", "(", "self", ",", "title", ",", "description", "=", "None", ",", "expires_at", "=", "None", ")", ":", "self", ".", "link", "=", "SecretLink", ".", "create", "(", "title", ",", "self", ".", "receiver", ",", "extra_data", "=", ...
Create a secret link from request.
[ "Create", "a", "secret", "link", "from", "request", "." ]
python
test
35
Crypto-toolbox/bitex
bitex/api/WSS/bitfinex.py
https://github.com/Crypto-toolbox/bitex/blob/56d46ea3db6de5219a72dad9b052fbabc921232f/bitex/api/WSS/bitfinex.py#L560-L571
def _handle_ticker(self, ts, chan_id, data): """ Adds received ticker data to self.tickers dict, filed under its channel id. :param ts: timestamp, declares when data was received by the client :param chan_id: int, channel id :param data: tuple or list of data received via...
[ "def", "_handle_ticker", "(", "self", ",", "ts", ",", "chan_id", ",", "data", ")", ":", "pair", "=", "self", ".", "channel_labels", "[", "chan_id", "]", "[", "1", "]", "[", "'pair'", "]", "entry", "=", "(", "*", "data", ",", "ts", ")", "self", "....
Adds received ticker data to self.tickers dict, filed under its channel id. :param ts: timestamp, declares when data was received by the client :param chan_id: int, channel id :param data: tuple or list of data received via wss :return:
[ "Adds", "received", "ticker", "data", "to", "self", ".", "tickers", "dict", "filed", "under", "its", "channel", "id", ".", ":", "param", "ts", ":", "timestamp", "declares", "when", "data", "was", "received", "by", "the", "client", ":", "param", "chan_id", ...
python
train
39.5
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L238-L264
def ensure_alt_ids_in_nest_spec_are_ints(nest_spec, list_elements): """ Ensures that the alternative id's in `nest_spec` are integers. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of ...
[ "def", "ensure_alt_ids_in_nest_spec_are_ints", "(", "nest_spec", ",", "list_elements", ")", ":", "try", ":", "assert", "all", "(", "[", "isinstance", "(", "x", ",", "int", ")", "for", "x", "in", "list_elements", "]", ")", "except", "AssertionError", ":", "ms...
Ensures that the alternative id's in `nest_spec` are integers. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternati...
[ "Ensures", "that", "the", "alternative", "id", "s", "in", "nest_spec", "are", "integers", ".", "Raises", "a", "helpful", "ValueError", "if", "they", "are", "not", "." ]
python
train
33.740741
biolink/ontobio
ontobio/assocmodel.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/assocmodel.py#L333-L337
def subontology(self, minimal=False): """ Generates a sub-ontology based on associations """ return self.ontology.subontology(self.objects, minimal=minimal)
[ "def", "subontology", "(", "self", ",", "minimal", "=", "False", ")", ":", "return", "self", ".", "ontology", ".", "subontology", "(", "self", ".", "objects", ",", "minimal", "=", "minimal", ")" ]
Generates a sub-ontology based on associations
[ "Generates", "a", "sub", "-", "ontology", "based", "on", "associations" ]
python
train
36.8
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L192-L202
def load_all(stream): """ Parse all YAML documents in a stream and produce corresponding YAMLDict objects. """ loader = YAMLDictLoader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose()
[ "def", "load_all", "(", "stream", ")", ":", "loader", "=", "YAMLDictLoader", "(", "stream", ")", "try", ":", "while", "loader", ".", "check_data", "(", ")", ":", "yield", "loader", ".", "get_data", "(", ")", "finally", ":", "loader", ".", "dispose", "(...
Parse all YAML documents in a stream and produce corresponding YAMLDict objects.
[ "Parse", "all", "YAML", "documents", "in", "a", "stream", "and", "produce", "corresponding", "YAMLDict", "objects", "." ]
python
train
24.545455
splitkeycoffee/pyhottop
pyhottop/pyhottop.py
https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L446-L476
def connect(self, interface=None): """Connect to the USB for the hottop. Attempt to discover the USB port used for the Hottop and then form a connection using the serial library. :returns: bool :raises SerialConnectionError: """ if self._simulate: re...
[ "def", "connect", "(", "self", ",", "interface", "=", "None", ")", ":", "if", "self", ".", "_simulate", ":", "return", "True", "if", "not", "interface", ":", "match", "=", "self", ".", "_autodiscover_usb", "(", ")", "self", ".", "_log", ".", "debug", ...
Connect to the USB for the hottop. Attempt to discover the USB port used for the Hottop and then form a connection using the serial library. :returns: bool :raises SerialConnectionError:
[ "Connect", "to", "the", "USB", "for", "the", "hottop", "." ]
python
train
36.258065
adewes/blitzdb
blitzdb/backends/file/queries.py
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L100-L114
def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ store_key for value, store_keys ...
[ "def", "regex_query", "(", "expression", ")", ":", "def", "_regex", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "pattern", "=", "re", ".", "compile", "(", "expression", ")", "re...
Apply regular expression to result of expression.
[ "Apply", "regular", "expression", "to", "result", "of", "expression", "." ]
python
train
34.133333
spotify/luigi
luigi/contrib/redshift.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L283-L291
def create_schema(self, connection): """ Will create the schema in the database """ if '.' not in self.table: return query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0]) connection.cursor().execute(query)
[ "def", "create_schema", "(", "self", ",", "connection", ")", ":", "if", "'.'", "not", "in", "self", ".", "table", ":", "return", "query", "=", "'CREATE SCHEMA IF NOT EXISTS {schema_name};'", ".", "format", "(", "schema_name", "=", "self", ".", "table", ".", ...
Will create the schema in the database
[ "Will", "create", "the", "schema", "in", "the", "database" ]
python
train
33.555556
ibis-project/ibis
ibis/expr/api.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L1161-L1191
def _numeric_summary(arg, exact_nunique=False, prefix=None): """ Compute a set of summary metrics from the input numeric value expression Parameters ---------- arg : numeric value expression exact_nunique : boolean, default False prefix : string, default None String prefix for metric ...
[ "def", "_numeric_summary", "(", "arg", ",", "exact_nunique", "=", "False", ",", "prefix", "=", "None", ")", ":", "metrics", "=", "[", "arg", ".", "count", "(", ")", ",", "arg", ".", "isnull", "(", ")", ".", "sum", "(", ")", ".", "name", "(", "'nu...
Compute a set of summary metrics from the input numeric value expression Parameters ---------- arg : numeric value expression exact_nunique : boolean, default False prefix : string, default None String prefix for metric names Returns ------- summary : (count, # nulls, min, max, s...
[ "Compute", "a", "set", "of", "summary", "metrics", "from", "the", "input", "numeric", "value", "expression" ]
python
train
25.516129
regebro/hovercraft
hovercraft/position.py
https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/position.py#L219-L236
def update_positions(tree, positions): """Updates the tree with new positions""" for step, pos in zip(tree.findall('step'), positions): for key in sorted(pos): value = pos.get(key) if key.endswith("-rel"): abs_key = key[:key.index("-rel")] if valu...
[ "def", "update_positions", "(", "tree", ",", "positions", ")", ":", "for", "step", ",", "pos", "in", "zip", "(", "tree", ".", "findall", "(", "'step'", ")", ",", "positions", ")", ":", "for", "key", "in", "sorted", "(", "pos", ")", ":", "value", "=...
Updates the tree with new positions
[ "Updates", "the", "tree", "with", "new", "positions" ]
python
train
40.5
projectatomic/atomic-reactor
atomic_reactor/plugins/post_export_operator_manifests.py
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_export_operator_manifests.py#L49-L61
def has_operator_manifest(self): """ Check if Dockerfile sets the operator manifest label :return: bool """ dockerfile = df_parser(self.workflow.builder.df_path, workflow=self.workflow) labels = Labels(dockerfile.labels) try: _, operator_label = label...
[ "def", "has_operator_manifest", "(", "self", ")", ":", "dockerfile", "=", "df_parser", "(", "self", ".", "workflow", ".", "builder", ".", "df_path", ",", "workflow", "=", "self", ".", "workflow", ")", "labels", "=", "Labels", "(", "dockerfile", ".", "label...
Check if Dockerfile sets the operator manifest label :return: bool
[ "Check", "if", "Dockerfile", "sets", "the", "operator", "manifest", "label" ]
python
train
36.615385
GNS3/gns3-server
gns3server/compute/dynamips/nodes/c3600.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/c3600.py#L129-L142
def set_iomem(self, iomem): """ Set I/O memory size for this router. :param iomem: I/O memory size """ yield from self._hypervisor.send('c3600 set_iomem "{name}" {size}'.format(name=self._name, size=iomem)) log.info('Router "{name}" [{id}]: I/O memory updated from {old...
[ "def", "set_iomem", "(", "self", ",", "iomem", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'c3600 set_iomem \"{name}\" {size}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "size", "=", "iomem", ")", ")", "lo...
Set I/O memory size for this router. :param iomem: I/O memory size
[ "Set", "I", "/", "O", "memory", "size", "for", "this", "router", "." ]
python
train
53.357143
Chilipp/model-organization
model_organization/config.py
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/config.py#L691-L713
def save(self): """ Save the project configuration This method dumps the configuration for each project and the project paths (see the :attr:`all_projects` attribute) to the hard drive """ project_paths = OrderedDict() for project, d in OrderedDict(self).items():...
[ "def", "save", "(", "self", ")", ":", "project_paths", "=", "OrderedDict", "(", ")", "for", "project", ",", "d", "in", "OrderedDict", "(", "self", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "d", ",", "dict", ")", ":", "project_path", ...
Save the project configuration This method dumps the configuration for each project and the project paths (see the :attr:`all_projects` attribute) to the hard drive
[ "Save", "the", "project", "configuration" ]
python
train
44.043478
Qiskit/qiskit-terra
qiskit/circuit/quantumcircuit.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L292-L294
def _attach(self, instruction, qargs, cargs): """DEPRECATED after 0.8""" self.append(instruction, qargs, cargs)
[ "def", "_attach", "(", "self", ",", "instruction", ",", "qargs", ",", "cargs", ")", ":", "self", ".", "append", "(", "instruction", ",", "qargs", ",", "cargs", ")" ]
DEPRECATED after 0.8
[ "DEPRECATED", "after", "0", ".", "8" ]
python
test
41.666667
mieubrisse/wunderpy2
wunderpy2/subtasks_endpoint.py
https://github.com/mieubrisse/wunderpy2/blob/7106b6c13ca45ef4d56f805753c93258d5b822c2/wunderpy2/subtasks_endpoint.py#L19-L26
def get_list_subtasks(client, list_id, completed=False): ''' Gets subtasks for the list with given ID ''' params = { 'list_id' : int(list_id), 'completed' : completed, } response = client.authenticated_request(client.api.Endpoints.SUBTASKS, params=params) return respo...
[ "def", "get_list_subtasks", "(", "client", ",", "list_id", ",", "completed", "=", "False", ")", ":", "params", "=", "{", "'list_id'", ":", "int", "(", "list_id", ")", ",", "'completed'", ":", "completed", ",", "}", "response", "=", "client", ".", "authen...
Gets subtasks for the list with given ID
[ "Gets", "subtasks", "for", "the", "list", "with", "given", "ID" ]
python
train
40.375
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/device_adapter.py#L112-L133
def disconnect_async(self, conn_id, callback): """Asynchronously disconnect from a device that has previously been connected Args: conn_id (int): a unique identifier for this connection on the DeviceManager that owns this adapter. callback (callable): A function ...
[ "def", "disconnect_async", "(", "self", ",", "conn_id", ",", "callback", ")", ":", "try", ":", "context", "=", "self", ".", "conns", ".", "get_context", "(", "conn_id", ")", "except", "ArgumentError", ":", "callback", "(", "conn_id", ",", "self", ".", "i...
Asynchronously disconnect from a device that has previously been connected Args: conn_id (int): a unique identifier for this connection on the DeviceManager that owns this adapter. callback (callable): A function called as callback(conn_id, adapter_id, success, failure_r...
[ "Asynchronously", "disconnect", "from", "a", "device", "that", "has", "previously", "been", "connected" ]
python
train
44.727273
BD2KGenomics/protect
src/protect/binding_prediction/common.py
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/binding_prediction/common.py#L389-L484
def predict_normal_binding(job, binding_result, transgened_files, allele, peplen, univ_options, mhc_options): """ Predict the binding score for the normal counterparts of the peptides in mhc_dict and then return the results in a properly formatted structure. :param str bindin...
[ "def", "predict_normal_binding", "(", "job", ",", "binding_result", ",", "transgened_files", ",", "allele", ",", "peplen", ",", "univ_options", ",", "mhc_options", ")", ":", "work_dir", "=", "os", ".", "getcwd", "(", ")", "results", "=", "pandas", ".", "Data...
Predict the binding score for the normal counterparts of the peptides in mhc_dict and then return the results in a properly formatted structure. :param str binding_result: The results from running predict_mhci_binding or predict_mhcii_binding on a single allele :param dict transgened_files: A di...
[ "Predict", "the", "binding", "score", "for", "the", "normal", "counterparts", "of", "the", "peptides", "in", "mhc_dict", "and", "then", "return", "the", "results", "in", "a", "properly", "formatted", "structure", "." ]
python
train
57.010417
Guake/guake
guake/guake_app.py
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L947-L959
def compute_tab_title(self, vte): """Abbreviate and cut vte terminal title when necessary """ vte_title = vte.get_window_title() or _("Terminal") try: current_directory = vte.get_current_directory() if self.abbreviate and vte_title.endswith(current_directory): ...
[ "def", "compute_tab_title", "(", "self", ",", "vte", ")", ":", "vte_title", "=", "vte", ".", "get_window_title", "(", ")", "or", "_", "(", "\"Terminal\"", ")", "try", ":", "current_directory", "=", "vte", ".", "get_current_directory", "(", ")", "if", "self...
Abbreviate and cut vte terminal title when necessary
[ "Abbreviate", "and", "cut", "vte", "terminal", "title", "when", "necessary" ]
python
train
48
zagfai/webtul
webtul/task.py
https://github.com/zagfai/webtul/blob/58c49928070b56ef54a45b4af20d800b269ad8ce/webtul/task.py#L192-L200
def get(self, timeout=10): """get() -> {'id': 32-byte-md5, 'body': msg-body}""" req = self.req({'op': 'GET', 'timeout': timeout}) if req.status_code != 200: return None result = req.json() if result.get('status') != 'ok': return False return result
[ "def", "get", "(", "self", ",", "timeout", "=", "10", ")", ":", "req", "=", "self", ".", "req", "(", "{", "'op'", ":", "'GET'", ",", "'timeout'", ":", "timeout", "}", ")", "if", "req", ".", "status_code", "!=", "200", ":", "return", "None", "resu...
get() -> {'id': 32-byte-md5, 'body': msg-body}
[ "get", "()", "-", ">", "{", "id", ":", "32", "-", "byte", "-", "md5", "body", ":", "msg", "-", "body", "}" ]
python
train
34.666667
common-workflow-language/schema_salad
schema_salad/schema.py
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L609-L621
def make_avro_schema(i, # type: List[Any] loader # type: Loader ): # type: (...) -> Names """ All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output. ...
[ "def", "make_avro_schema", "(", "i", ",", "# type: List[Any]", "loader", "# type: Loader", ")", ":", "# type: (...) -> Names", "names", "=", "Names", "(", ")", "avro", "=", "make_avro", "(", "i", ",", "loader", ")", "make_avsc_object", "(", "convert_to_dict", "(...
All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output.
[ "All", "in", "one", "convenience", "function", "." ]
python
train
33.384615
mapillary/mapillary_tools
mapillary_tools/ffprobe.py
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/ffprobe.py#L157-L169
def durationSeconds(self): """ Returns the runtime duration of the video stream as a floating point number of seconds. Returns 0.0 if not a video stream. """ f=0.0 if self.isVideo() or self.isAudio(): if self.__dict__['duration']: try: ...
[ "def", "durationSeconds", "(", "self", ")", ":", "f", "=", "0.0", "if", "self", ".", "isVideo", "(", ")", "or", "self", ".", "isAudio", "(", ")", ":", "if", "self", ".", "__dict__", "[", "'duration'", "]", ":", "try", ":", "f", "=", "float", "(",...
Returns the runtime duration of the video stream as a floating point number of seconds. Returns 0.0 if not a video stream.
[ "Returns", "the", "runtime", "duration", "of", "the", "video", "stream", "as", "a", "floating", "point", "number", "of", "seconds", ".", "Returns", "0", ".", "0", "if", "not", "a", "video", "stream", "." ]
python
train
35.384615
ArchiveTeam/wpull
wpull/stats.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/stats.py#L56-L66
def increment(self, size: int): '''Increment the number of files downloaded. Args: size: The size of the file ''' assert size >= 0, size self.files += 1 self.size += size self.bandwidth_meter.feed(size)
[ "def", "increment", "(", "self", ",", "size", ":", "int", ")", ":", "assert", "size", ">=", "0", ",", "size", "self", ".", "files", "+=", "1", "self", ".", "size", "+=", "size", "self", ".", "bandwidth_meter", ".", "feed", "(", "size", ")" ]
Increment the number of files downloaded. Args: size: The size of the file
[ "Increment", "the", "number", "of", "files", "downloaded", "." ]
python
train
23.818182
nephila/djangocms-installer
djangocms_installer/django/__init__.py
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L275-L402
def _build_settings(config_data): """ Build the django CMS settings dictionary :param config_data: configuration data """ spacer = ' ' text = [] vars = get_settings() vars.MIDDLEWARE_CLASSES.insert(0, vars.APPHOOK_RELOAD_MIDDLEWARE_CLASS) processors = vars.TEMPLATE_CONTEXT_PROC...
[ "def", "_build_settings", "(", "config_data", ")", ":", "spacer", "=", "' '", "text", "=", "[", "]", "vars", "=", "get_settings", "(", ")", "vars", ".", "MIDDLEWARE_CLASSES", ".", "insert", "(", "0", ",", "vars", ".", "APPHOOK_RELOAD_MIDDLEWARE_CLASS", ")...
Build the django CMS settings dictionary :param config_data: configuration data
[ "Build", "the", "django", "CMS", "settings", "dictionary" ]
python
valid
40.554688
dylanaraps/pywal
pywal/colors.py
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/colors.py#L76-L83
def saturate_colors(colors, amount): """Saturate all colors.""" if amount and float(amount) <= 1.0: for i, _ in enumerate(colors): if i not in [0, 7, 8, 15]: colors[i] = util.saturate_color(colors[i], float(amount)) return colors
[ "def", "saturate_colors", "(", "colors", ",", "amount", ")", ":", "if", "amount", "and", "float", "(", "amount", ")", "<=", "1.0", ":", "for", "i", ",", "_", "in", "enumerate", "(", "colors", ")", ":", "if", "i", "not", "in", "[", "0", ",", "7", ...
Saturate all colors.
[ "Saturate", "all", "colors", "." ]
python
train
33.875
saltstack/salt
salt/modules/opkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1599-L1630
def owner(*paths, **kwargs): # pylint: disable=unused-argument ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dic...
[ "def", "owner", "(", "*", "paths", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "if", "not", "paths", ":", "return", "''", "ret", "=", "{", "}", "cmd_search", "=", "[", "'opkg'", ",", "'search'", "]", "for", "path", "in", "pa...
Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not...
[ "Return", "the", "name", "of", "the", "package", "that", "owns", "the", "file", ".", "Multiple", "file", "paths", "can", "be", "passed", ".", "Like", ":", "mod", ":", "pkg", ".", "version", "<salt", ".", "modules", ".", "opkg", ".", "version", "if", ...
python
train
35.875
brendonh/pyth
pyth/plugins/xhtml/css.py
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/css.py#L73-L85
def parse_css(self, css): """ Parse a css style sheet into the CSS object. For the moment this will only work for very simple css documents. It works by using regular expression matching css syntax. This is not bullet proof. """ rulesets = self.ruleset_re.finda...
[ "def", "parse_css", "(", "self", ",", "css", ")", ":", "rulesets", "=", "self", ".", "ruleset_re", ".", "findall", "(", "css", ")", "for", "(", "selector", ",", "declarations", ")", "in", "rulesets", ":", "rule", "=", "Rule", "(", "self", ".", "parse...
Parse a css style sheet into the CSS object. For the moment this will only work for very simple css documents. It works by using regular expression matching css syntax. This is not bullet proof.
[ "Parse", "a", "css", "style", "sheet", "into", "the", "CSS", "object", "." ]
python
train
40.307692
StackStorm/pybind
pybind/slxos/v17r_2_00/telemetry/profile/mpls_traffic_bypass/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_2_00/telemetry/profile/mpls_traffic_bypass/__init__.py#L167-L188
def _set_mpls_traffic_bypasses(self, v, load=False): """ Setter method for mpls_traffic_bypasses, mapped from YANG variable /telemetry/profile/mpls_traffic_bypass/mpls_traffic_bypasses (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_traffic_bypasses is consid...
[ "def", "_set_mpls_traffic_bypasses", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
Setter method for mpls_traffic_bypasses, mapped from YANG variable /telemetry/profile/mpls_traffic_bypass/mpls_traffic_bypasses (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_traffic_bypasses is considered as a private method. Backends looking to populate this v...
[ "Setter", "method", "for", "mpls_traffic_bypasses", "mapped", "from", "YANG", "variable", "/", "telemetry", "/", "profile", "/", "mpls_traffic_bypass", "/", "mpls_traffic_bypasses", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "con...
python
train
129
brunobord/tdaemon
tdaemon.py
https://github.com/brunobord/tdaemon/blob/733b5bddb4b12bc3db326a192ce5606f28768307/tdaemon.py#L88-L101
def check_configuration(self, file_path, test_program, custom_args): """Checks if configuration is ok.""" # checking filepath if not os.path.isdir(file_path): raise InvalidFilePath("INVALID CONFIGURATION: file path %s is not a directory" % os.path.abspath(file_path) ...
[ "def", "check_configuration", "(", "self", ",", "file_path", ",", "test_program", ",", "custom_args", ")", ":", "# checking filepath", "if", "not", "os", ".", "path", ".", "isdir", "(", "file_path", ")", ":", "raise", "InvalidFilePath", "(", "\"INVALID CONFIGURA...
Checks if configuration is ok.
[ "Checks", "if", "configuration", "is", "ok", "." ]
python
train
55.285714
poldracklab/niworkflows
niworkflows/data/utils.py
https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/data/utils.py#L353-L383
def _chunk_report_(bytes_so_far, total_size, initial_size, t_0): """Show downloading percentage. :param int bytes_so_far: number of downloaded bytes :param int total_size: total size of the file (may be 0/None, depending on download method). :param int t_0: the time in seconds (as returned by t...
[ "def", "_chunk_report_", "(", "bytes_so_far", ",", "total_size", ",", "initial_size", ",", "t_0", ")", ":", "if", "not", "total_size", ":", "sys", ".", "stderr", ".", "write", "(", "\"\\rDownloaded {0:d} of ? bytes.\"", ".", "format", "(", "bytes_so_far", ")", ...
Show downloading percentage. :param int bytes_so_far: number of downloaded bytes :param int total_size: total size of the file (may be 0/None, depending on download method). :param int t_0: the time in seconds (as returned by time.time()) at which the download was resumed / started. :pa...
[ "Show", "downloading", "percentage", "." ]
python
train
43.516129
rongcloud/server-sdk-python
rongcloud/user.py
https://github.com/rongcloud/server-sdk-python/blob/3daadd8b67c84cc5d2a9419e8d45fd69c9baf976/rongcloud/user.py#L89-L120
def checkOnline(self, userId): """ 检查用户在线状态 方法 方法 @param userId:用户 Id,最大长度 64 字节。是用户在 App 中的唯一标识码,必须保证在同一个 App 内不重复,重复的用户 Id 将被当作是同一用户。(必传) @return code:返回码,200 为正常。 @return status:在线状态,1为在线,0为不在线。 @return errorMessage:错误信息。 """ desc = { "nam...
[ "def", "checkOnline", "(", "self", ",", "userId", ")", ":", "desc", "=", "{", "\"name\"", ":", "\"CheckOnlineReslut\"", ",", "\"desc\"", ":", "\"checkOnlineUser返回结果\",", "", "\"fields\"", ":", "[", "{", "\"name\"", ":", "\"code\"", ",", "\"type\"", ":", "\"I...
检查用户在线状态 方法 方法 @param userId:用户 Id,最大长度 64 字节。是用户在 App 中的唯一标识码,必须保证在同一个 App 内不重复,重复的用户 Id 将被当作是同一用户。(必传) @return code:返回码,200 为正常。 @return status:在线状态,1为在线,0为不在线。 @return errorMessage:错误信息。
[ "检查用户在线状态", "方法", "方法" ]
python
train
30.625
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L86-L127
def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of ar...
[ "def", "get_chunk_size", "(", "N", ",", "n", ")", ":", "mem_free", "=", "memory", "(", ")", "[", "'free'", "]", "if", "mem_free", ">", "60000000", ":", "chunk_size", "=", "int", "(", "(", "(", "mem_free", "-", "10000000", ")", "*", "1000", ")", "/"...
Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_siz...
[ "Given", "a", "two", "-", "dimensional", "array", "with", "a", "dimension", "of", "size", "N", "determine", "the", "number", "of", "rows", "or", "columns", "that", "can", "fit", "into", "memory", "." ]
python
train
34.761905
Alignak-monitoring/alignak
alignak/objects/item.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L247-L258
def init_running_properties(self): """ Initialize the running_properties. Each instance have own property. :return: None """ for prop, entry in list(self.__class__.running_properties.items()): val = entry.default # Make a copy of the value for com...
[ "def", "init_running_properties", "(", "self", ")", ":", "for", "prop", ",", "entry", "in", "list", "(", "self", ".", "__class__", ".", "running_properties", ".", "items", "(", ")", ")", ":", "val", "=", "entry", ".", "default", "# Make a copy of the value f...
Initialize the running_properties. Each instance have own property. :return: None
[ "Initialize", "the", "running_properties", ".", "Each", "instance", "have", "own", "property", "." ]
python
train
41.583333
robertmartin8/PyPortfolioOpt
pypfopt/risk_models.py
https://github.com/robertmartin8/PyPortfolioOpt/blob/dfad1256cb6995c7fbd7a025eedb54b1ca04b2fc/pypfopt/risk_models.py#L248-L308
def shrink(self): """ Calculate the Constant-Correlation covariance matrix. :return: shrunk sample covariance matrix :rtype: np.ndarray """ x = np.nan_to_num(self.X.values) # de-mean returns t, n = np.shape(x) meanx = x.mean(axis=0) x = x...
[ "def", "shrink", "(", "self", ")", ":", "x", "=", "np", ".", "nan_to_num", "(", "self", ".", "X", ".", "values", ")", "# de-mean returns", "t", ",", "n", "=", "np", ".", "shape", "(", "x", ")", "meanx", "=", "x", ".", "mean", "(", "axis", "=", ...
Calculate the Constant-Correlation covariance matrix. :return: shrunk sample covariance matrix :rtype: np.ndarray
[ "Calculate", "the", "Constant", "-", "Correlation", "covariance", "matrix", "." ]
python
train
33.081967
bitesofcode/projex
projex/xmlutil.py
https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/xmlutil.py#L228-L243
def save(self, data, xparent=None): """ Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.ElementTree.Element> || None :return <xml.etree.ElementTree.Element> """ if xparent is not None: ...
[ "def", "save", "(", "self", ",", "data", ",", "xparent", "=", "None", ")", ":", "if", "xparent", "is", "not", "None", ":", "elem", "=", "ElementTree", ".", "SubElement", "(", "xparent", ",", "'bool'", ")", "else", ":", "elem", "=", "ElementTree", "."...
Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.ElementTree.Element> || None :return <xml.etree.ElementTree.Element>
[ "Parses", "the", "element", "from", "XML", "to", "Python", ".", ":", "param", "data", "|", "<variant", ">", "xparent", "|", "<xml", ".", "etree", ".", "ElementTree", ".", "Element", ">", "||", "None", ":", "return", "<xml", ".", "etree", ".", "ElementT...
python
train
29.6875
GNS3/gns3-server
gns3server/compute/base_node.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/base_node.py#L286-L293
def stop(self): """ Stop the node process. """ if self._wrapper_telnet_server: self._wrapper_telnet_server.close() yield from self._wrapper_telnet_server.wait_closed() self.status = "stopped"
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_wrapper_telnet_server", ":", "self", ".", "_wrapper_telnet_server", ".", "close", "(", ")", "yield", "from", "self", ".", "_wrapper_telnet_server", ".", "wait_closed", "(", ")", "self", ".", "status"...
Stop the node process.
[ "Stop", "the", "node", "process", "." ]
python
train
31
getsentry/sentry-plugins
src/sentry_plugins/vsts/plugin.py
https://github.com/getsentry/sentry-plugins/blob/2d65331bcb807e0bb16b5e7bdcae56b152bb0dda/src/sentry_plugins/vsts/plugin.py#L102-L132
def create_issue(self, request, group, form_data, **kwargs): """ Creates the issue on the remote service and returns an issue ID. """ instance = self.get_option('instance', group.project) project = ( form_data.get('project') or self.get_option('default_pro...
[ "def", "create_issue", "(", "self", ",", "request", ",", "group", ",", "form_data", ",", "*", "*", "kwargs", ")", ":", "instance", "=", "self", ".", "get_option", "(", "'instance'", ",", "group", ".", "project", ")", "project", "=", "(", "form_data", "...
Creates the issue on the remote service and returns an issue ID.
[ "Creates", "the", "issue", "on", "the", "remote", "service", "and", "returns", "an", "issue", "ID", "." ]
python
train
33.16129
joerick/pyinstrument
pyinstrument/vendor/decorator.py
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/vendor/decorator.py#L331-L433
def dispatch_on(*dispatch_args): """ Factory of decorators turning a function into a generic function dispatching on the given arguments. """ assert dispatch_args, 'No dispatch args passed' dispatch_str = '(%s,)' % ', '.join(dispatch_args) def check(arguments, wrong=operator.ne, msg=''): ...
[ "def", "dispatch_on", "(", "*", "dispatch_args", ")", ":", "assert", "dispatch_args", ",", "'No dispatch args passed'", "dispatch_str", "=", "'(%s,)'", "%", "', '", ".", "join", "(", "dispatch_args", ")", "def", "check", "(", "arguments", ",", "wrong", "=", "o...
Factory of decorators turning a function into a generic function dispatching on the given arguments.
[ "Factory", "of", "decorators", "turning", "a", "function", "into", "a", "generic", "function", "dispatching", "on", "the", "given", "arguments", "." ]
python
train
35.563107
pmacosta/peng
docs/support/ptypes.py
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/ptypes.py#L277-L295
def wave_interp_option(obj): r""" Validate if an object is a :ref:`WaveInterpOption` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contr...
[ "def", "wave_interp_option", "(", "obj", ")", ":", "exdesc", "=", "pexdoc", ".", "pcontracts", ".", "get_exdesc", "(", ")", "if", "not", "isinstance", "(", "obj", ",", "str", ")", ":", "raise", "ValueError", "(", "exdesc", ")", "if", "obj", ".", "upper...
r""" Validate if an object is a :ref:`WaveInterpOption` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contract is attached to :rtype: N...
[ "r", "Validate", "if", "an", "object", "is", "a", ":", "ref", ":", "WaveInterpOption", "pseudo", "-", "type", "object", "." ]
python
test
29.263158
arviz-devs/arviz
arviz/plots/energyplot.py
https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/plots/energyplot.py#L11-L146
def plot_energy( data, kind="kde", bfmi=True, figsize=None, legend=True, fill_alpha=(1, 0.75), fill_color=("C0", "C5"), bw=4.5, textsize=None, fill_kwargs=None, plot_kwargs=None, ax=None, ): """Plot energy transition distribution and marginal energy distribution in HM...
[ "def", "plot_energy", "(", "data", ",", "kind", "=", "\"kde\"", ",", "bfmi", "=", "True", ",", "figsize", "=", "None", ",", "legend", "=", "True", ",", "fill_alpha", "=", "(", "1", ",", "0.75", ")", ",", "fill_color", "=", "(", "\"C0\"", ",", "\"C5...
Plot energy transition distribution and marginal energy distribution in HMC algorithms. This may help to diagnose poor exploration by gradient-based algorithms like HMC or NUTS. Parameters ---------- data : xarray dataset, or object that can be converted (must represent `sample_stats` and h...
[ "Plot", "energy", "transition", "distribution", "and", "marginal", "energy", "distribution", "in", "HMC", "algorithms", "." ]
python
train
29.264706
pkgw/pwkit
pwkit/environments/casa/tasks.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/environments/casa/tasks.py#L2267-L2288
def importalma(asdm, ms): """Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: f...
[ "def", "importalma", "(", "asdm", ",", "ms", ")", ":", "from", ".", "scripting", "import", "CasapyScript", "script", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'cscript_importalma.py'", ")", ...
Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: from pwkit.environments.casa impor...
[ "Convert", "an", "ALMA", "low", "-", "level", "ASDM", "dataset", "to", "Measurement", "Set", "format", "." ]
python
train
26.636364
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_horizon.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_horizon.py#L36-L63
def fpsInformation(self,args): '''fps command''' invalidStr = 'Invalid number of arguments. Usage horizon-fps set <fps> or horizon-fps get. Set fps to zero to get unrestricted framerate.' if len(args)>0: if args[0] == "get": '''Get the current framerate.''' ...
[ "def", "fpsInformation", "(", "self", ",", "args", ")", ":", "invalidStr", "=", "'Invalid number of arguments. Usage horizon-fps set <fps> or horizon-fps get. Set fps to zero to get unrestricted framerate.'", "if", "len", "(", "args", ")", ">", "0", ":", "if", "args", "[", ...
fps command
[ "fps", "command" ]
python
train
41.428571
AoiKuiyuyou/AoikLiveReload
src/aoiklivereload/aoiklivereload.py
https://github.com/AoiKuiyuyou/AoikLiveReload/blob/0d5adb12118a33749e6690a8165fdb769cff7d5c/src/aoiklivereload/aoiklivereload.py#L450-L480
def reload_using_spawn_exit(self): """ Spawn a subprocess and exit the current process. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Spawn subpro...
[ "def", "reload_using_spawn_exit", "(", "self", ")", ":", "# Create command parts", "cmd_parts", "=", "[", "sys", ".", "executable", "]", "+", "sys", ".", "argv", "# Get env dict copy", "env_copy", "=", "os", ".", "environ", ".", "copy", "(", ")", "# Spawn subp...
Spawn a subprocess and exit the current process. :return: None.
[ "Spawn", "a", "subprocess", "and", "exit", "the", "current", "process", "." ]
python
train
23.903226
Spinmob/spinmob
_data.py
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1234-L1285
def c(self, *args, **kwargs): """ Takes a single argument or keyword argument, and returns the specified column. If the argument (or keyword argument) is an integer, return the n'th column, otherwise return the column based on key. If no arguments are supplied, simply ...
[ "def", "c", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# If not arguments, print everything", "if", "len", "(", "args", ")", "+", "len", "(", "kwargs", ")", "==", "0", ":", "print", "(", "\"Columns\"", ")", "if", "len", "(", ...
Takes a single argument or keyword argument, and returns the specified column. If the argument (or keyword argument) is an integer, return the n'th column, otherwise return the column based on key. If no arguments are supplied, simply print the column information.
[ "Takes", "a", "single", "argument", "or", "keyword", "argument", "and", "returns", "the", "specified", "column", ".", "If", "the", "argument", "(", "or", "keyword", "argument", ")", "is", "an", "integer", "return", "the", "n", "th", "column", "otherwise", ...
python
train
35.288462
Esri/ArcREST
src/arcrest/manageags/administration.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/administration.py#L488-L500
def uploads(self): """returns an object to work with the site uploads""" if self._resources is None: self.__init() if "uploads" in self._resources: url = self._url + "/uploads" return _uploads.Uploads(url=url, securityHandle...
[ "def", "uploads", "(", "self", ")", ":", "if", "self", ".", "_resources", "is", "None", ":", "self", ".", "__init", "(", ")", "if", "\"uploads\"", "in", "self", ".", "_resources", ":", "url", "=", "self", ".", "_url", "+", "\"/uploads\"", "return", "...
returns an object to work with the site uploads
[ "returns", "an", "object", "to", "work", "with", "the", "site", "uploads" ]
python
train
42.384615
dropbox/stone
stone/backends/python_type_stubs.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/backends/python_type_stubs.py#L151-L160
def _generate_typevars(self): # type: () -> None """ Creates type variables that are used by the type signatures for _process_custom_annotations. """ self.emit("T = TypeVar('T', bound=bb.AnnotationType)") self.emit("U = TypeVar('U')") self.import_tracker._...
[ "def", "_generate_typevars", "(", "self", ")", ":", "# type: () -> None", "self", ".", "emit", "(", "\"T = TypeVar('T', bound=bb.AnnotationType)\"", ")", "self", ".", "emit", "(", "\"U = TypeVar('U')\"", ")", "self", ".", "import_tracker", ".", "_register_typing_import"...
Creates type variables that are used by the type signatures for _process_custom_annotations.
[ "Creates", "type", "variables", "that", "are", "used", "by", "the", "type", "signatures", "for", "_process_custom_annotations", "." ]
python
train
36.4
yamins81/tabular
tabular/spreadsheet.py
https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/spreadsheet.py#L1126-L1316
def join(L, keycols=None, nullvals=None, renamer=None, returnrenaming=False, Names=None): """ Combine two or more numpy ndarray with structured dtype on common key column(s). Merge a list (or dictionary) of numpy ndarray with structured dtype, given by `L`, on key columns listed in `keyc...
[ "def", "join", "(", "L", ",", "keycols", "=", "None", ",", "nullvals", "=", "None", ",", "renamer", "=", "None", ",", "returnrenaming", "=", "False", ",", "Names", "=", "None", ")", ":", "if", "isinstance", "(", "L", ",", "dict", ")", ":", "Names",...
Combine two or more numpy ndarray with structured dtype on common key column(s). Merge a list (or dictionary) of numpy ndarray with structured dtype, given by `L`, on key columns listed in `keycols`. This function is actually a wrapper for :func:`tabular.spreadsheet.strictjoin`. The ``stric...
[ "Combine", "two", "or", "more", "numpy", "ndarray", "with", "structured", "dtype", "on", "common", "key", "column", "(", "s", ")", "." ]
python
train
37.471204
QuantEcon/QuantEcon.py
quantecon/game_theory/repeated_game.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/game_theory/repeated_game.py#L435-L458
def _update_u(u, W): """ Update the threat points if it not feasible in the new W, by the minimum of new feasible payoffs. Parameters ---------- u : ndarray(float, ndim=1) The threat points. W : ndarray(float, ndim=1) The points that construct the feasible payoff convex hul...
[ "def", "_update_u", "(", "u", ",", "W", ")", ":", "for", "i", "in", "range", "(", "2", ")", ":", "W_min", "=", "W", "[", ":", ",", "i", "]", ".", "min", "(", ")", "if", "u", "[", "i", "]", "<", "W_min", ":", "u", "[", "i", "]", "=", "...
Update the threat points if it not feasible in the new W, by the minimum of new feasible payoffs. Parameters ---------- u : ndarray(float, ndim=1) The threat points. W : ndarray(float, ndim=1) The points that construct the feasible payoff convex hull. Returns ------- u...
[ "Update", "the", "threat", "points", "if", "it", "not", "feasible", "in", "the", "new", "W", "by", "the", "minimum", "of", "new", "feasible", "payoffs", "." ]
python
train
21.458333
yakupadakli/python-unsplash
unsplash/photo.py
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L179-L192
def like(self, photo_id): """ Like a photo on behalf of the logged-in user. This requires the 'write_likes' scope. Note: This action is idempotent; sending the POST request to a single photo multiple times has no additional effect. :param photo_id [string]: The photo’s ...
[ "def", "like", "(", "self", ",", "photo_id", ")", ":", "url", "=", "\"/photos/%s/like\"", "%", "photo_id", "result", "=", "self", ".", "_post", "(", "url", ")", "return", "PhotoModel", ".", "parse", "(", "result", ")" ]
Like a photo on behalf of the logged-in user. This requires the 'write_likes' scope. Note: This action is idempotent; sending the POST request to a single photo multiple times has no additional effect. :param photo_id [string]: The photo’s ID. Required. :return: [Photo]: The Un...
[ "Like", "a", "photo", "on", "behalf", "of", "the", "logged", "-", "in", "user", ".", "This", "requires", "the", "write_likes", "scope", "." ]
python
train
35.285714
Yubico/yubikey-manager
ykman/cli/config.py
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/config.py#L332-L401
def nfc(ctx, enable, disable, enable_all, disable_all, list, lock_code, force): """ Enable or disable applications over NFC. """ if not (list or enable_all or enable or disable_all or disable): ctx.fail('No configuration options chosen.') if enable_all: enable = APPLICATION.__membe...
[ "def", "nfc", "(", "ctx", ",", "enable", ",", "disable", ",", "enable_all", ",", "disable_all", ",", "list", ",", "lock_code", ",", "force", ")", ":", "if", "not", "(", "list", "or", "enable_all", "or", "enable", "or", "disable_all", "or", "disable", "...
Enable or disable applications over NFC.
[ "Enable", "or", "disable", "applications", "over", "NFC", "." ]
python
train
31.128571
googlesamples/assistant-sdk-python
google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py
https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L322-L327
def write(self, buf): """Write bytes to the sink (if currently playing). """ buf = align_buf(buf, self._sample_width) buf = normalize_audio_buffer(buf, self.volume_percentage) return self._sink.write(buf)
[ "def", "write", "(", "self", ",", "buf", ")", ":", "buf", "=", "align_buf", "(", "buf", ",", "self", ".", "_sample_width", ")", "buf", "=", "normalize_audio_buffer", "(", "buf", ",", "self", ".", "volume_percentage", ")", "return", "self", ".", "_sink", ...
Write bytes to the sink (if currently playing).
[ "Write", "bytes", "to", "the", "sink", "(", "if", "currently", "playing", ")", "." ]
python
train
39.833333
wtolson/gnsq
gnsq/nsqd.py
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L556-L559
def create_topic(self, topic): """Create a topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/create', fields={'topic': topic})
[ "def", "create_topic", "(", "self", ",", "topic", ")", ":", "nsq", ".", "assert_valid_topic_name", "(", "topic", ")", "return", "self", ".", "_request", "(", "'POST'", ",", "'/topic/create'", ",", "fields", "=", "{", "'topic'", ":", "topic", "}", ")" ]
Create a topic.
[ "Create", "a", "topic", "." ]
python
train
44.75
trec-kba/streamcorpus-pipeline
streamcorpus_pipeline/run.py
https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/run.py#L117-L159
def instantiate_config(config): '''setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added to sys.path * If 'setup_mod...
[ "def", "instantiate_config", "(", "config", ")", ":", "make_absolute_paths", "(", "config", ")", "pipeline_config", "=", "config", "[", "'streamcorpus_pipeline'", "]", "pipeline_config", "[", "'config_hash'", "]", "=", "make_hash", "(", "config", ")", "pipeline_conf...
setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added to sys.path * If 'setup_modules' is in the config, all modules nam...
[ "setup", "the", "config", "and", "load", "external", "modules" ]
python
test
36.186047
mikedh/trimesh
trimesh/exchange/ply.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/exchange/ply.py#L97-L205
def export_ply(mesh, encoding='binary', vertex_normal=None): """ Export a mesh in the PLY format. Parameters ---------- mesh : Trimesh object encoding : ['ascii'|'binary_little_endian'] vertex_normal : include vertex normals Returns ---------- expo...
[ "def", "export_ply", "(", "mesh", ",", "encoding", "=", "'binary'", ",", "vertex_normal", "=", "None", ")", ":", "# evaluate input args", "# allow a shortcut for binary", "if", "encoding", "==", "'binary'", ":", "encoding", "=", "'binary_little_endian'", "elif", "en...
Export a mesh in the PLY format. Parameters ---------- mesh : Trimesh object encoding : ['ascii'|'binary_little_endian'] vertex_normal : include vertex normals Returns ---------- export : bytes of result
[ "Export", "a", "mesh", "in", "the", "PLY", "format", "." ]
python
train
34.385321
staugur/Flask-PluginKit
example/plugins/jwt/__init__.py
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/example/plugins/jwt/__init__.py#L85-L112
def post(self): """token生成流程: >1. 首先使用用户名和密码去签定身份返回True/False >2. 如果True接着获取用户可公开数据 >3. 之后生成JWT 具体业务流程自由定义,比如可以保存token到redis中,设置ttl过期时间。 """ #1. username = request.form.get("username") password = request.form.get("password") exipres = 7200...
[ "def", "post", "(", "self", ")", ":", "#1.", "username", "=", "request", ".", "form", ".", "get", "(", "\"username\"", ")", "password", "=", "request", ".", "form", ".", "get", "(", "\"password\"", ")", "exipres", "=", "7200", "#expire time(seconds)", "i...
token生成流程: >1. 首先使用用户名和密码去签定身份返回True/False >2. 如果True接着获取用户可公开数据 >3. 之后生成JWT 具体业务流程自由定义,比如可以保存token到redis中,设置ttl过期时间。
[ "token生成流程", ":", ">", "1", ".", "首先使用用户名和密码去签定身份返回True", "/", "False", ">", "2", ".", "如果True接着获取用户可公开数据", ">", "3", ".", "之后生成JWT", "具体业务流程自由定义,比如可以保存token到redis中,设置ttl过期时间。" ]
python
train
32.25
apache/incubator-heron
heron/tools/admin/src/python/standalone.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L554-L571
def wait_for_master_to_start(single_master): ''' Wait for a nomad master to start ''' i = 0 while True: try: r = requests.get("http://%s:4646/v1/status/leader" % single_master) if r.status_code == 200: break except: Log.debug(sys.exc_info()[0]) Log.info("Waiting for clu...
[ "def", "wait_for_master_to_start", "(", "single_master", ")", ":", "i", "=", "0", "while", "True", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "\"http://%s:4646/v1/status/leader\"", "%", "single_master", ")", "if", "r", ".", "status_code", "==", ...
Wait for a nomad master to start
[ "Wait", "for", "a", "nomad", "master", "to", "start" ]
python
valid
25.222222
Valuehorizon/valuehorizon-companies
companies/models.py
https://github.com/Valuehorizon/valuehorizon-companies/blob/5366e230da69ee30fcdc1bf4beddc99310f6b767/companies/models.py#L466-L472
def save(self, *args, **kwargs): """ Updates name """ self.name = str(self.company.name) + " --- " + str(self.person) super(Executive, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "name", "=", "str", "(", "self", ".", "company", ".", "name", ")", "+", "\" --- \"", "+", "str", "(", "self", ".", "person", ")", "super", "(", "E...
Updates name
[ "Updates", "name" ]
python
train
28.714286
fhcrc/seqmagick
seqmagick/subcommands/quality_filter.py
https://github.com/fhcrc/seqmagick/blob/1642bb87ba5c171fbd307f9da0f8a0ee1d69d5ed/seqmagick/subcommands/quality_filter.py#L427-L437
def filter_record(self, record): """ Filter a single record """ quality_scores = record.letter_annotations['phred_quality'] mean_score = mean(quality_scores) if mean_score >= self.min_mean_score: return record else: raise FailedFilter(mean...
[ "def", "filter_record", "(", "self", ",", "record", ")", ":", "quality_scores", "=", "record", ".", "letter_annotations", "[", "'phred_quality'", "]", "mean_score", "=", "mean", "(", "quality_scores", ")", "if", "mean_score", ">=", "self", ".", "min_mean_score",...
Filter a single record
[ "Filter", "a", "single", "record" ]
python
train
28.818182
oblalex/django-candv-choices
candv_x/django/choices/db.py
https://github.com/oblalex/django-candv-choices/blob/a299cefceebc2fb23e223dfcc63700dff572b6a0/candv_x/django/choices/db.py#L99-L109
def _get_flatchoices(self): """ Redefine standard method. Return constants themselves instead of their names for right rendering in admin's 'change_list' view, if field is present in 'list_display' attribute of model's admin. """ return [ (self.to_pyt...
[ "def", "_get_flatchoices", "(", "self", ")", ":", "return", "[", "(", "self", ".", "to_python", "(", "choice", ")", ",", "value", ")", "for", "choice", ",", "value", "in", "self", ".", "_choices", "]" ]
Redefine standard method. Return constants themselves instead of their names for right rendering in admin's 'change_list' view, if field is present in 'list_display' attribute of model's admin.
[ "Redefine", "standard", "method", "." ]
python
train
34