repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
IvanMalison/okcupyd | okcupyd/profile.py | https://github.com/IvanMalison/okcupyd/blob/46f4eaa9419098f6c299738ce148af55c64deb64/okcupyd/profile.py#L220-L229 | def age(self):
"""
:returns: The age of the user associated with this profile.
"""
if self.is_logged_in_user:
# Retrieve the logged-in user's profile age
return int(self._user_age_xpb.get_text_(self.profile_tree).strip())
else:
# Retrieve a no... | [
"def",
"age",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_logged_in_user",
":",
"# Retrieve the logged-in user's profile age",
"return",
"int",
"(",
"self",
".",
"_user_age_xpb",
".",
"get_text_",
"(",
"self",
".",
"profile_tree",
")",
".",
"strip",
"(",
")"... | :returns: The age of the user associated with this profile. | [
":",
"returns",
":",
"The",
"age",
"of",
"the",
"user",
"associated",
"with",
"this",
"profile",
"."
] | python | train |
mikedh/trimesh | trimesh/util.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/util.py#L303-L324 | def make_sequence(obj):
"""
Given an object, if it is a sequence return, otherwise
add it to a length 1 sequence and return.
Useful for wrapping functions which sometimes return single
objects and other times return lists of objects.
Parameters
--------------
obj : object
An obje... | [
"def",
"make_sequence",
"(",
"obj",
")",
":",
"if",
"is_sequence",
"(",
"obj",
")",
":",
"return",
"np",
".",
"array",
"(",
"list",
"(",
"obj",
")",
")",
"else",
":",
"return",
"np",
".",
"array",
"(",
"[",
"obj",
"]",
")"
] | Given an object, if it is a sequence return, otherwise
add it to a length 1 sequence and return.
Useful for wrapping functions which sometimes return single
objects and other times return lists of objects.
Parameters
--------------
obj : object
An object to be made a sequence
Return... | [
"Given",
"an",
"object",
"if",
"it",
"is",
"a",
"sequence",
"return",
"otherwise",
"add",
"it",
"to",
"a",
"length",
"1",
"sequence",
"and",
"return",
"."
] | python | train |
totalgood/twip | twip/scripts/clean.py | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/clean.py#L107-L146 | def dropna(df, nonnull_rows=100, nonnull_cols=50, nanstrs=('nan', 'NaN', ''), nullstr=''):
"""Drop columns/rows with too many NaNs and replace NaNs in columns of strings with ''
>>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]])
>>> dropna(df)
Empty DataFrame
Columns... | [
"def",
"dropna",
"(",
"df",
",",
"nonnull_rows",
"=",
"100",
",",
"nonnull_cols",
"=",
"50",
",",
"nanstrs",
"=",
"(",
"'nan'",
",",
"'NaN'",
",",
"''",
")",
",",
"nullstr",
"=",
"''",
")",
":",
"if",
"0",
"<",
"nonnull_rows",
"<",
"1",
":",
"non... | Drop columns/rows with too many NaNs and replace NaNs in columns of strings with ''
>>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]])
>>> dropna(df)
Empty DataFrame
Columns: []
Index: []
>>> dropna(df, nonnull_cols=0, nonnull_rows=0)
0 1 2
0 ... | [
"Drop",
"columns",
"/",
"rows",
"with",
"too",
"many",
"NaNs",
"and",
"replace",
"NaNs",
"in",
"columns",
"of",
"strings",
"with"
] | python | train |
hydraplatform/hydra-base | hydra_base/lib/scenario.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/scenario.py#L220-L286 | def update_scenario(scenario,update_data=True,update_groups=True,flush=True,**kwargs):
"""
Update a single scenario
as all resources already exist, there is no need to worry
about negative IDS
flush = True flushes to the DB at the end of the function.
flush = False does not ... | [
"def",
"update_scenario",
"(",
"scenario",
",",
"update_data",
"=",
"True",
",",
"update_groups",
"=",
"True",
",",
"flush",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"scen",
"=",
"_get... | Update a single scenario
as all resources already exist, there is no need to worry
about negative IDS
flush = True flushes to the DB at the end of the function.
flush = False does not flush, assuming that it will happen as part
of another process, like update_network. | [
"Update",
"a",
"single",
"scenario",
"as",
"all",
"resources",
"already",
"exist",
"there",
"is",
"no",
"need",
"to",
"worry",
"about",
"negative",
"IDS"
] | python | train |
toomore/grs | grs/best_buy_or_sell.py | https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/best_buy_or_sell.py#L50-L57 | def best_buy_1(self):
""" 量大收紅
:rtype: bool
"""
result = self.data.value[-1] > self.data.value[-2] and \
self.data.price[-1] > self.data.openprice[-1]
return result | [
"def",
"best_buy_1",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"data",
".",
"value",
"[",
"-",
"1",
"]",
">",
"self",
".",
"data",
".",
"value",
"[",
"-",
"2",
"]",
"and",
"self",
".",
"data",
".",
"price",
"[",
"-",
"1",
"]",
">",
... | 量大收紅
:rtype: bool | [
"量大收紅"
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/functionprofiler.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/functionprofiler.py#L104-L129 | def parseprofile(profilelog, out):
'''
Parse a profile log and print the result on screen
'''
file = open(out, 'w') # opening the output file
print('Opening the profile in %s...' % profilelog)
p = pstats.Stats(profilelog, stream=file) # parsing the profile with pstats, and output everything to t... | [
"def",
"parseprofile",
"(",
"profilelog",
",",
"out",
")",
":",
"file",
"=",
"open",
"(",
"out",
",",
"'w'",
")",
"# opening the output file",
"print",
"(",
"'Opening the profile in %s...'",
"%",
"profilelog",
")",
"p",
"=",
"pstats",
".",
"Stats",
"(",
"pro... | Parse a profile log and print the result on screen | [
"Parse",
"a",
"profile",
"log",
"and",
"print",
"the",
"result",
"on",
"screen"
] | python | train |
hobson/aima | aima/logic.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L301-L308 | def parse_definite_clause(s):
"Return the antecedents and the consequent of a definite clause."
assert is_definite_clause(s)
if is_symbol(s.op):
return [], s
else:
antecedent, consequent = s.args
return conjuncts(antecedent), consequent | [
"def",
"parse_definite_clause",
"(",
"s",
")",
":",
"assert",
"is_definite_clause",
"(",
"s",
")",
"if",
"is_symbol",
"(",
"s",
".",
"op",
")",
":",
"return",
"[",
"]",
",",
"s",
"else",
":",
"antecedent",
",",
"consequent",
"=",
"s",
".",
"args",
"r... | Return the antecedents and the consequent of a definite clause. | [
"Return",
"the",
"antecedents",
"and",
"the",
"consequent",
"of",
"a",
"definite",
"clause",
"."
] | python | valid |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/builds_api.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/builds_api.py#L377-L401 | def get_ssh_credentials(self, id, **kwargs):
"""
Gets ssh credentials for a build
This GET request is for authenticated users only. The path for the endpoint is not restful to be able to authenticate this GET request only.
This method makes a synchronous HTTP request by default. To make ... | [
"def",
"get_ssh_credentials",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_ssh_credentials_with_ht... | Gets ssh credentials for a build
This GET request is for authenticated users only. The path for the endpoint is not restful to be able to authenticate this GET request only.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` ... | [
"Gets",
"ssh",
"credentials",
"for",
"a",
"build",
"This",
"GET",
"request",
"is",
"for",
"authenticated",
"users",
"only",
".",
"The",
"path",
"for",
"the",
"endpoint",
"is",
"not",
"restful",
"to",
"be",
"able",
"to",
"authenticate",
"this",
"GET",
"requ... | python | train |
ns1/ns1-python | ns1/zones.py | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L228-L238 | def loadRecord(self, domain, rtype, callback=None, errback=None):
"""
Load a high level Record object from a domain within this Zone.
:param str domain: The name of the record to load
:param str rtype: The DNS record type
:rtype: ns1.records.Record
:return: new Record
... | [
"def",
"loadRecord",
"(",
"self",
",",
"domain",
",",
"rtype",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"rec",
"=",
"Record",
"(",
"self",
",",
"domain",
",",
"rtype",
")",
"return",
"rec",
".",
"load",
"(",
"callback",
... | Load a high level Record object from a domain within this Zone.
:param str domain: The name of the record to load
:param str rtype: The DNS record type
:rtype: ns1.records.Record
:return: new Record | [
"Load",
"a",
"high",
"level",
"Record",
"object",
"from",
"a",
"domain",
"within",
"this",
"Zone",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/core/state_machine.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/state_machine.py#L148-L157 | def join(self):
"""Wait for root state to finish execution"""
self._root_state.join()
# execution finished, close execution history log file (if present)
if len(self._execution_histories) > 0:
if self._execution_histories[-1].execution_history_storage is not None:
... | [
"def",
"join",
"(",
"self",
")",
":",
"self",
".",
"_root_state",
".",
"join",
"(",
")",
"# execution finished, close execution history log file (if present)",
"if",
"len",
"(",
"self",
".",
"_execution_histories",
")",
">",
"0",
":",
"if",
"self",
".",
"_execut... | Wait for root state to finish execution | [
"Wait",
"for",
"root",
"state",
"to",
"finish",
"execution"
] | python | train |
ranaroussi/ezibpy | ezibpy/ezibpy.py | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1217-L1299 | def triggerTrailingStops(self, tickerId):
""" trigger waiting trailing stops """
# print('.')
# test
symbol = self.tickerSymbol(tickerId)
price = self.marketData[tickerId]['last'][0]
# contract = self.contracts[tickerId]
if symbol in self.triggerableTrailingStop... | [
"def",
"triggerTrailingStops",
"(",
"self",
",",
"tickerId",
")",
":",
"# print('.')",
"# test",
"symbol",
"=",
"self",
".",
"tickerSymbol",
"(",
"tickerId",
")",
"price",
"=",
"self",
".",
"marketData",
"[",
"tickerId",
"]",
"[",
"'last'",
"]",
"[",
"0",
... | trigger waiting trailing stops | [
"trigger",
"waiting",
"trailing",
"stops"
] | python | train |
persephone-tools/persephone | persephone/preprocess/feat_extract.py | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/feat_extract.py#L188-L230 | def kaldi_pitch(wav_dir: str, feat_dir: str) -> None:
""" Extract Kaldi pitch features. Assumes 16k mono wav files."""
logger.debug("Make wav.scp and pitch.scp files")
# Make wav.scp and pitch.scp files
prefixes = []
for fn in os.listdir(wav_dir):
prefix, ext = os.path.splitext(fn)
... | [
"def",
"kaldi_pitch",
"(",
"wav_dir",
":",
"str",
",",
"feat_dir",
":",
"str",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Make wav.scp and pitch.scp files\"",
")",
"# Make wav.scp and pitch.scp files",
"prefixes",
"=",
"[",
"]",
"for",
"fn",
"in",
... | Extract Kaldi pitch features. Assumes 16k mono wav files. | [
"Extract",
"Kaldi",
"pitch",
"features",
".",
"Assumes",
"16k",
"mono",
"wav",
"files",
"."
] | python | train |
dwkim78/upsilon | upsilon/extract_features/is_period_alias.py | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/is_period_alias.py#L1-L57 | def is_period_alias(period):
"""
Check if a given period is possibly an alias.
Parameters
----------
period : float
A period to test if it is a possible alias or not.
Returns
-------
is_alias : boolean
True if the given period is in a range of period alias.
"""
... | [
"def",
"is_period_alias",
"(",
"period",
")",
":",
"# Based on the period vs periodSN plot of EROS-2 dataset (Kim+ 2014).",
"# Period alias occurs mostly at ~1 and ~30.",
"# Check each 1, 2, 3, 4, 5 factors.",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"6",
")",
":",
"# One-day ... | Check if a given period is possibly an alias.
Parameters
----------
period : float
A period to test if it is a possible alias or not.
Returns
-------
is_alias : boolean
True if the given period is in a range of period alias. | [
"Check",
"if",
"a",
"given",
"period",
"is",
"possibly",
"an",
"alias",
"."
] | python | train |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/input_readers.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L1063-L1087 | def _split_input_from_params(cls, app, namespaces, entity_kind_name,
params, shard_count):
"""Return input reader objects. Helper for split_input."""
# pylint: disable=redefined-outer-name
key_ranges = [] # KeyRanges for all namespaces
for namespace in namespaces:
k... | [
"def",
"_split_input_from_params",
"(",
"cls",
",",
"app",
",",
"namespaces",
",",
"entity_kind_name",
",",
"params",
",",
"shard_count",
")",
":",
"# pylint: disable=redefined-outer-name",
"key_ranges",
"=",
"[",
"]",
"# KeyRanges for all namespaces",
"for",
"namespace... | Return input reader objects. Helper for split_input. | [
"Return",
"input",
"reader",
"objects",
".",
"Helper",
"for",
"split_input",
"."
] | python | train |
the01/python-paps | paps/si/app/sensorServer.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L392-L405 | def stop(self):
"""
Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None
"""
self.debug("()")
super(SensorServer, self).stop()
# No new clients
if self.... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"super",
"(",
"SensorServer",
",",
"self",
")",
".",
"stop",
"(",
")",
"# No new clients",
"if",
"self",
".",
"_multicast_socket",
"is",
"not",
"None",
":",
"self",
".",
... | Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None | [
"Stop",
"the",
"sensor",
"server",
"(",
"soft",
"stop",
"-",
"signal",
"packet",
"loop",
"to",
"stop",
")",
"Warning",
":",
"Is",
"non",
"blocking",
"(",
"server",
"might",
"still",
"do",
"something",
"after",
"this!",
")"
] | python | train |
UCSBarchlab/PyRTL | pyrtl/passes.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/passes.py#L299-L325 | def _remove_unlistened_nets(block):
""" Removes all nets that are not connected to an output wirevector
"""
listened_nets = set()
listened_wires = set()
prev_listened_net_count = 0
def add_to_listened(net):
listened_nets.add(net)
listened_wires.update(net.args)
for a_net i... | [
"def",
"_remove_unlistened_nets",
"(",
"block",
")",
":",
"listened_nets",
"=",
"set",
"(",
")",
"listened_wires",
"=",
"set",
"(",
")",
"prev_listened_net_count",
"=",
"0",
"def",
"add_to_listened",
"(",
"net",
")",
":",
"listened_nets",
".",
"add",
"(",
"n... | Removes all nets that are not connected to an output wirevector | [
"Removes",
"all",
"nets",
"that",
"are",
"not",
"connected",
"to",
"an",
"output",
"wirevector"
] | python | train |
cltk/cltk | cltk/phonology/orthophonology.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/orthophonology.py#L733-L744 | def transcribe(self, text, as_phonemes = False):
'''
Trascribes a text, which is first tokenized for words, then each word is transcribed.
If as_phonemes is true, returns a list of list of phoneme objects,
else returns a string concatenation of the IPA symbols of the phonemes.
'''
phoneme_words = [sel... | [
"def",
"transcribe",
"(",
"self",
",",
"text",
",",
"as_phonemes",
"=",
"False",
")",
":",
"phoneme_words",
"=",
"[",
"self",
".",
"transcribe_word",
"(",
"word",
")",
"for",
"word",
"in",
"self",
".",
"_tokenize",
"(",
"text",
")",
"]",
"if",
"not",
... | Trascribes a text, which is first tokenized for words, then each word is transcribed.
If as_phonemes is true, returns a list of list of phoneme objects,
else returns a string concatenation of the IPA symbols of the phonemes. | [
"Trascribes",
"a",
"text",
"which",
"is",
"first",
"tokenized",
"for",
"words",
"then",
"each",
"word",
"is",
"transcribed",
".",
"If",
"as_phonemes",
"is",
"true",
"returns",
"a",
"list",
"of",
"list",
"of",
"phoneme",
"objects",
"else",
"returns",
"a",
"... | python | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py#L434-L460 | def load_rsa_key(key, key_type, key_encoding):
# (bytes, EncryptionKeyType, KeyEncodingType) -> Any
# TODO: narrow down the output type
"""Load an RSA key object from the provided raw key bytes.
:param bytes key: Raw key bytes to load
:param EncryptionKeyType key_type: Type of key to load
:para... | [
"def",
"load_rsa_key",
"(",
"key",
",",
"key_type",
",",
"key_encoding",
")",
":",
"# (bytes, EncryptionKeyType, KeyEncodingType) -> Any",
"# TODO: narrow down the output type",
"try",
":",
"loader",
"=",
"_RSA_KEY_LOADING",
"[",
"key_type",
"]",
"[",
"key_encoding",
"]",... | Load an RSA key object from the provided raw key bytes.
:param bytes key: Raw key bytes to load
:param EncryptionKeyType key_type: Type of key to load
:param KeyEncodingType key_encoding: Encoding used to serialize ``key``
:returns: Loaded key
:rtype: TODO:
:raises ValueError: if ``key_type`` a... | [
"Load",
"an",
"RSA",
"key",
"object",
"from",
"the",
"provided",
"raw",
"key",
"bytes",
"."
] | python | train |
Cadasta/django-jsonattrs | jsonattrs/fields.py | https://github.com/Cadasta/django-jsonattrs/blob/5149e08ec84da00dd73bd3fe548bc52fd361667c/jsonattrs/fields.py#L123-L129 | def _check_key(self, key):
"""
Ensure key is either in schema's attributes or already set on self.
"""
self.setup_schema()
if key not in self._attrs and key not in self:
raise KeyError(key) | [
"def",
"_check_key",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"setup_schema",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_attrs",
"and",
"key",
"not",
"in",
"self",
":",
"raise",
"KeyError",
"(",
"key",
")"
] | Ensure key is either in schema's attributes or already set on self. | [
"Ensure",
"key",
"is",
"either",
"in",
"schema",
"s",
"attributes",
"or",
"already",
"set",
"on",
"self",
"."
] | python | train |
django-parler/django-parler | parler/views.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L214-L218 | def get_language(self):
"""
Get the language parameter from the current request.
"""
return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object)) | [
"def",
"get_language",
"(",
"self",
")",
":",
"return",
"get_language_parameter",
"(",
"self",
".",
"request",
",",
"self",
".",
"query_language_key",
",",
"default",
"=",
"self",
".",
"get_default_language",
"(",
"object",
"=",
"object",
")",
")"
] | Get the language parameter from the current request. | [
"Get",
"the",
"language",
"parameter",
"from",
"the",
"current",
"request",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/graphs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/graphs.py#L424-L465 | def alter_edge(self, from_index, to_index, to_jimage=None,
new_weight=None, new_edge_properties=None):
"""
Alters either the weight or the edge_properties of
an edge in the StructureGraph.
:param from_index: int
:param to_index: int
:param to_jimage: t... | [
"def",
"alter_edge",
"(",
"self",
",",
"from_index",
",",
"to_index",
",",
"to_jimage",
"=",
"None",
",",
"new_weight",
"=",
"None",
",",
"new_edge_properties",
"=",
"None",
")",
":",
"existing_edges",
"=",
"self",
".",
"graph",
".",
"get_edge_data",
"(",
... | Alters either the weight or the edge_properties of
an edge in the StructureGraph.
:param from_index: int
:param to_index: int
:param to_jimage: tuple
:param new_weight: alter_edge does not require
that weight be altered. As such, by default, this
is None. If weig... | [
"Alters",
"either",
"the",
"weight",
"or",
"the",
"edge_properties",
"of",
"an",
"edge",
"in",
"the",
"StructureGraph",
"."
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/ml/metrics/regression.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/ml/metrics/regression.py#L221-L237 | def residual_histogram(df, col_true, col_pred=None):
"""
Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: s... | [
"def",
"residual_histogram",
"(",
"df",
",",
"col_true",
",",
"col_pred",
"=",
"None",
")",
":",
"if",
"not",
"col_pred",
":",
"col_pred",
"=",
"get_field_name_by_role",
"(",
"df",
",",
"FieldRole",
".",
"PREDICTED_VALUE",
")",
"return",
"_run_evaluation_node",
... | Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str
:param col_true: column name of predicted value, 'predicti... | [
"Compute",
"histogram",
"of",
"residuals",
"of",
"a",
"predicted",
"DataFrame",
"."
] | python | train |
vmlaker/coils | coils/SortedList.py | https://github.com/vmlaker/coils/blob/a3a613b3d661dec010e5879c86e62cbff2519dd0/coils/SortedList.py#L23-L26 | def getCountGT(self, item):
"""Return number of elements greater than *item*."""
index = bisect.bisect_right(self._list, item)
return len(self._list) - index | [
"def",
"getCountGT",
"(",
"self",
",",
"item",
")",
":",
"index",
"=",
"bisect",
".",
"bisect_right",
"(",
"self",
".",
"_list",
",",
"item",
")",
"return",
"len",
"(",
"self",
".",
"_list",
")",
"-",
"index"
] | Return number of elements greater than *item*. | [
"Return",
"number",
"of",
"elements",
"greater",
"than",
"*",
"item",
"*",
"."
] | python | train |
jaraco/irc | irc/client.py | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L403-L439 | def cap(self, subcommand, *args):
"""
Send a CAP command according to `the spec
<http://ircv3.atheme.org/specification/capability-negotiation-3.1>`_.
Arguments:
subcommand -- LS, LIST, REQ, ACK, CLEAR, END
args -- capabilities, if required for given subcommand
... | [
"def",
"cap",
"(",
"self",
",",
"subcommand",
",",
"*",
"args",
")",
":",
"cap_subcommands",
"=",
"set",
"(",
"'LS LIST REQ ACK NAK CLEAR END'",
".",
"split",
"(",
")",
")",
"client_subcommands",
"=",
"set",
"(",
"cap_subcommands",
")",
"-",
"{",
"'NAK'",
... | Send a CAP command according to `the spec
<http://ircv3.atheme.org/specification/capability-negotiation-3.1>`_.
Arguments:
subcommand -- LS, LIST, REQ, ACK, CLEAR, END
args -- capabilities, if required for given subcommand
Example:
.cap('LS')
.... | [
"Send",
"a",
"CAP",
"command",
"according",
"to",
"the",
"spec",
"<http",
":",
"//",
"ircv3",
".",
"atheme",
".",
"org",
"/",
"specification",
"/",
"capability",
"-",
"negotiation",
"-",
"3",
".",
"1",
">",
"_",
"."
] | python | train |
pahaz/sshtunnel | sshtunnel.py | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L263-L266 | def _remove_none_values(dictionary):
""" Remove dictionary keys whose value is None """
return list(map(dictionary.pop,
[i for i in dictionary if dictionary[i] is None])) | [
"def",
"_remove_none_values",
"(",
"dictionary",
")",
":",
"return",
"list",
"(",
"map",
"(",
"dictionary",
".",
"pop",
",",
"[",
"i",
"for",
"i",
"in",
"dictionary",
"if",
"dictionary",
"[",
"i",
"]",
"is",
"None",
"]",
")",
")"
] | Remove dictionary keys whose value is None | [
"Remove",
"dictionary",
"keys",
"whose",
"value",
"is",
"None"
] | python | train |
chop-dbhi/varify-data-warehouse | vdw/pipeline/load.py | https://github.com/chop-dbhi/varify-data-warehouse/blob/1600ee1bc5fae6c68fd03b23624467298570cca8/vdw/pipeline/load.py#L34-L55 | def batch_stream(buff, stream, size=DEFAULT_BATCH_SIZE):
"""Writes a batch of `size` lines to `buff`.
Returns boolean of whether the stream has been exhausted.
"""
buff.truncate(0)
for _ in xrange(size):
if hasattr(stream, 'readline'):
line = stream.readline()
else:
... | [
"def",
"batch_stream",
"(",
"buff",
",",
"stream",
",",
"size",
"=",
"DEFAULT_BATCH_SIZE",
")",
":",
"buff",
".",
"truncate",
"(",
"0",
")",
"for",
"_",
"in",
"xrange",
"(",
"size",
")",
":",
"if",
"hasattr",
"(",
"stream",
",",
"'readline'",
")",
":... | Writes a batch of `size` lines to `buff`.
Returns boolean of whether the stream has been exhausted. | [
"Writes",
"a",
"batch",
"of",
"size",
"lines",
"to",
"buff",
"."
] | python | train |
klmitch/turnstile | turnstile/limits.py | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L146-L150 | def _encode(cls, value):
"""Encode the given value, taking care of '%' and '/'."""
value = json.dumps(value)
return cls._ENC_RE.sub(lambda x: '%%%2x' % ord(x.group(0)), value) | [
"def",
"_encode",
"(",
"cls",
",",
"value",
")",
":",
"value",
"=",
"json",
".",
"dumps",
"(",
"value",
")",
"return",
"cls",
".",
"_ENC_RE",
".",
"sub",
"(",
"lambda",
"x",
":",
"'%%%2x'",
"%",
"ord",
"(",
"x",
".",
"group",
"(",
"0",
")",
")"... | Encode the given value, taking care of '%' and '/'. | [
"Encode",
"the",
"given",
"value",
"taking",
"care",
"of",
"%",
"and",
"/",
"."
] | python | train |
keon/algorithms | algorithms/heap/sliding_window_max.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/heap/sliding_window_max.py#L23-L41 | def max_sliding_window(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums:
return nums
queue = collections.deque()
res = []
for num in nums:
if len(queue) < k:
queue.append(num)
else:
res.append(max(queue... | [
"def",
"max_sliding_window",
"(",
"nums",
",",
"k",
")",
":",
"if",
"not",
"nums",
":",
"return",
"nums",
"queue",
"=",
"collections",
".",
"deque",
"(",
")",
"res",
"=",
"[",
"]",
"for",
"num",
"in",
"nums",
":",
"if",
"len",
"(",
"queue",
")",
... | :type nums: List[int]
:type k: int
:rtype: List[int] | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | python | train |
aaugustin/websockets | src/websockets/headers.py | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L95-L107 | def parse_quoted_string(header: str, pos: int, header_name: str) -> Tuple[str, int]:
"""
Parse a quoted string from ``header`` at the given position.
Return the unquoted value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
"""
match = _quoted_... | [
"def",
"parse_quoted_string",
"(",
"header",
":",
"str",
",",
"pos",
":",
"int",
",",
"header_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"int",
"]",
":",
"match",
"=",
"_quoted_string_re",
".",
"match",
"(",
"header",
",",
"pos",
")",
"i... | Parse a quoted string from ``header`` at the given position.
Return the unquoted value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. | [
"Parse",
"a",
"quoted",
"string",
"from",
"header",
"at",
"the",
"given",
"position",
"."
] | python | train |
xtrementl/focus | focus/plugin/modules/apps.py | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/apps.py#L24-L47 | def _get_process_cwd(pid):
""" Returns the working directory for the provided process identifier.
`pid`
System process identifier.
Returns string or ``None``.
Note this is used as a workaround, since `psutil` isn't consistent on
being able to provide this path in all c... | [
"def",
"_get_process_cwd",
"(",
"pid",
")",
":",
"cmd",
"=",
"'lsof -a -p {0} -d cwd -Fn'",
".",
"format",
"(",
"pid",
")",
"data",
"=",
"common",
".",
"shell_process",
"(",
"cmd",
")",
"if",
"not",
"data",
"is",
"None",
":",
"lines",
"=",
"str",
"(",
... | Returns the working directory for the provided process identifier.
`pid`
System process identifier.
Returns string or ``None``.
Note this is used as a workaround, since `psutil` isn't consistent on
being able to provide this path in all cases, especially MacOS X. | [
"Returns",
"the",
"working",
"directory",
"for",
"the",
"provided",
"process",
"identifier",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L322-L327 | def get_datatype(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str,
column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
raise RuntimeError(_MSG_NO_FLAVOUR) | [
"def",
"get_datatype",
"(",
"cls",
",",
"db",
":",
"DATABASE_SUPPORTER_FWD_REF",
",",
"table",
":",
"str",
",",
"column",
":",
"str",
")",
"->",
"str",
":",
"raise",
"RuntimeError",
"(",
"_MSG_NO_FLAVOUR",
")"
] | Returns database SQL datatype for a column: e.g. VARCHAR. | [
"Returns",
"database",
"SQL",
"datatype",
"for",
"a",
"column",
":",
"e",
".",
"g",
".",
"VARCHAR",
"."
] | python | train |
tanghaibao/goatools | goatools/anno/annoreader_base.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/annoreader_base.py#L164-L175 | def chk_qualifiers(self):
"""Check format of qualifier"""
if self.name == 'id2gos':
return
for ntd in self.associations:
# print(ntd)
qual = ntd.Qualifier
assert isinstance(qual, set), '{NAME}: QUALIFIER MUST BE A LIST: {NT}'.format(
... | [
"def",
"chk_qualifiers",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
"==",
"'id2gos'",
":",
"return",
"for",
"ntd",
"in",
"self",
".",
"associations",
":",
"# print(ntd)",
"qual",
"=",
"ntd",
".",
"Qualifier",
"assert",
"isinstance",
"(",
"qual",
"... | Check format of qualifier | [
"Check",
"format",
"of",
"qualifier"
] | python | train |
RJT1990/pyflux | pyflux/arma/nnar.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/nnar.py#L136-L154 | def _create_latent_variables(self):
""" Creates the model's latent variables
Returns
----------
None (changes model attributes)
"""
no_of_features = self.ar
self.latent_variables.create(name='Bias', dim=[self.layers, self.units], prior=fam.Cauchy(0, 1, transfor... | [
"def",
"_create_latent_variables",
"(",
"self",
")",
":",
"no_of_features",
"=",
"self",
".",
"ar",
"self",
".",
"latent_variables",
".",
"create",
"(",
"name",
"=",
"'Bias'",
",",
"dim",
"=",
"[",
"self",
".",
"layers",
",",
"self",
".",
"units",
"]",
... | Creates the model's latent variables
Returns
----------
None (changes model attributes) | [
"Creates",
"the",
"model",
"s",
"latent",
"variables"
] | python | train |
xtrinch/fcm-django | fcm_django/admin.py | https://github.com/xtrinch/fcm-django/blob/8480d1cf935bfb28e2ad6d86a0abf923c2ecb266/fcm_django/admin.py#L24-L75 | def send_messages(self, request, queryset, bulk=False, data=False):
"""
Provides error handling for DeviceAdmin send_message and
send_bulk_message methods.
"""
ret = []
errors = []
total_failure = 0
for device in queryset:
if bulk:
... | [
"def",
"send_messages",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"bulk",
"=",
"False",
",",
"data",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"errors",
"=",
"[",
"]",
"total_failure",
"=",
"0",
"for",
"device",
"in",
"queryset",
":",
... | Provides error handling for DeviceAdmin send_message and
send_bulk_message methods. | [
"Provides",
"error",
"handling",
"for",
"DeviceAdmin",
"send_message",
"and",
"send_bulk_message",
"methods",
"."
] | python | train |
NiklasRosenstein/py-localimport | localimport.py | https://github.com/NiklasRosenstein/py-localimport/blob/69af71c37f8bd3b2121ec39083dff18a9a2d04a1/localimport.py#L73-L107 | def eval_pth(filename, sitedir, dest=None, imports=None):
'''
Evaluates a `.pth` file (including support for `import` statements), and
appends the result to the list *dest*. If *dest* is #None, it will fall
back to `sys.path`.
If *imports* is specified, it must be a list. `import` statements will not
execu... | [
"def",
"eval_pth",
"(",
"filename",
",",
"sitedir",
",",
"dest",
"=",
"None",
",",
"imports",
"=",
"None",
")",
":",
"if",
"dest",
"is",
"None",
":",
"dest",
"=",
"sys",
".",
"path",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
... | Evaluates a `.pth` file (including support for `import` statements), and
appends the result to the list *dest*. If *dest* is #None, it will fall
back to `sys.path`.
If *imports* is specified, it must be a list. `import` statements will not
executed but instead appended to that list in tuples of
(*filename*, ... | [
"Evaluates",
"a",
".",
"pth",
"file",
"(",
"including",
"support",
"for",
"import",
"statements",
")",
"and",
"appends",
"the",
"result",
"to",
"the",
"list",
"*",
"dest",
"*",
".",
"If",
"*",
"dest",
"*",
"is",
"#None",
"it",
"will",
"fall",
"back",
... | python | train |
msoulier/tftpy | tftpy/TftpPacketTypes.py | https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L399-L408 | def encode(self):
"""Encode the DAT packet based on instance variables, populating
self.buffer, returning self."""
fmt = b"!HH%dsx" % len(self.errmsgs[self.errorcode])
log.debug("encoding ERR packet with fmt %s", fmt)
self.buffer = struct.pack(fmt,
... | [
"def",
"encode",
"(",
"self",
")",
":",
"fmt",
"=",
"b\"!HH%dsx\"",
"%",
"len",
"(",
"self",
".",
"errmsgs",
"[",
"self",
".",
"errorcode",
"]",
")",
"log",
".",
"debug",
"(",
"\"encoding ERR packet with fmt %s\"",
",",
"fmt",
")",
"self",
".",
"buffer",... | Encode the DAT packet based on instance variables, populating
self.buffer, returning self. | [
"Encode",
"the",
"DAT",
"packet",
"based",
"on",
"instance",
"variables",
"populating",
"self",
".",
"buffer",
"returning",
"self",
"."
] | python | train |
gwpy/gwpy | gwpy/types/index.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/types/index.py#L68-L77 | def regular(self):
"""`True` if this index is linearly increasing
"""
try:
return self.info.meta['regular']
except (TypeError, KeyError):
if self.info.meta is None:
self.info.meta = {}
self.info.meta['regular'] = self.is_regular()
... | [
"def",
"regular",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"info",
".",
"meta",
"[",
"'regular'",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
":",
"if",
"self",
".",
"info",
".",
"meta",
"is",
"None",
":",
"self",
".",
... | `True` if this index is linearly increasing | [
"True",
"if",
"this",
"index",
"is",
"linearly",
"increasing"
] | python | train |
IEMLdev/ieml | ieml/grammar/paths/parser/parser.py | https://github.com/IEMLdev/ieml/blob/4c842ba7e6165e2f1b4a4e2e98759f9f33af5f25/ieml/grammar/paths/parser/parser.py#L98-L105 | def p_coordinate(self, p):
""" coordinate : COORD_KIND
| COORD_KIND COORD_INDEX"""
if len(p) == 2:
p[0] = Coordinate(p[1])
else:
p[0] = Coordinate(p[1], int(p[2])) | [
"def",
"p_coordinate",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"Coordinate",
"(",
"p",
"[",
"1",
"]",
")",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"Coordinate",
"(",
"p",
"[",
"1... | coordinate : COORD_KIND
| COORD_KIND COORD_INDEX | [
"coordinate",
":",
"COORD_KIND",
"|",
"COORD_KIND",
"COORD_INDEX"
] | python | test |
bioidiap/gridtk | gridtk/script/jman.py | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L236-L241 | def run_job(args):
"""Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us."""
jm = setup(args)
job_id = int(os.environ['JOB_ID'])
array_id = int(os.environ['SGE_TASK_ID']) if os.environ['SGE_TASK_ID'] != 'undefined' else None
jm.run_jo... | [
"def",
"run_job",
"(",
"args",
")",
":",
"jm",
"=",
"setup",
"(",
"args",
")",
"job_id",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'JOB_ID'",
"]",
")",
"array_id",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'SGE_TASK_ID'",
"]",
")",
"if",
"o... | Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us. | [
"Starts",
"the",
"wrapper",
"script",
"to",
"execute",
"a",
"job",
"interpreting",
"the",
"JOB_ID",
"and",
"SGE_TASK_ID",
"keywords",
"that",
"are",
"set",
"by",
"the",
"grid",
"or",
"by",
"us",
"."
] | python | train |
google/grr | grr/server/grr_response_server/sequential_collection.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/sequential_collection.py#L122-L154 | def Scan(self, after_timestamp=None, include_suffix=False, max_records=None):
"""Scans for stored records.
Scans through the collection, returning stored values ordered by timestamp.
Args:
after_timestamp: If set, only returns values recorded after timestamp.
include_suffix: If true, the times... | [
"def",
"Scan",
"(",
"self",
",",
"after_timestamp",
"=",
"None",
",",
"include_suffix",
"=",
"False",
",",
"max_records",
"=",
"None",
")",
":",
"suffix",
"=",
"None",
"if",
"isinstance",
"(",
"after_timestamp",
",",
"tuple",
")",
":",
"suffix",
"=",
"af... | Scans for stored records.
Scans through the collection, returning stored values ordered by timestamp.
Args:
after_timestamp: If set, only returns values recorded after timestamp.
include_suffix: If true, the timestamps returned are pairs of the form
(micros_since_epoc, suffix) where suffix... | [
"Scans",
"for",
"stored",
"records",
"."
] | python | train |
lucapinello/Haystack | haystack/external.py | https://github.com/lucapinello/Haystack/blob/cc080d741f36cd77b07c0b59d08ea6a4cf0ef2f7/haystack/external.py#L794-L799 | def score(self, seq, fwd='Y'):
"""
m.score(seq, fwd='Y') -- Returns the score of the first w-bases of the sequence, where w is the motif width.
"""
matches, endpoints, scores = self._scan(seq,threshold=-100000,forw_only=fwd)
return scores[0] | [
"def",
"score",
"(",
"self",
",",
"seq",
",",
"fwd",
"=",
"'Y'",
")",
":",
"matches",
",",
"endpoints",
",",
"scores",
"=",
"self",
".",
"_scan",
"(",
"seq",
",",
"threshold",
"=",
"-",
"100000",
",",
"forw_only",
"=",
"fwd",
")",
"return",
"scores... | m.score(seq, fwd='Y') -- Returns the score of the first w-bases of the sequence, where w is the motif width. | [
"m",
".",
"score",
"(",
"seq",
"fwd",
"=",
"Y",
")",
"--",
"Returns",
"the",
"score",
"of",
"the",
"first",
"w",
"-",
"bases",
"of",
"the",
"sequence",
"where",
"w",
"is",
"the",
"motif",
"width",
"."
] | python | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L733-L755 | def highlight_block(self, text):
"""Implement highlight specific for Fortran."""
text = to_text_string(text)
self.setFormat(0, len(text), self.formats["normal"])
match = self.PROG.search(text)
index = 0
while match:
for key, value in list(matc... | [
"def",
"highlight_block",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"normal\"",
"]",
")",
"match",
"=",
... | Implement highlight specific for Fortran. | [
"Implement",
"highlight",
"specific",
"for",
"Fortran",
"."
] | python | train |
mwouts/jupytext | jupytext/jupytext.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/jupytext.py#L237-L263 | def writes(notebook, fmt, version=nbformat.NO_CONVERT, **kwargs):
"""Write a notebook to a string"""
metadata = deepcopy(notebook.metadata)
rearrange_jupytext_metadata(metadata)
fmt = copy(fmt)
fmt = long_form_one_format(fmt, metadata)
ext = fmt['extension']
format_name = fmt.get('format_nam... | [
"def",
"writes",
"(",
"notebook",
",",
"fmt",
",",
"version",
"=",
"nbformat",
".",
"NO_CONVERT",
",",
"*",
"*",
"kwargs",
")",
":",
"metadata",
"=",
"deepcopy",
"(",
"notebook",
".",
"metadata",
")",
"rearrange_jupytext_metadata",
"(",
"metadata",
")",
"f... | Write a notebook to a string | [
"Write",
"a",
"notebook",
"to",
"a",
"string"
] | python | train |
curious-containers/cc-core | cc_core/commons/files.py | https://github.com/curious-containers/cc-core/blob/eaeb03a4366016aff54fcc6953d052ae12ed599b/cc_core/commons/files.py#L155-L163 | def make_file_read_only(file_path):
"""
Removes the write permissions for the given file for owner, groups and others.
:param file_path: The file whose privileges are revoked.
:raise FileNotFoundError: If the given file does not exist.
"""
old_permissions = os.stat(file_path).st_mode
os.chm... | [
"def",
"make_file_read_only",
"(",
"file_path",
")",
":",
"old_permissions",
"=",
"os",
".",
"stat",
"(",
"file_path",
")",
".",
"st_mode",
"os",
".",
"chmod",
"(",
"file_path",
",",
"old_permissions",
"&",
"~",
"WRITE_PERMISSIONS",
")"
] | Removes the write permissions for the given file for owner, groups and others.
:param file_path: The file whose privileges are revoked.
:raise FileNotFoundError: If the given file does not exist. | [
"Removes",
"the",
"write",
"permissions",
"for",
"the",
"given",
"file",
"for",
"owner",
"groups",
"and",
"others",
"."
] | python | train |
dbcli/athenacli | athenacli/sqlexecute.py | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L100-L105 | def tables(self):
'''Yields table names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLES_QUERY)
for row in cur:
yield row | [
"def",
"tables",
"(",
"self",
")",
":",
"with",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"as",
"cur",
":",
"cur",
".",
"execute",
"(",
"self",
".",
"TABLES_QUERY",
")",
"for",
"row",
"in",
"cur",
":",
"yield",
"row"
] | Yields table names. | [
"Yields",
"table",
"names",
"."
] | python | train |
eighthave/pyvendapin | vendapin.py | https://github.com/eighthave/pyvendapin/blob/270c4da5c31ab4a0435660b25b655692fdffcf01/vendapin.py#L225-L234 | def request_status(self):
'''request the status of the card dispenser and return the status code'''
self.sendcommand(Vendapin.REQUEST_STATUS)
# wait for the reply
time.sleep(1)
response = self.receivepacket()
if self.was_packet_accepted(response):
return Venda... | [
"def",
"request_status",
"(",
"self",
")",
":",
"self",
".",
"sendcommand",
"(",
"Vendapin",
".",
"REQUEST_STATUS",
")",
"# wait for the reply",
"time",
".",
"sleep",
"(",
"1",
")",
"response",
"=",
"self",
".",
"receivepacket",
"(",
")",
"if",
"self",
"."... | request the status of the card dispenser and return the status code | [
"request",
"the",
"status",
"of",
"the",
"card",
"dispenser",
"and",
"return",
"the",
"status",
"code"
] | python | train |
twilio/twilio-python | twilio/rest/video/v1/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/video/v1/__init__.py#L46-L52 | def composition_settings(self):
"""
:rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsList
"""
if self._composition_settings is None:
self._composition_settings = CompositionSettingsList(self)
return self._composition_settings | [
"def",
"composition_settings",
"(",
"self",
")",
":",
"if",
"self",
".",
"_composition_settings",
"is",
"None",
":",
"self",
".",
"_composition_settings",
"=",
"CompositionSettingsList",
"(",
"self",
")",
"return",
"self",
".",
"_composition_settings"
] | :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsList | [
":",
"rtype",
":",
"twilio",
".",
"rest",
".",
"video",
".",
"v1",
".",
"composition_settings",
".",
"CompositionSettingsList"
] | python | train |
pyviz/holoviews | holoviews/core/spaces.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/spaces.py#L65-L82 | def grid(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dim... | [
"def",
"grid",
"(",
"self",
",",
"dimensions",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"dimensions",
"=",
"self",
".",
"_valid_dimensions",
"(",
"dimensions",
")",
"if",
"len",
"(",
"dimensions",
")",
"==",
"self",
".",
"ndims",
":",
"with",
... | Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
Grid... | [
"Group",
"by",
"supplied",
"dimension",
"(",
"s",
")",
"and",
"lay",
"out",
"groups",
"in",
"grid"
] | python | train |
gwastro/pycbc-glue | pycbc_glue/gpstime.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/gpstime.py#L67-L72 | def julianDay(year, month, day):
"returns julian day=day since Jan 1 of year"
hr = 12 #make sure you fall into right day, middle is save
t = time.mktime((year, month, day, hr, 0, 0.0, 0, 0, -1))
julDay = time.localtime(t)[7]
return julDay | [
"def",
"julianDay",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"hr",
"=",
"12",
"#make sure you fall into right day, middle is save",
"t",
"=",
"time",
".",
"mktime",
"(",
"(",
"year",
",",
"month",
",",
"day",
",",
"hr",
",",
"0",
",",
"0.0",
",... | returns julian day=day since Jan 1 of year | [
"returns",
"julian",
"day",
"=",
"day",
"since",
"Jan",
"1",
"of",
"year"
] | python | train |
ambitioninc/django-query-builder | querybuilder/query.py | https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/query.py#L1415-L1432 | def build_joins(self):
"""
Generates the sql for the JOIN portion of the query
:return: the JOIN portion of the query
:rtype: str
"""
join_parts = []
# get the sql for each join object
for join_item in self.joins:
join_parts.append(join_item.... | [
"def",
"build_joins",
"(",
"self",
")",
":",
"join_parts",
"=",
"[",
"]",
"# get the sql for each join object",
"for",
"join_item",
"in",
"self",
".",
"joins",
":",
"join_parts",
".",
"append",
"(",
"join_item",
".",
"get_sql",
"(",
")",
")",
"# if there are a... | Generates the sql for the JOIN portion of the query
:return: the JOIN portion of the query
:rtype: str | [
"Generates",
"the",
"sql",
"for",
"the",
"JOIN",
"portion",
"of",
"the",
"query"
] | python | train |
deontologician/restnavigator | restnavigator/halnav.py | https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L63-L71 | def cache(self, link, nav):
'''Stores a navigator in the identity map for the current
api. Can take a link or a bare uri'''
if link is None:
return # We don't cache navigators without a Link
elif hasattr(link, 'uri'):
self.id_map[link.uri] = nav
else:
... | [
"def",
"cache",
"(",
"self",
",",
"link",
",",
"nav",
")",
":",
"if",
"link",
"is",
"None",
":",
"return",
"# We don't cache navigators without a Link",
"elif",
"hasattr",
"(",
"link",
",",
"'uri'",
")",
":",
"self",
".",
"id_map",
"[",
"link",
".",
"uri... | Stores a navigator in the identity map for the current
api. Can take a link or a bare uri | [
"Stores",
"a",
"navigator",
"in",
"the",
"identity",
"map",
"for",
"the",
"current",
"api",
".",
"Can",
"take",
"a",
"link",
"or",
"a",
"bare",
"uri"
] | python | train |
tensorflow/hub | tensorflow_hub/native_module.py | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/native_module.py#L773-L814 | def register_ops_if_needed(graph_ops):
"""Register graph ops absent in op_def_registry, if present in c++ registry.
Args:
graph_ops: set with graph op names to register.
Raises:
RuntimeError: if `graph_ops` contains ops that are not in either python or
c++ registry.
"""
missing_ops = graph_ops... | [
"def",
"register_ops_if_needed",
"(",
"graph_ops",
")",
":",
"missing_ops",
"=",
"graph_ops",
"-",
"set",
"(",
"op_def_registry",
".",
"get_registered_ops",
"(",
")",
".",
"keys",
"(",
")",
")",
"if",
"not",
"missing_ops",
":",
"return",
"p_buffer",
"=",
"c_... | Register graph ops absent in op_def_registry, if present in c++ registry.
Args:
graph_ops: set with graph op names to register.
Raises:
RuntimeError: if `graph_ops` contains ops that are not in either python or
c++ registry. | [
"Register",
"graph",
"ops",
"absent",
"in",
"op_def_registry",
"if",
"present",
"in",
"c",
"++",
"registry",
"."
] | python | train |
CivicSpleen/ambry | ambry/library/filesystem.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/filesystem.py#L86-L92 | def database_dsn(self):
"""Substitute the root dir into the database DSN, for Sqlite"""
if not self._config.library.database:
return 'sqlite:///{root}/library.db'.format(root=self._root)
return self._config.library.database.format(root=self._root) | [
"def",
"database_dsn",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_config",
".",
"library",
".",
"database",
":",
"return",
"'sqlite:///{root}/library.db'",
".",
"format",
"(",
"root",
"=",
"self",
".",
"_root",
")",
"return",
"self",
".",
"_config"... | Substitute the root dir into the database DSN, for Sqlite | [
"Substitute",
"the",
"root",
"dir",
"into",
"the",
"database",
"DSN",
"for",
"Sqlite"
] | python | train |
saltstack/salt | salt/modules/boto_elb.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L357-L380 | def apply_security_groups(name, security_groups, region=None, key=None,
keyid=None, profile=None):
'''
Apply security groups to ELB.
CLI example:
.. code-block:: bash
salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]'
'''
conn = _get_conn(re... | [
"def",
"apply_security_groups",
"(",
"name",
",",
"security_groups",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"ke... | Apply security groups to ELB.
CLI example:
.. code-block:: bash
salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' | [
"Apply",
"security",
"groups",
"to",
"ELB",
"."
] | python | train |
taborlab/FlowCal | FlowCal/plot.py | https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/plot.py#L1259-L1405 | def scatter2d(data_list,
channels=[0,1],
xscale='logicle',
yscale='logicle',
xlabel=None,
ylabel=None,
xlim=None,
ylim=None,
title=None,
color=None,
savefig=None,
**... | [
"def",
"scatter2d",
"(",
"data_list",
",",
"channels",
"=",
"[",
"0",
",",
"1",
"]",
",",
"xscale",
"=",
"'logicle'",
",",
"yscale",
"=",
"'logicle'",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",",
"xlim",
"=",
"None",
",",
"ylim",
"=... | Plot 2D scatter plot from one or more FCSData objects or numpy arrays.
Parameters
----------
data_list : array or FCSData or list of array or list of FCSData
Flow cytometry data to plot.
channels : list of int, list of str
Two channels to use for the plot.
savefig : str, optional
... | [
"Plot",
"2D",
"scatter",
"plot",
"from",
"one",
"or",
"more",
"FCSData",
"objects",
"or",
"numpy",
"arrays",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/works.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/works.py#L192-L200 | def disconnect_signals(self):
"""
Disable the signals within the work. This function reverses the process of `connect_signals`
"""
for task in self:
try:
dispatcher.disconnect(self.on_ok, signal=task.S_OK, sender=task)
except dispatcher.errors.Disp... | [
"def",
"disconnect_signals",
"(",
"self",
")",
":",
"for",
"task",
"in",
"self",
":",
"try",
":",
"dispatcher",
".",
"disconnect",
"(",
"self",
".",
"on_ok",
",",
"signal",
"=",
"task",
".",
"S_OK",
",",
"sender",
"=",
"task",
")",
"except",
"dispatche... | Disable the signals within the work. This function reverses the process of `connect_signals` | [
"Disable",
"the",
"signals",
"within",
"the",
"work",
".",
"This",
"function",
"reverses",
"the",
"process",
"of",
"connect_signals"
] | python | train |
ethereum/pyethereum | ethereum/tools/keys.py | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/keys.py#L161-L184 | def check_keystore_json(jsondata):
"""Check if ``jsondata`` has the structure of a keystore file version 3.
Note that this test is not complete, e.g. it doesn't check key derivation or cipher parameters.
:param jsondata: dictionary containing the data from the json file
:returns: `True` if the data ap... | [
"def",
"check_keystore_json",
"(",
"jsondata",
")",
":",
"if",
"'crypto'",
"not",
"in",
"jsondata",
"and",
"'Crypto'",
"not",
"in",
"jsondata",
":",
"return",
"False",
"if",
"'version'",
"not",
"in",
"jsondata",
":",
"return",
"False",
"if",
"jsondata",
"[",... | Check if ``jsondata`` has the structure of a keystore file version 3.
Note that this test is not complete, e.g. it doesn't check key derivation or cipher parameters.
:param jsondata: dictionary containing the data from the json file
:returns: `True` if the data appears to be valid, otherwise `False` | [
"Check",
"if",
"jsondata",
"has",
"the",
"structure",
"of",
"a",
"keystore",
"file",
"version",
"3",
"."
] | python | train |
pantsbuild/pants | contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/go/src/python/pants/contrib/go/tasks/go_workspace_task.py#L32-L34 | def get_gopath(self, target):
"""Returns the $GOPATH for the given target."""
return os.path.join(self.workdir, target.id) | [
"def",
"get_gopath",
"(",
"self",
",",
"target",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"target",
".",
"id",
")"
] | Returns the $GOPATH for the given target. | [
"Returns",
"the",
"$GOPATH",
"for",
"the",
"given",
"target",
"."
] | python | train |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L88-L106 | def _aha_request(self, cmd, ain=None, param=None, rf=str):
"""Send an AHA request."""
url = 'http://' + self._host + '/webservices/homeautoswitch.lua'
params = {
'switchcmd': cmd,
'sid': self._sid
}
if param:
params['param'] = param
if ... | [
"def",
"_aha_request",
"(",
"self",
",",
"cmd",
",",
"ain",
"=",
"None",
",",
"param",
"=",
"None",
",",
"rf",
"=",
"str",
")",
":",
"url",
"=",
"'http://'",
"+",
"self",
".",
"_host",
"+",
"'/webservices/homeautoswitch.lua'",
"params",
"=",
"{",
"'swi... | Send an AHA request. | [
"Send",
"an",
"AHA",
"request",
"."
] | python | train |
Kozea/cairocffi | cairocffi/patterns.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/patterns.py#L352-L363 | def get_radial_circles(self):
"""Return this radial gradient’s endpoint circles,
each specified as a center coordinate and a radius.
:returns: A ``(cx0, cy0, radius0, cx1, cy1, radius1)`` tuple of floats.
"""
circles = ffi.new('double[6]')
_check_status(cairo.cairo_patt... | [
"def",
"get_radial_circles",
"(",
"self",
")",
":",
"circles",
"=",
"ffi",
".",
"new",
"(",
"'double[6]'",
")",
"_check_status",
"(",
"cairo",
".",
"cairo_pattern_get_radial_circles",
"(",
"self",
".",
"_pointer",
",",
"circles",
"+",
"0",
",",
"circles",
"+... | Return this radial gradient’s endpoint circles,
each specified as a center coordinate and a radius.
:returns: A ``(cx0, cy0, radius0, cx1, cy1, radius1)`` tuple of floats. | [
"Return",
"this",
"radial",
"gradient’s",
"endpoint",
"circles",
"each",
"specified",
"as",
"a",
"center",
"coordinate",
"and",
"a",
"radius",
"."
] | python | train |
romana/vpc-router | vpcrouter/watcher/plugins/configfile.py | https://github.com/romana/vpc-router/blob/d696c2e023f1111ceb61f9c6fbabfafed8e14040/vpcrouter/watcher/plugins/configfile.py#L167-L184 | def get_info(self):
"""
Return plugin information.
"""
return {
self.get_plugin_name() : {
"version" : self.get_version(),
"params" : {
"file" : self.conf['file']
},
"stats" : {
... | [
"def",
"get_info",
"(",
"self",
")",
":",
"return",
"{",
"self",
".",
"get_plugin_name",
"(",
")",
":",
"{",
"\"version\"",
":",
"self",
".",
"get_version",
"(",
")",
",",
"\"params\"",
":",
"{",
"\"file\"",
":",
"self",
".",
"conf",
"[",
"'file'",
"... | Return plugin information. | [
"Return",
"plugin",
"information",
"."
] | python | train |
coleifer/walrus | walrus/containers.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L540-L550 | def add(self, _mapping=None, **kwargs):
"""
Add the given item/score pairs to the ZSet. Arguments are
specified as ``item1, score1, item2, score2...``.
"""
if _mapping is not None:
_mapping.update(kwargs)
mapping = _mapping
else:
mappin... | [
"def",
"add",
"(",
"self",
",",
"_mapping",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_mapping",
"is",
"not",
"None",
":",
"_mapping",
".",
"update",
"(",
"kwargs",
")",
"mapping",
"=",
"_mapping",
"else",
":",
"mapping",
"=",
"_mapping"... | Add the given item/score pairs to the ZSet. Arguments are
specified as ``item1, score1, item2, score2...``. | [
"Add",
"the",
"given",
"item",
"/",
"score",
"pairs",
"to",
"the",
"ZSet",
".",
"Arguments",
"are",
"specified",
"as",
"item1",
"score1",
"item2",
"score2",
"...",
"."
] | python | train |
LionelR/pyair | pyair/xair.py | https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/xair.py#L132-L144 | def _connect(self):
"""
Connexion à la base XAIR
"""
try:
# On passe par Oracle Instant Client avec le TNS ORA_FULL
self.conn = cx_Oracle.connect(self._ORA_FULL)
self.cursor = self.conn.cursor()
print('XAIR: Connexion établie')
exc... | [
"def",
"_connect",
"(",
"self",
")",
":",
"try",
":",
"# On passe par Oracle Instant Client avec le TNS ORA_FULL",
"self",
".",
"conn",
"=",
"cx_Oracle",
".",
"connect",
"(",
"self",
".",
"_ORA_FULL",
")",
"self",
".",
"cursor",
"=",
"self",
".",
"conn",
".",
... | Connexion à la base XAIR | [
"Connexion",
"à",
"la",
"base",
"XAIR"
] | python | valid |
mehmetg/streak_client | streak_client/streak_client.py | https://github.com/mehmetg/streak_client/blob/46575510b4e4163a4a3cc06f7283a1ae377cdce6/streak_client/streak_client.py#L764-L776 | def _get_newsfeeds(self, uri, detail_level = None):
'''General purpose function to get newsfeeds
Args:
uri uri for the feed base
detail_level arguments for req str ['ALL', 'CONDENSED']
return list of feed dicts parse at your convenience
'''
if detail_level:
if detail_level not in ['ALL', 'CON... | [
"def",
"_get_newsfeeds",
"(",
"self",
",",
"uri",
",",
"detail_level",
"=",
"None",
")",
":",
"if",
"detail_level",
":",
"if",
"detail_level",
"not",
"in",
"[",
"'ALL'",
",",
"'CONDENSED'",
"]",
":",
"return",
"requests",
".",
"codes",
".",
"bad_request",
... | General purpose function to get newsfeeds
Args:
uri uri for the feed base
detail_level arguments for req str ['ALL', 'CONDENSED']
return list of feed dicts parse at your convenience | [
"General",
"purpose",
"function",
"to",
"get",
"newsfeeds",
"Args",
":",
"uri",
"uri",
"for",
"the",
"feed",
"base",
"detail_level",
"arguments",
"for",
"req",
"str",
"[",
"ALL",
"CONDENSED",
"]",
"return",
"list",
"of",
"feed",
"dicts",
"parse",
"at",
"yo... | python | train |
miguelgrinberg/python-engineio | engineio/client.py | https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/client.py#L483-L500 | def _ping_loop(self):
"""This background task sends a PING to the server at the requested
interval.
"""
self.pong_received = True
self.ping_loop_event.clear()
while self.state == 'connected':
if not self.pong_received:
self.logger.info(
... | [
"def",
"_ping_loop",
"(",
"self",
")",
":",
"self",
".",
"pong_received",
"=",
"True",
"self",
".",
"ping_loop_event",
".",
"clear",
"(",
")",
"while",
"self",
".",
"state",
"==",
"'connected'",
":",
"if",
"not",
"self",
".",
"pong_received",
":",
"self"... | This background task sends a PING to the server at the requested
interval. | [
"This",
"background",
"task",
"sends",
"a",
"PING",
"to",
"the",
"server",
"at",
"the",
"requested",
"interval",
"."
] | python | train |
LionelAuroux/pyrser | pyrser/ast/state.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L65-L83 | def to_dot(self) -> str:
"""
Provide a '.dot' representation of all State in the register.
"""
txt = ""
txt += "digraph S%d {\n" % id(self)
if self.label is not None:
txt += '\tlabel="%s";\n' % (self.label + '\l').replace('\n', '\l')
txt += "\trankdir=... | [
"def",
"to_dot",
"(",
"self",
")",
"->",
"str",
":",
"txt",
"=",
"\"\"",
"txt",
"+=",
"\"digraph S%d {\\n\"",
"%",
"id",
"(",
"self",
")",
"if",
"self",
".",
"label",
"is",
"not",
"None",
":",
"txt",
"+=",
"'\\tlabel=\"%s\";\\n'",
"%",
"(",
"self",
"... | Provide a '.dot' representation of all State in the register. | [
"Provide",
"a",
".",
"dot",
"representation",
"of",
"all",
"State",
"in",
"the",
"register",
"."
] | python | test |
ska-sa/katcp-python | katcp/resource.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L893-L964 | def wait(self, condition_or_value, timeout=None):
"""Wait for the sensor to satisfy a condition.
Parameters
----------
condition_or_value : obj or callable, or seq of objs or callables
If obj, sensor.value is compared with obj. If callable,
condition_or_value(rea... | [
"def",
"wait",
"(",
"self",
",",
"condition_or_value",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"(",
"isinstance",
"(",
"condition_or_value",
",",
"collections",
".",
"Sequence",
")",
"and",
"not",
"isinstance",
"(",
"condition_or_value",
",",
"basestring"... | Wait for the sensor to satisfy a condition.
Parameters
----------
condition_or_value : obj or callable, or seq of objs or callables
If obj, sensor.value is compared with obj. If callable,
condition_or_value(reading) is called, and must return True if its
cond... | [
"Wait",
"for",
"the",
"sensor",
"to",
"satisfy",
"a",
"condition",
"."
] | python | train |
instacart/jardin | jardin/tools.py | https://github.com/instacart/jardin/blob/007e283b9ccd621b60b86679148cacd9eab7c4e3/jardin/tools.py#L72-L110 | def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
exceptions to check... | [
"def",
"retry",
"(",
"ExceptionToCheck",
",",
"tries",
"=",
"4",
",",
"delay",
"=",
"3",
",",
"backoff",
"=",
"2",
",",
"logger",
"=",
"None",
")",
":",
"def",
"deco_retry",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"f_retry",
"(",
... | Retry calling the decorated function using an exponential backoff.
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
exceptions to check
:type ExceptionToCheck: Exception or tuple
:param tries: number of ti... | [
"Retry",
"calling",
"the",
"decorated",
"function",
"using",
"an",
"exponential",
"backoff",
".",
"original",
"from",
":",
"http",
":",
"//",
"wiki",
".",
"python",
".",
"org",
"/",
"moin",
"/",
"PythonDecoratorLibrary#Retry"
] | python | train |
thombashi/pytablewriter | pytablewriter/writer/text/_text_writer.py | https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_text_writer.py#L179-L201 | def dump(self, output, close_after_write=True):
"""Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
... | [
"def",
"dump",
"(",
"self",
",",
"output",
",",
"close_after_write",
"=",
"True",
")",
":",
"try",
":",
"output",
".",
"write",
"self",
".",
"stream",
"=",
"output",
"except",
"AttributeError",
":",
"self",
".",
"stream",
"=",
"io",
".",
"open",
"(",
... | Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
Defaults to |True|. | [
"Write",
"data",
"to",
"the",
"output",
"with",
"tabular",
"format",
"."
] | python | train |
eventable/vobject | vobject/base.py | https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/base.py#L242-L258 | def serialize(self, buf=None, lineLength=75, validate=True, behavior=None):
"""
Serialize to buf if it exists, otherwise return a string.
Use self.behavior.serialize if behavior exists.
"""
if not behavior:
behavior = self.behavior
if behavior:
i... | [
"def",
"serialize",
"(",
"self",
",",
"buf",
"=",
"None",
",",
"lineLength",
"=",
"75",
",",
"validate",
"=",
"True",
",",
"behavior",
"=",
"None",
")",
":",
"if",
"not",
"behavior",
":",
"behavior",
"=",
"self",
".",
"behavior",
"if",
"behavior",
":... | Serialize to buf if it exists, otherwise return a string.
Use self.behavior.serialize if behavior exists. | [
"Serialize",
"to",
"buf",
"if",
"it",
"exists",
"otherwise",
"return",
"a",
"string",
"."
] | python | train |
rocky/python3-trepan | trepan/processor/command/info_subcmd/pc.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/info_subcmd/pc.py#L42-L73 | def run(self, args):
"""Program counter."""
mainfile = self.core.filename(None)
if self.core.is_running():
curframe = self.proc.curframe
if curframe:
line_no = inspect.getlineno(curframe)
offset = curframe.f_lasti
self.msg(... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"mainfile",
"=",
"self",
".",
"core",
".",
"filename",
"(",
"None",
")",
"if",
"self",
".",
"core",
".",
"is_running",
"(",
")",
":",
"curframe",
"=",
"self",
".",
"proc",
".",
"curframe",
"if",
"... | Program counter. | [
"Program",
"counter",
"."
] | python | test |
lucaskjaero/PyCasia | pycasia/CASIA.py | https://github.com/lucaskjaero/PyCasia/blob/511ddb7809d788fc2c7bc7c1e8600db60bac8152/pycasia/CASIA.py#L57-L70 | def get_all_datasets(self):
"""
Make sure the datasets are present. If not, downloads and extracts them.
Attempts the download five times because the file hosting is unreliable.
:return: True if successful, false otherwise
"""
success = True
for dataset in tqdm(s... | [
"def",
"get_all_datasets",
"(",
"self",
")",
":",
"success",
"=",
"True",
"for",
"dataset",
"in",
"tqdm",
"(",
"self",
".",
"datasets",
")",
":",
"individual_success",
"=",
"self",
".",
"get_dataset",
"(",
"dataset",
")",
"if",
"not",
"individual_success",
... | Make sure the datasets are present. If not, downloads and extracts them.
Attempts the download five times because the file hosting is unreliable.
:return: True if successful, false otherwise | [
"Make",
"sure",
"the",
"datasets",
"are",
"present",
".",
"If",
"not",
"downloads",
"and",
"extracts",
"them",
".",
"Attempts",
"the",
"download",
"five",
"times",
"because",
"the",
"file",
"hosting",
"is",
"unreliable",
".",
":",
"return",
":",
"True",
"i... | python | train |
nugget/python-insteonplm | insteonplm/tools.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/tools.py#L340-L344 | def kpl_off(self, address, group):
"""Get the status of a KPL button."""
addr = Address(address)
device = self.plm.devices[addr.id]
device.states[group].off() | [
"def",
"kpl_off",
"(",
"self",
",",
"address",
",",
"group",
")",
":",
"addr",
"=",
"Address",
"(",
"address",
")",
"device",
"=",
"self",
".",
"plm",
".",
"devices",
"[",
"addr",
".",
"id",
"]",
"device",
".",
"states",
"[",
"group",
"]",
".",
"... | Get the status of a KPL button. | [
"Get",
"the",
"status",
"of",
"a",
"KPL",
"button",
"."
] | python | train |
NLeSC/noodles | noodles/run/xenon/dynamic_pool.py | https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/xenon/dynamic_pool.py#L130-L143 | def wait_until_running(self, callback=None):
"""Waits until the remote worker is running, then calls the callback.
Usually, this method is passed to a different thread; the callback
is then a function patching results through to the result queue."""
status = self.machine.scheduler.wait_u... | [
"def",
"wait_until_running",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"status",
"=",
"self",
".",
"machine",
".",
"scheduler",
".",
"wait_until_running",
"(",
"self",
".",
"job",
",",
"self",
".",
"worker_config",
".",
"time_out",
")",
"if",
... | Waits until the remote worker is running, then calls the callback.
Usually, this method is passed to a different thread; the callback
is then a function patching results through to the result queue. | [
"Waits",
"until",
"the",
"remote",
"worker",
"is",
"running",
"then",
"calls",
"the",
"callback",
".",
"Usually",
"this",
"method",
"is",
"passed",
"to",
"a",
"different",
"thread",
";",
"the",
"callback",
"is",
"then",
"a",
"function",
"patching",
"results"... | python | train |
iterative/dvc | dvc/config.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L32-L43 | def supported_cache_type(types):
"""Checks if link type config option has a valid value.
Args:
types (list/string): type(s) of links that dvc should try out.
"""
if isinstance(types, str):
types = [typ.strip() for typ in types.split(",")]
for typ in types:
if typ not in ["re... | [
"def",
"supported_cache_type",
"(",
"types",
")",
":",
"if",
"isinstance",
"(",
"types",
",",
"str",
")",
":",
"types",
"=",
"[",
"typ",
".",
"strip",
"(",
")",
"for",
"typ",
"in",
"types",
".",
"split",
"(",
"\",\"",
")",
"]",
"for",
"typ",
"in",
... | Checks if link type config option has a valid value.
Args:
types (list/string): type(s) of links that dvc should try out. | [
"Checks",
"if",
"link",
"type",
"config",
"option",
"has",
"a",
"valid",
"value",
"."
] | python | train |
pawelad/pymonzo | src/pymonzo/monzo_api.py | https://github.com/pawelad/pymonzo/blob/b5c8d4f46dcb3a2f475797a8b8ef1c15f6493fb9/src/pymonzo/monzo_api.py#L119-L133 | def _save_token_on_disk(self):
"""Helper function that saves the token on disk"""
token = self._token.copy()
# Client secret is needed for token refreshing and isn't returned
# as a pared of OAuth token by default
token.update(client_secret=self._client_secret)
with cod... | [
"def",
"_save_token_on_disk",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"_token",
".",
"copy",
"(",
")",
"# Client secret is needed for token refreshing and isn't returned",
"# as a pared of OAuth token by default",
"token",
".",
"update",
"(",
"client_secret",
"=... | Helper function that saves the token on disk | [
"Helper",
"function",
"that",
"saves",
"the",
"token",
"on",
"disk"
] | python | train |
helixyte/everest | everest/repositories/rdb/utils.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/repositories/rdb/utils.py#L228-L240 | def inspect(orm_class, attribute_name):
"""
:param attribute_name: name of the mapped attribute to inspect.
:returns: list of 2-tuples containing information about the inspected
attribute (first element: mapped entity attribute kind; second
attribute: mapped entity attribute)... | [
"def",
"inspect",
"(",
"orm_class",
",",
"attribute_name",
")",
":",
"key",
"=",
"(",
"orm_class",
",",
"attribute_name",
")",
"elems",
"=",
"OrmAttributeInspector",
".",
"__cache",
".",
"get",
"(",
"key",
")",
"if",
"elems",
"is",
"None",
":",
"elems",
... | :param attribute_name: name of the mapped attribute to inspect.
:returns: list of 2-tuples containing information about the inspected
attribute (first element: mapped entity attribute kind; second
attribute: mapped entity attribute) | [
":",
"param",
"attribute_name",
":",
"name",
"of",
"the",
"mapped",
"attribute",
"to",
"inspect",
".",
":",
"returns",
":",
"list",
"of",
"2",
"-",
"tuples",
"containing",
"information",
"about",
"the",
"inspected",
"attribute",
"(",
"first",
"element",
":",... | python | train |
jepegit/cellpy | cellpy/readers/dbreader.py | https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/dbreader.py#L430-L470 | def filter_by_col_value(self, column_name,
min_val=None, max_val=None):
"""filters sheet/table by column.
The routine returns the serial-numbers with min_val <= values >= max_val
in the selected column.
Args:
column_name (str): column name.
... | [
"def",
"filter_by_col_value",
"(",
"self",
",",
"column_name",
",",
"min_val",
"=",
"None",
",",
"max_val",
"=",
"None",
")",
":",
"sheet",
"=",
"self",
".",
"table",
"identity",
"=",
"self",
".",
"db_sheet_cols",
".",
"id",
"exists_col_number",
"=",
"self... | filters sheet/table by column.
The routine returns the serial-numbers with min_val <= values >= max_val
in the selected column.
Args:
column_name (str): column name.
min_val (int): minimum value of serial number.
max_val (int): maximum value of serial number... | [
"filters",
"sheet",
"/",
"table",
"by",
"column",
"."
] | python | train |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ambiente.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ambiente.py#L228-L259 | def listar_por_equip(self, equip_id):
"""Lista todos os ambientes por equipamento especifico.
:return: Dicionário com a seguinte estrutura:
::
{'ambiente': {'id': < id_ambiente >,
'link': < link >,
'id_divisao': < id_divisao >,
'nome_divisao': <... | [
"def",
"listar_por_equip",
"(",
"self",
",",
"equip_id",
")",
":",
"if",
"equip_id",
"is",
"None",
":",
"raise",
"InvalidParameterError",
"(",
"u'O id do equipamento não foi informado.')",
"",
"url",
"=",
"'ambiente/equip/'",
"+",
"str",
"(",
"equip_id",
")",
"+",... | Lista todos os ambientes por equipamento especifico.
:return: Dicionário com a seguinte estrutura:
::
{'ambiente': {'id': < id_ambiente >,
'link': < link >,
'id_divisao': < id_divisao >,
'nome_divisao': < nome_divisao >,
'id_ambiente_logico'... | [
"Lista",
"todos",
"os",
"ambientes",
"por",
"equipamento",
"especifico",
"."
] | python | train |
ShawnClake/Apitax | apitax/ah/api/util.py | https://github.com/ShawnClake/Apitax/blob/2eb9c6990d4088b2503c7f13c2a76f8e59606e6d/apitax/ah/api/util.py#L130-L141 | def _deserialize_dict(data, boxed_type):
"""Deserializes a dict and its elements.
:param data: dict to deserialize.
:type data: dict
:param boxed_type: class literal.
:return: deserialized dict.
:rtype: dict
"""
return {k: _deserialize(v, boxed_type)
for k, v in six.iterite... | [
"def",
"_deserialize_dict",
"(",
"data",
",",
"boxed_type",
")",
":",
"return",
"{",
"k",
":",
"_deserialize",
"(",
"v",
",",
"boxed_type",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"data",
")",
"}"
] | Deserializes a dict and its elements.
:param data: dict to deserialize.
:type data: dict
:param boxed_type: class literal.
:return: deserialized dict.
:rtype: dict | [
"Deserializes",
"a",
"dict",
"and",
"its",
"elements",
"."
] | python | train |
scottrice/pysteam | pysteam/steam.py | https://github.com/scottrice/pysteam/blob/1eb2254b5235a053a953e596fa7602d0b110245d/pysteam/steam.py#L12-L43 | def get_steam():
"""
Returns a Steam object representing the current Steam installation on the
users computer. If the user doesn't have Steam installed, returns None.
"""
# Helper function which checks if the potential userdata directory exists
# and returns a new Steam instance with that userdata directory... | [
"def",
"get_steam",
"(",
")",
":",
"# Helper function which checks if the potential userdata directory exists",
"# and returns a new Steam instance with that userdata directory if it does.",
"# If the directory doesnt exist it returns None instead",
"helper",
"=",
"lambda",
"udd",
":",
"St... | Returns a Steam object representing the current Steam installation on the
users computer. If the user doesn't have Steam installed, returns None. | [
"Returns",
"a",
"Steam",
"object",
"representing",
"the",
"current",
"Steam",
"installation",
"on",
"the",
"users",
"computer",
".",
"If",
"the",
"user",
"doesn",
"t",
"have",
"Steam",
"installed",
"returns",
"None",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/db/dfa_db_models.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/db/dfa_db_models.py#L1129-L1141 | def query_topology_db(self, dict_convert=False, **req):
"""Query an entry to the topology DB. """
session = db.get_session()
with session.begin(subtransactions=True):
try:
# Check if entry exists.
topo_disc = session.query(DfaTopologyDb).filter_by(**re... | [
"def",
"query_topology_db",
"(",
"self",
",",
"dict_convert",
"=",
"False",
",",
"*",
"*",
"req",
")",
":",
"session",
"=",
"db",
".",
"get_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
"subtransactions",
"=",
"True",
")",
":",
"try",
":",
... | Query an entry to the topology DB. | [
"Query",
"an",
"entry",
"to",
"the",
"topology",
"DB",
"."
] | python | train |
lcharleux/argiope | argiope/mesh.py | https://github.com/lcharleux/argiope/blob/8170e431362dc760589f7d141090fd133dece259/argiope/mesh.py#L327-L332 | def nvert(self):
"""
Returns the number of vertices of eache element according to its type/
"""
return self.elements.type.argiope.map(
lambda t: ELEMENTS[t].nvert) | [
"def",
"nvert",
"(",
"self",
")",
":",
"return",
"self",
".",
"elements",
".",
"type",
".",
"argiope",
".",
"map",
"(",
"lambda",
"t",
":",
"ELEMENTS",
"[",
"t",
"]",
".",
"nvert",
")"
] | Returns the number of vertices of eache element according to its type/ | [
"Returns",
"the",
"number",
"of",
"vertices",
"of",
"eache",
"element",
"according",
"to",
"its",
"type",
"/"
] | python | test |
waqasbhatti/astrobase | astrobase/checkplot/png.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/png.py#L108-L364 | def _make_periodogram(axes,
lspinfo,
objectinfo,
findercmap,
finderconvolve,
verbose=True,
findercachedir='~/.astrobase/stamp-cache'):
'''Makes periodogram, objectinfo, and finder tile... | [
"def",
"_make_periodogram",
"(",
"axes",
",",
"lspinfo",
",",
"objectinfo",
",",
"findercmap",
",",
"finderconvolve",
",",
"verbose",
"=",
"True",
",",
"findercachedir",
"=",
"'~/.astrobase/stamp-cache'",
")",
":",
"# get the appropriate plot ylabel",
"pgramylabel",
"... | Makes periodogram, objectinfo, and finder tile for `checkplot_png` and
`twolsp_checkplot_png`.
Parameters
----------
axes : matplotlib.axes.Axes object
The Axes object which will contain the plot being made.
lspinfo : dict
Dict containing results from a period-finder in `astrobase... | [
"Makes",
"periodogram",
"objectinfo",
"and",
"finder",
"tile",
"for",
"checkplot_png",
"and",
"twolsp_checkplot_png",
"."
] | python | valid |
apple/turicreate | src/unity/python/turicreate/util/__init__.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L47-L70 | def _get_aws_credentials():
"""
Returns the values stored in the AWS credential environment variables.
Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and
the value stored in the AWS_SECRET_ACCESS_KEY environment variable.
Returns
-------
out : tuple [string]
... | [
"def",
"_get_aws_credentials",
"(",
")",
":",
"if",
"(",
"not",
"'AWS_ACCESS_KEY_ID'",
"in",
"_os",
".",
"environ",
")",
":",
"raise",
"KeyError",
"(",
"'No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.'",
")",
"if",
"(",
"not",
"'AWS_SECRET_A... | Returns the values stored in the AWS credential environment variables.
Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and
the value stored in the AWS_SECRET_ACCESS_KEY environment variable.
Returns
-------
out : tuple [string]
The first string of the tuple is the val... | [
"Returns",
"the",
"values",
"stored",
"in",
"the",
"AWS",
"credential",
"environment",
"variables",
".",
"Returns",
"the",
"value",
"stored",
"in",
"the",
"AWS_ACCESS_KEY_ID",
"environment",
"variable",
"and",
"the",
"value",
"stored",
"in",
"the",
"AWS_SECRET_ACC... | python | train |
dropbox/stone | stone/frontend/ir_generator.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/ir_generator.py#L841-L850 | def _populate_route_attributes(self):
"""
Converts all routes from forward references to complete definitions.
"""
route_schema = self._validate_stone_cfg()
self.api.add_route_schema(route_schema)
for namespace in self.api.namespaces.values():
env = self._get_... | [
"def",
"_populate_route_attributes",
"(",
"self",
")",
":",
"route_schema",
"=",
"self",
".",
"_validate_stone_cfg",
"(",
")",
"self",
".",
"api",
".",
"add_route_schema",
"(",
"route_schema",
")",
"for",
"namespace",
"in",
"self",
".",
"api",
".",
"namespaces... | Converts all routes from forward references to complete definitions. | [
"Converts",
"all",
"routes",
"from",
"forward",
"references",
"to",
"complete",
"definitions",
"."
] | python | train |
LabKey/labkey-api-python | labkey/utils.py | https://github.com/LabKey/labkey-api-python/blob/3c8d393384d7cbb2785f8a7f5fe34007b17a76b8/labkey/utils.py#L114-L137 | def create_server_context(domain, container_path, context_path=None, use_ssl=True, verify_ssl=True, api_key=None):
# type: (str, str, str, bool, bool, str) -> ServerContext
"""
Create a LabKey server context. This context is used to encapsulate properties
about the LabKey server that is being requested ... | [
"def",
"create_server_context",
"(",
"domain",
",",
"container_path",
",",
"context_path",
"=",
"None",
",",
"use_ssl",
"=",
"True",
",",
"verify_ssl",
"=",
"True",
",",
"api_key",
"=",
"None",
")",
":",
"# type: (str, str, str, bool, bool, str) -> ServerContext",
"... | Create a LabKey server context. This context is used to encapsulate properties
about the LabKey server that is being requested against. This includes, but is not limited to,
the domain, container_path, if the server is using SSL, and CSRF token request.
:param domain:
:param container_path:
:param c... | [
"Create",
"a",
"LabKey",
"server",
"context",
".",
"This",
"context",
"is",
"used",
"to",
"encapsulate",
"properties",
"about",
"the",
"LabKey",
"server",
"that",
"is",
"being",
"requested",
"against",
".",
"This",
"includes",
"but",
"is",
"not",
"limited",
... | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/ietf_netconf_monitoring.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/ietf_netconf_monitoring.py#L509-L520 | def get_schema_input_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_schema = ET.Element("get_schema")
config = get_schema
input = ET.SubElement(get_schema, "input")
version = ET.SubElement(input, "version")
version.te... | [
"def",
"get_schema_input_version",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_schema",
"=",
"ET",
".",
"Element",
"(",
"\"get_schema\"",
")",
"config",
"=",
"get_schema",
"input",
"=",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
BD2KGenomics/toil-scripts | src/toil_scripts/rnaseq_unc/rnaseq_unc_pipeline.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/rnaseq_unc/rnaseq_unc_pipeline.py#L479-L524 | def mapsplice(job, job_vars):
"""
Maps RNA-Seq reads to a reference genome.
job_vars: tuple Tuple of dictionaries: input_args and ids
"""
# Unpack variables
input_args, ids = job_vars
work_dir = job.fileStore.getLocalTempDir()
cores = input_args['cpu_count']
sudo = input_args['s... | [
"def",
"mapsplice",
"(",
"job",
",",
"job_vars",
")",
":",
"# Unpack variables",
"input_args",
",",
"ids",
"=",
"job_vars",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"cores",
"=",
"input_args",
"[",
"'cpu_count'",
"]",
"sudo... | Maps RNA-Seq reads to a reference genome.
job_vars: tuple Tuple of dictionaries: input_args and ids | [
"Maps",
"RNA",
"-",
"Seq",
"reads",
"to",
"a",
"reference",
"genome",
"."
] | python | train |
benhoff/vexbot | vexbot/extensions/log.py | https://github.com/benhoff/vexbot/blob/9b844eb20e84eea92a0e7db7d86a90094956c38f/vexbot/extensions/log.py#L5-L25 | def log_level(self,
level: typing.Union[str, int]=None,
*args,
**kwargs) -> typing.Union[None, str]:
"""
Args:
level:
Returns:
The log level if a `level` is passed in
"""
if level is None:
return self.root_logger.getEffectiveLevel()
... | [
"def",
"log_level",
"(",
"self",
",",
"level",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"int",
"]",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Union",
"[",
"None",
",",
"str",
"]",
":",
"if",
"level"... | Args:
level:
Returns:
The log level if a `level` is passed in | [
"Args",
":",
"level",
":"
] | python | train |
chrisjrn/registrasion | registrasion/controllers/credit_note.py | https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/controllers/credit_note.py#L18-L31 | def generate_from_invoice(cls, invoice, value):
''' Generates a credit note of the specified value and pays it against
the given invoice. You need to call InvoiceController.update_status()
to set the status correctly, if appropriate. '''
credit_note = commerce.CreditNote.objects.create(... | [
"def",
"generate_from_invoice",
"(",
"cls",
",",
"invoice",
",",
"value",
")",
":",
"credit_note",
"=",
"commerce",
".",
"CreditNote",
".",
"objects",
".",
"create",
"(",
"invoice",
"=",
"invoice",
",",
"amount",
"=",
"0",
"-",
"value",
",",
"# Credit note... | Generates a credit note of the specified value and pays it against
the given invoice. You need to call InvoiceController.update_status()
to set the status correctly, if appropriate. | [
"Generates",
"a",
"credit",
"note",
"of",
"the",
"specified",
"value",
"and",
"pays",
"it",
"against",
"the",
"given",
"invoice",
".",
"You",
"need",
"to",
"call",
"InvoiceController",
".",
"update_status",
"()",
"to",
"set",
"the",
"status",
"correctly",
"i... | python | test |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/nose/plugins/prof.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/prof.py#L60-L66 | def begin(self):
"""Create profile stats file and load profiler.
"""
if not self.available():
return
self._create_pfile()
self.prof = hotshot.Profile(self.pfile) | [
"def",
"begin",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"available",
"(",
")",
":",
"return",
"self",
".",
"_create_pfile",
"(",
")",
"self",
".",
"prof",
"=",
"hotshot",
".",
"Profile",
"(",
"self",
".",
"pfile",
")"
] | Create profile stats file and load profiler. | [
"Create",
"profile",
"stats",
"file",
"and",
"load",
"profiler",
"."
] | python | test |
thebigmunch/gmusicapi-wrapper | gmusicapi_wrapper/utils.py | https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/utils.py#L398-L418 | def walk_depth(path, max_depth=float('inf')):
"""Walk a directory tree with configurable depth.
Parameters:
path (str): A directory path to walk.
max_depth (int): The depth in the directory tree to walk.
A depth of '0' limits the walk to the top directory.
Default: No limit.
"""
start_level = os.path.a... | [
"def",
"walk_depth",
"(",
"path",
",",
"max_depth",
"=",
"float",
"(",
"'inf'",
")",
")",
":",
"start_level",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
".",
"count",
"(",
"os",
".",
"path",
".",
"sep",
")",
"for",
"dir_entry",
"in",... | Walk a directory tree with configurable depth.
Parameters:
path (str): A directory path to walk.
max_depth (int): The depth in the directory tree to walk.
A depth of '0' limits the walk to the top directory.
Default: No limit. | [
"Walk",
"a",
"directory",
"tree",
"with",
"configurable",
"depth",
"."
] | python | valid |
gwastro/pycbc-glue | pycbc_glue/ligolw/ilwd.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ilwd.py#L157-L227 | def get_ilwdchar_class(tbl_name, col_name, namespace = globals()):
"""
Searches this module's namespace for a subclass of _ilwd.ilwdchar
whose table_name and column_name attributes match those provided.
If a matching subclass is found it is returned; otherwise a new
class is defined, added to this module's namespa... | [
"def",
"get_ilwdchar_class",
"(",
"tbl_name",
",",
"col_name",
",",
"namespace",
"=",
"globals",
"(",
")",
")",
":",
"#",
"# if the class already exists, retrieve and return it",
"#",
"key",
"=",
"(",
"str",
"(",
"tbl_name",
")",
",",
"str",
"(",
"col_name",
"... | Searches this module's namespace for a subclass of _ilwd.ilwdchar
whose table_name and column_name attributes match those provided.
If a matching subclass is found it is returned; otherwise a new
class is defined, added to this module's namespace, and returned.
Example:
>>> process_id = get_ilwdchar_class("proce... | [
"Searches",
"this",
"module",
"s",
"namespace",
"for",
"a",
"subclass",
"of",
"_ilwd",
".",
"ilwdchar",
"whose",
"table_name",
"and",
"column_name",
"attributes",
"match",
"those",
"provided",
".",
"If",
"a",
"matching",
"subclass",
"is",
"found",
"it",
"is",
... | python | train |
dpgaspar/Flask-AppBuilder | flask_appbuilder/views.py | https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/views.py#L268-L276 | def show_item_dict(self, item):
"""Returns a json-able dict for show"""
d = {}
for col in self.show_columns:
v = getattr(item, col)
if not isinstance(v, (int, float, string_types)):
v = str(v)
d[col] = v
return d | [
"def",
"show_item_dict",
"(",
"self",
",",
"item",
")",
":",
"d",
"=",
"{",
"}",
"for",
"col",
"in",
"self",
".",
"show_columns",
":",
"v",
"=",
"getattr",
"(",
"item",
",",
"col",
")",
"if",
"not",
"isinstance",
"(",
"v",
",",
"(",
"int",
",",
... | Returns a json-able dict for show | [
"Returns",
"a",
"json",
"-",
"able",
"dict",
"for",
"show"
] | python | train |
shaypal5/strct | strct/sortedlists/sortedlist.py | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L56-L107 | def find_range_ix_in_section_list(start, end, section_list):
"""Returns the index range all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the lis... | [
"def",
"find_range_ix_in_section_list",
"(",
"start",
",",
"end",
",",
"section_list",
")",
":",
"if",
"start",
">",
"section_list",
"[",
"-",
"1",
"]",
"or",
"end",
"<",
"section_list",
"[",
"0",
"]",
":",
"return",
"[",
"0",
",",
"0",
"]",
"if",
"s... | Returns the index range all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of section... | [
"Returns",
"the",
"index",
"range",
"all",
"sections",
"belonging",
"to",
"the",
"given",
"range",
"."
] | python | train |
zetaops/zengine | zengine/engine.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/engine.py#L410-L418 | def _clear_current_task(self):
"""
Clear tasks related attributes, checks permissions
While switching WF to WF, authentication and permissions are checked for new WF.
"""
self.current.task_name = None
self.current.task_type = None
self.current.task = None | [
"def",
"_clear_current_task",
"(",
"self",
")",
":",
"self",
".",
"current",
".",
"task_name",
"=",
"None",
"self",
".",
"current",
".",
"task_type",
"=",
"None",
"self",
".",
"current",
".",
"task",
"=",
"None"
] | Clear tasks related attributes, checks permissions
While switching WF to WF, authentication and permissions are checked for new WF. | [
"Clear",
"tasks",
"related",
"attributes",
"checks",
"permissions",
"While",
"switching",
"WF",
"to",
"WF",
"authentication",
"and",
"permissions",
"are",
"checked",
"for",
"new",
"WF",
"."
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/DFReader.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/DFReader.py#L166-L171 | def find_time_base(self, gps, first_us_stamp):
'''work out time basis for the log - even newer style'''
t = self._gpsTimeToTime(gps.GWk, gps.GMS)
self.set_timebase(t - gps.TimeUS*0.000001)
# this ensures FMT messages get appropriate timestamp:
self.timestamp = self.timebase + fir... | [
"def",
"find_time_base",
"(",
"self",
",",
"gps",
",",
"first_us_stamp",
")",
":",
"t",
"=",
"self",
".",
"_gpsTimeToTime",
"(",
"gps",
".",
"GWk",
",",
"gps",
".",
"GMS",
")",
"self",
".",
"set_timebase",
"(",
"t",
"-",
"gps",
".",
"TimeUS",
"*",
... | work out time basis for the log - even newer style | [
"work",
"out",
"time",
"basis",
"for",
"the",
"log",
"-",
"even",
"newer",
"style"
] | python | train |
hayd/ctox | ctox/subst.py | https://github.com/hayd/ctox/blob/6f032488ad67170d57d025a830d7b967075b0d7f/ctox/subst.py#L188-L197 | def _replace_config(s, env):
"""[sectionname]optionname"""
m = re.match(r"\[(.*?)\](.*)", s)
if m:
section, option = m.groups()
expanded = env.config.get(section, option)
return '\n'.join([expand_factor_conditions(e, env)
for e in expanded.split("\n")])
... | [
"def",
"_replace_config",
"(",
"s",
",",
"env",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r\"\\[(.*?)\\](.*)\"",
",",
"s",
")",
"if",
"m",
":",
"section",
",",
"option",
"=",
"m",
".",
"groups",
"(",
")",
"expanded",
"=",
"env",
".",
"config",
... | [sectionname]optionname | [
"[",
"sectionname",
"]",
"optionname"
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py#L971-L984 | def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_blade_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
config = logical_chassis_fwdl_status
outpu... | [
"def",
"logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_blade_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"logical_chassis_fwdl_status",
"=",
"ET",
".",
"Element",
"(",
"\"log... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.