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 |
|---|---|---|---|---|---|---|---|---|
hobson/pug-invest | pug/invest/sandbox/sim.py | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L263-L273 | def symbol_bollinger(symbol='GOOG',
start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='close', cleaner=clean_dataframe,
window=20, sigma=1.):
"""Calculate the Bolinger indicator value
>>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NOR... | [
"def",
"symbol_bollinger",
"(",
"symbol",
"=",
"'GOOG'",
",",
"start",
"=",
"datetime",
".",
"datetime",
"(",
"2008",
",",
"1",
",",
"1",
")",
",",
"end",
"=",
"datetime",
".",
"datetime",
"(",
"2009",
",",
"12",
",",
"31",
")",
",",
"price_type",
... | Calculate the Bolinger indicator value
>>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
-1.8782... | [
"Calculate",
"the",
"Bolinger",
"indicator",
"value"
] | python | train |
bram85/topydo | topydo/lib/printers/Ical.py | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/printers/Ical.py#L93-L146 | def _convert_todo(self, p_todo):
""" Converts a Todo instance (Topydo) to an icalendar Todo instance. """
def _get_uid(p_todo):
"""
Gets a unique ID from a todo item, stored by the ical tag. If the
tag is not present, a random value is assigned to it and returned.
... | [
"def",
"_convert_todo",
"(",
"self",
",",
"p_todo",
")",
":",
"def",
"_get_uid",
"(",
"p_todo",
")",
":",
"\"\"\"\n Gets a unique ID from a todo item, stored by the ical tag. If the\n tag is not present, a random value is assigned to it and returned.\n \"... | Converts a Todo instance (Topydo) to an icalendar Todo instance. | [
"Converts",
"a",
"Todo",
"instance",
"(",
"Topydo",
")",
"to",
"an",
"icalendar",
"Todo",
"instance",
"."
] | python | train |
htm-community/menorah | menorah/menorah.py | https://github.com/htm-community/menorah/blob/1991b01eda3f6361b22ed165b4a688ae3fb2deaf/menorah/menorah.py#L225-L237 | def stream(self, handler, whenDone=None):
"""
Fetches data from river streams and feeds them into the given function.
:param handler: (function) passed headers [list] and row [list] of the data
for one time step, for every row of data
"""
self._createConfluence()
headers = ["... | [
"def",
"stream",
"(",
"self",
",",
"handler",
",",
"whenDone",
"=",
"None",
")",
":",
"self",
".",
"_createConfluence",
"(",
")",
"headers",
"=",
"[",
"\"timestamp\"",
"]",
"+",
"self",
".",
"getStreamIds",
"(",
")",
"for",
"row",
"in",
"self",
".",
... | Fetches data from river streams and feeds them into the given function.
:param handler: (function) passed headers [list] and row [list] of the data
for one time step, for every row of data | [
"Fetches",
"data",
"from",
"river",
"streams",
"and",
"feeds",
"them",
"into",
"the",
"given",
"function",
".",
":",
"param",
"handler",
":",
"(",
"function",
")",
"passed",
"headers",
"[",
"list",
"]",
"and",
"row",
"[",
"list",
"]",
"of",
"the",
"dat... | python | train |
saltstack/salt | salt/modules/xapi_virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L114-L121 | def _get_xtool():
'''
Internal, returns xl or xm command line path
'''
for xtool in ['xl', 'xm']:
path = salt.utils.path.which(xtool)
if path is not None:
return path | [
"def",
"_get_xtool",
"(",
")",
":",
"for",
"xtool",
"in",
"[",
"'xl'",
",",
"'xm'",
"]",
":",
"path",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"xtool",
")",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"path"
] | Internal, returns xl or xm command line path | [
"Internal",
"returns",
"xl",
"or",
"xm",
"command",
"line",
"path"
] | python | train |
shoeffner/cvloop | tools/sanitize_ipynb.py | https://github.com/shoeffner/cvloop/blob/3ddd311e9b679d16c8fd36779931380374de343c/tools/sanitize_ipynb.py#L8-L30 | def main():
"""Sanitizes the loaded *.ipynb."""
with open(sys.argv[1], 'r') as nbfile:
notebook = json.load(nbfile)
# remove kernelspec (venvs)
try:
del notebook['metadata']['kernelspec']
except KeyError:
pass
# remove outputs and metadata, set execution counts to None
... | [
"def",
"main",
"(",
")",
":",
"with",
"open",
"(",
"sys",
".",
"argv",
"[",
"1",
"]",
",",
"'r'",
")",
"as",
"nbfile",
":",
"notebook",
"=",
"json",
".",
"load",
"(",
"nbfile",
")",
"# remove kernelspec (venvs)",
"try",
":",
"del",
"notebook",
"[",
... | Sanitizes the loaded *.ipynb. | [
"Sanitizes",
"the",
"loaded",
"*",
".",
"ipynb",
"."
] | python | train |
kmpm/nodemcu-uploader | nodemcu_uploader/uploader.py | https://github.com/kmpm/nodemcu-uploader/blob/557a25f37b1fb4e31a745719e237e42fff192834/nodemcu_uploader/uploader.py#L244-L260 | def read_file(self, filename, destination=''):
"""reading data from device into local file"""
if not destination:
destination = filename
log.info('Transferring %s to %s', filename, destination)
data = self.download_file(filename)
# Just in case, the filename may cont... | [
"def",
"read_file",
"(",
"self",
",",
"filename",
",",
"destination",
"=",
"''",
")",
":",
"if",
"not",
"destination",
":",
"destination",
"=",
"filename",
"log",
".",
"info",
"(",
"'Transferring %s to %s'",
",",
"filename",
",",
"destination",
")",
"data",
... | reading data from device into local file | [
"reading",
"data",
"from",
"device",
"into",
"local",
"file"
] | python | valid |
apache/airflow | airflow/contrib/hooks/bigquery_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L1915-L1927 | def fetchall(self):
"""
Fetch all (remaining) rows of a query result, returning them as a sequence of
sequences (e.g. a list of tuples).
"""
result = []
while True:
one = self.fetchone()
if one is None:
break
else:
... | [
"def",
"fetchall",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"while",
"True",
":",
"one",
"=",
"self",
".",
"fetchone",
"(",
")",
"if",
"one",
"is",
"None",
":",
"break",
"else",
":",
"result",
".",
"append",
"(",
"one",
")",
"return",
"res... | Fetch all (remaining) rows of a query result, returning them as a sequence of
sequences (e.g. a list of tuples). | [
"Fetch",
"all",
"(",
"remaining",
")",
"rows",
"of",
"a",
"query",
"result",
"returning",
"them",
"as",
"a",
"sequence",
"of",
"sequences",
"(",
"e",
".",
"g",
".",
"a",
"list",
"of",
"tuples",
")",
"."
] | python | test |
buildbot/buildbot | master/docs/bbdocs/ext.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/docs/bbdocs/ext.py#L123-L130 | def make_ref_target_directive(ref_type, indextemplates=None, **kwargs):
"""
Create and return a L{BBRefTargetDirective} subclass.
"""
class_vars = dict(ref_type=ref_type, indextemplates=indextemplates)
class_vars.update(kwargs)
return type("BB%sRefTargetDirective" % (ref_type.capitalize(),),
... | [
"def",
"make_ref_target_directive",
"(",
"ref_type",
",",
"indextemplates",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"class_vars",
"=",
"dict",
"(",
"ref_type",
"=",
"ref_type",
",",
"indextemplates",
"=",
"indextemplates",
")",
"class_vars",
".",
"upda... | Create and return a L{BBRefTargetDirective} subclass. | [
"Create",
"and",
"return",
"a",
"L",
"{",
"BBRefTargetDirective",
"}",
"subclass",
"."
] | python | train |
arista-eosplus/pyeapi | pyeapi/api/mlag.py | https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/mlag.py#L151-L163 | def _parse_peer_link(self, config):
"""Scans the config block and parses the peer-link value
Args:
config (str): The config block to scan
Returns:
dict: A dict object that is intended to be merged into the
resource dict
"""
match = re.sea... | [
"def",
"_parse_peer_link",
"(",
"self",
",",
"config",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'peer-link (\\S+)'",
",",
"config",
")",
"value",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"match",
"else",
"None",
"return",
"dict",
"("... | Scans the config block and parses the peer-link value
Args:
config (str): The config block to scan
Returns:
dict: A dict object that is intended to be merged into the
resource dict | [
"Scans",
"the",
"config",
"block",
"and",
"parses",
"the",
"peer",
"-",
"link",
"value"
] | python | train |
JonathanRaiman/pytreebank | pytreebank/download.py | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/download.py#L9-L25 | def delete_paths(paths):
"""
Delete a list of paths that are files or directories.
If a file/directory does not exist, skip it.
Arguments:
----------
paths : list<str>, names of files/directories to remove.
"""
for path in paths:
if exists(path):
if isfile(path):
... | [
"def",
"delete_paths",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"exists",
"(",
"path",
")",
":",
"if",
"isfile",
"(",
"path",
")",
":",
"remove",
"(",
"path",
")",
"else",
":",
"rmtree",
"(",
"path",
")"
] | Delete a list of paths that are files or directories.
If a file/directory does not exist, skip it.
Arguments:
----------
paths : list<str>, names of files/directories to remove. | [
"Delete",
"a",
"list",
"of",
"paths",
"that",
"are",
"files",
"or",
"directories",
".",
"If",
"a",
"file",
"/",
"directory",
"does",
"not",
"exist",
"skip",
"it",
"."
] | python | train |
twisted/mantissa | xmantissa/websession.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L196-L213 | def authenticatedUserForKey(self, key):
"""
Find a persistent session for a user.
@type key: L{bytes}
@param key: The persistent session identifier.
@rtype: L{bytes} or C{None}
@return: The avatar ID the session belongs to, or C{None} if no such
session exis... | [
"def",
"authenticatedUserForKey",
"(",
"self",
",",
"key",
")",
":",
"session",
"=",
"self",
".",
"store",
".",
"findFirst",
"(",
"PersistentSession",
",",
"PersistentSession",
".",
"sessionKey",
"==",
"key",
")",
"if",
"session",
"is",
"None",
":",
"return"... | Find a persistent session for a user.
@type key: L{bytes}
@param key: The persistent session identifier.
@rtype: L{bytes} or C{None}
@return: The avatar ID the session belongs to, or C{None} if no such
session exists. | [
"Find",
"a",
"persistent",
"session",
"for",
"a",
"user",
"."
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/versions.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/versions.py#L209-L229 | def update_lipd_v1_3(d):
"""
Update LiPD v1.2 to v1.3
- Added 'createdBy' key
- Top-level folder inside LiPD archives are named "bag". (No longer <datasetname>)
- .jsonld file is now generically named 'metadata.jsonld' (No longer <datasetname>.lpd )
- All "paleo" and "chron" prefixes are removed... | [
"def",
"update_lipd_v1_3",
"(",
"d",
")",
":",
"# sub routine (recursive): changes all the key names and merges interpretation",
"d",
"=",
"update_lipd_v1_3_names",
"(",
"d",
")",
"# sub routine: changes ensemble and summary table structure",
"d",
"=",
"update_lipd_v1_3_structure",
... | Update LiPD v1.2 to v1.3
- Added 'createdBy' key
- Top-level folder inside LiPD archives are named "bag". (No longer <datasetname>)
- .jsonld file is now generically named 'metadata.jsonld' (No longer <datasetname>.lpd )
- All "paleo" and "chron" prefixes are removed from "paleoMeasurementTable", "paleo... | [
"Update",
"LiPD",
"v1",
".",
"2",
"to",
"v1",
".",
"3",
"-",
"Added",
"createdBy",
"key",
"-",
"Top",
"-",
"level",
"folder",
"inside",
"LiPD",
"archives",
"are",
"named",
"bag",
".",
"(",
"No",
"longer",
"<datasetname",
">",
")",
"-",
".",
"jsonld",... | python | train |
marcolagi/quantulum | quantulum/classifier.py | https://github.com/marcolagi/quantulum/blob/28b697dfa997116c1aa3ef63a3ceb8725bffd24f/quantulum/classifier.py#L57-L66 | def clean_text(text):
"""Clean text for TFIDF."""
new_text = re.sub(ur'\p{P}+', ' ', text)
new_text = [stem(i) for i in new_text.lower().split() if not
re.findall(r'[0-9]', i)]
new_text = ' '.join(new_text)
return new_text | [
"def",
"clean_text",
"(",
"text",
")",
":",
"new_text",
"=",
"re",
".",
"sub",
"(",
"ur'\\p{P}+'",
",",
"' '",
",",
"text",
")",
"new_text",
"=",
"[",
"stem",
"(",
"i",
")",
"for",
"i",
"in",
"new_text",
".",
"lower",
"(",
")",
".",
"split",
"(",... | Clean text for TFIDF. | [
"Clean",
"text",
"for",
"TFIDF",
"."
] | python | train |
sdispater/cleo | cleo/commands/command.py | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L174-L185 | def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
... | [
"def",
"create_question",
"(",
"self",
",",
"question",
",",
"type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"type",
":",
"return",
"Question",
"(",
"question",
",",
"*",
"*",
"kwargs",
")",
"if",
"type",
"==",
"\"choice\"",
":",... | Returns a Question of specified type. | [
"Returns",
"a",
"Question",
"of",
"specified",
"type",
"."
] | python | train |
adafruit/Adafruit_Python_BluefruitLE | Adafruit_BluefruitLE/corebluetooth/gatt.py | https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/gatt.py#L84-L92 | def read_value(self, timeout_sec=TIMEOUT_SEC):
"""Read the value of this characteristic."""
# Kick off a query to read the value of the characteristic, then wait
# for the result to return asyncronously.
self._value_read.clear()
self._device._peripheral.readValueForCharacteristic... | [
"def",
"read_value",
"(",
"self",
",",
"timeout_sec",
"=",
"TIMEOUT_SEC",
")",
":",
"# Kick off a query to read the value of the characteristic, then wait",
"# for the result to return asyncronously.",
"self",
".",
"_value_read",
".",
"clear",
"(",
")",
"self",
".",
"_devic... | Read the value of this characteristic. | [
"Read",
"the",
"value",
"of",
"this",
"characteristic",
"."
] | python | valid |
pytroll/satpy | satpy/multiscene.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/multiscene.py#L175-L188 | def scenes(self):
"""Get list of Scene objects contained in this MultiScene.
.. note::
If the Scenes contained in this object are stored in a
generator (not list or tuple) then accessing this property
will load/iterate through the generator possibly
"""
... | [
"def",
"scenes",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_generator",
":",
"log",
".",
"debug",
"(",
"\"Forcing iteration of generator-like object of Scenes\"",
")",
"self",
".",
"_scenes",
"=",
"list",
"(",
"self",
".",
"_scenes",
")",
"return",
"self",
... | Get list of Scene objects contained in this MultiScene.
.. note::
If the Scenes contained in this object are stored in a
generator (not list or tuple) then accessing this property
will load/iterate through the generator possibly | [
"Get",
"list",
"of",
"Scene",
"objects",
"contained",
"in",
"this",
"MultiScene",
"."
] | python | train |
IndicoDataSolutions/IndicoIo-python | indicoio/custom/custom.py | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/custom/custom.py#L337-L356 | def authorize(self, email, permission_type='read', cloud=None, api_key=None, version=None, **kwargs):
"""
This API endpoint allows you to authorize another user to access your model in a read or write capacity.
Before calling authorize, you must first make sure your model has been registered.
... | [
"def",
"authorize",
"(",
"self",
",",
"email",
",",
"permission_type",
"=",
"'read'",
",",
"cloud",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'permission_type'",
"]",
"=",
... | This API endpoint allows you to authorize another user to access your model in a read or write capacity.
Before calling authorize, you must first make sure your model has been registered.
Inputs:
email - String: The email of the user you would like to share access with.
permission_type ... | [
"This",
"API",
"endpoint",
"allows",
"you",
"to",
"authorize",
"another",
"user",
"to",
"access",
"your",
"model",
"in",
"a",
"read",
"or",
"write",
"capacity",
".",
"Before",
"calling",
"authorize",
"you",
"must",
"first",
"make",
"sure",
"your",
"model",
... | python | train |
PythonCharmers/python-future | src/future/types/newbytes.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newbytes.py#L293-L304 | def splitlines(self, keepends=False):
"""
B.splitlines([keepends]) -> list of lines
Return a list of the lines in B, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
# Py2 str.splitlines() take... | [
"def",
"splitlines",
"(",
"self",
",",
"keepends",
"=",
"False",
")",
":",
"# Py2 str.splitlines() takes keepends as an optional parameter,",
"# not as a keyword argument as in Python 3 bytes.",
"parts",
"=",
"super",
"(",
"newbytes",
",",
"self",
")",
".",
"splitlines",
... | B.splitlines([keepends]) -> list of lines
Return a list of the lines in B, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true. | [
"B",
".",
"splitlines",
"(",
"[",
"keepends",
"]",
")",
"-",
">",
"list",
"of",
"lines"
] | python | train |
timothyb0912/pylogit | pylogit/choice_tools.py | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_tools.py#L585-L715 | def create_design_matrix(long_form,
specification_dict,
alt_id_col,
names=None):
"""
Parameters
----------
long_form : pandas dataframe.
Contains one row for each available alternative, for each observation.
specifica... | [
"def",
"create_design_matrix",
"(",
"long_form",
",",
"specification_dict",
",",
"alt_id_col",
",",
"names",
"=",
"None",
")",
":",
"##########",
"# Check that the arguments meet this functions assumptions.",
"# Fail gracefully if the arguments do not meet the function's requirements... | Parameters
----------
long_form : pandas dataframe.
Contains one row for each available alternative, for each observation.
specification_dict : OrderedDict.
Keys are a proper subset of the columns in `long_form_df`. Values are
either a list or a single string, `"all_diff"` or `"all_s... | [
"Parameters",
"----------",
"long_form",
":",
"pandas",
"dataframe",
".",
"Contains",
"one",
"row",
"for",
"each",
"available",
"alternative",
"for",
"each",
"observation",
".",
"specification_dict",
":",
"OrderedDict",
".",
"Keys",
"are",
"a",
"proper",
"subset",... | python | train |
nerox8664/pytorch2keras | pytorch2keras/reshape_layers.py | https://github.com/nerox8664/pytorch2keras/blob/750eaf747323580e6732d0c5ba9f2f39cb096764/pytorch2keras/reshape_layers.py#L64-L96 | def convert_reshape(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert reshape layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary w... | [
"def",
"convert_reshape",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting reshape ...'",
")",
"if",
"names",
"==",
"'short'",
":",
"tf_name",
"=",
"'RESH'",
"... | Convert reshape layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for kera... | [
"Convert",
"reshape",
"layer",
"."
] | python | valid |
HDI-Project/ballet | ballet/feature.py | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/feature.py#L40-L62 | def _name_estimators(estimators):
"""Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators
"""
def get_name(estimator):
if isinstance(estimator, DelegatingRobustTransformer):
return get_name(estimator._transformer)
return type(estimator).__name__.lo... | [
"def",
"_name_estimators",
"(",
"estimators",
")",
":",
"def",
"get_name",
"(",
"estimator",
")",
":",
"if",
"isinstance",
"(",
"estimator",
",",
"DelegatingRobustTransformer",
")",
":",
"return",
"get_name",
"(",
"estimator",
".",
"_transformer",
")",
"return",... | Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators | [
"Generate",
"names",
"for",
"estimators",
"."
] | python | train |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L499-L510 | def hidden(self):
"""return list of hidden members"""
members = [self.member_info(item["_id"]) for item in self.members()]
result = []
for member in members:
if member['rsInfo'].get('hidden'):
server_id = member['server_id']
result.append({
... | [
"def",
"hidden",
"(",
"self",
")",
":",
"members",
"=",
"[",
"self",
".",
"member_info",
"(",
"item",
"[",
"\"_id\"",
"]",
")",
"for",
"item",
"in",
"self",
".",
"members",
"(",
")",
"]",
"result",
"=",
"[",
"]",
"for",
"member",
"in",
"members",
... | return list of hidden members | [
"return",
"list",
"of",
"hidden",
"members"
] | python | train |
stephenmcd/django-forms-builder | forms_builder/forms/utils.py | https://github.com/stephenmcd/django-forms-builder/blob/89fe03100ec09a6166cc0bf0022399bbbdca6298/forms_builder/forms/utils.py#L61-L67 | def import_attr(path):
"""
Given a a Python dotted path to a variable in a module,
imports the module and returns the variable in it.
"""
module_path, attr_name = path.rsplit(".", 1)
return getattr(import_module(module_path), attr_name) | [
"def",
"import_attr",
"(",
"path",
")",
":",
"module_path",
",",
"attr_name",
"=",
"path",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"return",
"getattr",
"(",
"import_module",
"(",
"module_path",
")",
",",
"attr_name",
")"
] | Given a a Python dotted path to a variable in a module,
imports the module and returns the variable in it. | [
"Given",
"a",
"a",
"Python",
"dotted",
"path",
"to",
"a",
"variable",
"in",
"a",
"module",
"imports",
"the",
"module",
"and",
"returns",
"the",
"variable",
"in",
"it",
"."
] | python | train |
manns/pyspread | pyspread/src/actions/_grid_cell_actions.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_grid_cell_actions.py#L308-L337 | def change_frozen_attr(self):
"""Changes frozen state of cell if there is no selection"""
# Selections are not supported
if self.grid.selection:
statustext = _("Freezing selections is not supported.")
post_command_event(self.main_window, self.StatusBarMsg,
... | [
"def",
"change_frozen_attr",
"(",
"self",
")",
":",
"# Selections are not supported",
"if",
"self",
".",
"grid",
".",
"selection",
":",
"statustext",
"=",
"_",
"(",
"\"Freezing selections is not supported.\"",
")",
"post_command_event",
"(",
"self",
".",
"main_window"... | Changes frozen state of cell if there is no selection | [
"Changes",
"frozen",
"state",
"of",
"cell",
"if",
"there",
"is",
"no",
"selection"
] | python | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L261-L269 | def _is_billing_complete(self):
"""Has the specified `fixed_amount` been billed?
If so, we should not be enacting this RecurringCost.
"""
if self.is_one_off():
return self.get_billed_amount() >= Balance(self.fixed_amount, self.currency)
else:
return False | [
"def",
"_is_billing_complete",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_one_off",
"(",
")",
":",
"return",
"self",
".",
"get_billed_amount",
"(",
")",
">=",
"Balance",
"(",
"self",
".",
"fixed_amount",
",",
"self",
".",
"currency",
")",
"else",
":",... | Has the specified `fixed_amount` been billed?
If so, we should not be enacting this RecurringCost. | [
"Has",
"the",
"specified",
"fixed_amount",
"been",
"billed?"
] | python | train |
thombashi/allpairspy | examples/example2.2.py | https://github.com/thombashi/allpairspy/blob/9dd256d7ccdc1348c5807d4a814294d9c5192293/examples/example2.2.py#L14-L42 | def is_valid_combination(values, names):
dictionary = dict(zip(names, values))
"""
Should return True if combination is valid and False otherwise.
Dictionary that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data... | [
"def",
"is_valid_combination",
"(",
"values",
",",
"names",
")",
":",
"dictionary",
"=",
"dict",
"(",
"zip",
"(",
"names",
",",
"values",
")",
")",
"rules",
"=",
"[",
"# Brand Y does not support Windows 98",
"# Brand X does not work with XP",
"# Contractors are billed... | Should return True if combination is valid and False otherwise.
Dictionary that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it. | [
"Should",
"return",
"True",
"if",
"combination",
"is",
"valid",
"and",
"False",
"otherwise",
"."
] | python | train |
ucsb-cs/submit | submit/models.py | https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/models.py#L663-L666 | def points(self, include_hidden=False):
"""Return the number of points awarded to this submission."""
return sum(x.points for x in self.testable_results
if include_hidden or not x.testable.is_hidden) | [
"def",
"points",
"(",
"self",
",",
"include_hidden",
"=",
"False",
")",
":",
"return",
"sum",
"(",
"x",
".",
"points",
"for",
"x",
"in",
"self",
".",
"testable_results",
"if",
"include_hidden",
"or",
"not",
"x",
".",
"testable",
".",
"is_hidden",
")"
] | Return the number of points awarded to this submission. | [
"Return",
"the",
"number",
"of",
"points",
"awarded",
"to",
"this",
"submission",
"."
] | python | train |
ihucos/plash | opt/plash/lib/py/plash/macros/common.py | https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L161-L167 | def entrypoint_script(*lines):
'write lines to /entrypoint and hint it as default command'
lines = list(lines)
if lines and not lines[0].startswith('#!'):
lines.insert(0, '#!/bin/sh')
return eval([['entrypoint', '/entrypoint'],
['write-script', '/entrypoint'] + lines]) | [
"def",
"entrypoint_script",
"(",
"*",
"lines",
")",
":",
"lines",
"=",
"list",
"(",
"lines",
")",
"if",
"lines",
"and",
"not",
"lines",
"[",
"0",
"]",
".",
"startswith",
"(",
"'#!'",
")",
":",
"lines",
".",
"insert",
"(",
"0",
",",
"'#!/bin/sh'",
"... | write lines to /entrypoint and hint it as default command | [
"write",
"lines",
"to",
"/",
"entrypoint",
"and",
"hint",
"it",
"as",
"default",
"command"
] | python | train |
tanghaibao/jcvi | jcvi/utils/progressbar.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/progressbar.py#L171-L181 | def update(self, pbar):
'Updates the widget with the current SI prefixed speed.'
if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: # =~ 0
scaled = power = 0
else:
speed = pbar.currval / pbar.seconds_elapsed
power = int(math.log(speed, 1000))
... | [
"def",
"update",
"(",
"self",
",",
"pbar",
")",
":",
"if",
"pbar",
".",
"seconds_elapsed",
"<",
"2e-6",
"or",
"pbar",
".",
"currval",
"<",
"2e-6",
":",
"# =~ 0",
"scaled",
"=",
"power",
"=",
"0",
"else",
":",
"speed",
"=",
"pbar",
".",
"currval",
"... | Updates the widget with the current SI prefixed speed. | [
"Updates",
"the",
"widget",
"with",
"the",
"current",
"SI",
"prefixed",
"speed",
"."
] | python | train |
polysquare/jobstamps | jobstamps/jobstamp.py | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L23-L29 | def _safe_mkdir(directory):
"""Create a directory, ignoring errors if it already exists."""
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise error | [
"def",
"_safe_mkdir",
"(",
"directory",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"directory",
")",
"except",
"OSError",
"as",
"error",
":",
"if",
"error",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"error"
] | Create a directory, ignoring errors if it already exists. | [
"Create",
"a",
"directory",
"ignoring",
"errors",
"if",
"it",
"already",
"exists",
"."
] | python | train |
pysal/esda | esda/smoothing.py | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L759-L824 | def by_col(cls, df, e,b, w=None, inplace=False, **kwargs):
"""
Compute smoothing by columns in a dataframe.
Parameters
-----------
df : pandas.DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
... | [
"def",
"by_col",
"(",
"cls",
",",
"df",
",",
"e",
",",
"b",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"inplace",
":",
"new",
"=",
"df",
".",
"copy",
"(",
")",
"cls",
".",
"by_col",
... | Compute smoothing by columns in a dataframe.
Parameters
-----------
df : pandas.DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
the name or names of columns containing event variables to be
... | [
"Compute",
"smoothing",
"by",
"columns",
"in",
"a",
"dataframe",
"."
] | python | train |
mattbierner/blotre-py | blotre.py | https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L358-L365 | def _persist(self):
"""Persist client data."""
with open(self.file, 'w') as f:
json.dump({
'client': self.client,
'creds': self.creds,
'config': self.config
}, f) | [
"def",
"_persist",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"file",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"{",
"'client'",
":",
"self",
".",
"client",
",",
"'creds'",
":",
"self",
".",
"creds",
",",
"'config'"... | Persist client data. | [
"Persist",
"client",
"data",
"."
] | python | train |
striglia/pyramid_swagger | pyramid_swagger/tween.py | https://github.com/striglia/pyramid_swagger/blob/1dbc0b4f23e2e5f4ed575c116f3f7d0e83e30d45/pyramid_swagger/tween.py#L604-L634 | def get_op_for_request(request, route_info, spec):
"""
Find out which operation in the Swagger schema corresponds to the given
pyramid request.
:type request: :class:`pyramid.request.Request`
:type route_info: dict (usually has 'match' and 'route' keys)
:type spec: :class:`bravado_core.spec.Spe... | [
"def",
"get_op_for_request",
"(",
"request",
",",
"route_info",
",",
"spec",
")",
":",
"# pyramid.urldispath.Route",
"route",
"=",
"route_info",
"[",
"'route'",
"]",
"if",
"hasattr",
"(",
"route",
",",
"'path'",
")",
":",
"route_path",
"=",
"route",
".",
"pa... | Find out which operation in the Swagger schema corresponds to the given
pyramid request.
:type request: :class:`pyramid.request.Request`
:type route_info: dict (usually has 'match' and 'route' keys)
:type spec: :class:`bravado_core.spec.Spec`
:rtype: :class:`bravado_core.operation.Operation`
:r... | [
"Find",
"out",
"which",
"operation",
"in",
"the",
"Swagger",
"schema",
"corresponds",
"to",
"the",
"given",
"pyramid",
"request",
"."
] | python | train |
lablup/backend.ai-client-py | src/ai/backend/client/kernel.py | https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/kernel.py#L457-L492 | def stream_execute(self, code: str = '', *,
mode: str = 'query',
opts: dict = None) -> WebSocketResponse:
'''
Executes a code snippet in the streaming mode.
Since the returned websocket represents a run loop, there is no need to
specify *run_... | [
"def",
"stream_execute",
"(",
"self",
",",
"code",
":",
"str",
"=",
"''",
",",
"*",
",",
"mode",
":",
"str",
"=",
"'query'",
",",
"opts",
":",
"dict",
"=",
"None",
")",
"->",
"WebSocketResponse",
":",
"params",
"=",
"{",
"}",
"if",
"self",
".",
"... | Executes a code snippet in the streaming mode.
Since the returned websocket represents a run loop, there is no need to
specify *run_id* explicitly. | [
"Executes",
"a",
"code",
"snippet",
"in",
"the",
"streaming",
"mode",
".",
"Since",
"the",
"returned",
"websocket",
"represents",
"a",
"run",
"loop",
"there",
"is",
"no",
"need",
"to",
"specify",
"*",
"run_id",
"*",
"explicitly",
"."
] | python | train |
vi3k6i5/flashtext | flashtext/keyword.py | https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L395-L411 | def remove_keywords_from_list(self, keyword_list):
"""To remove keywords present in list
Args:
keyword_list (list(str)): List of keywords to remove
Examples:
>>> keyword_processor.remove_keywords_from_list(["java", "python"]})
Raises:
AttributeError:... | [
"def",
"remove_keywords_from_list",
"(",
"self",
",",
"keyword_list",
")",
":",
"if",
"not",
"isinstance",
"(",
"keyword_list",
",",
"list",
")",
":",
"raise",
"AttributeError",
"(",
"\"keyword_list should be a list\"",
")",
"for",
"keyword",
"in",
"keyword_list",
... | To remove keywords present in list
Args:
keyword_list (list(str)): List of keywords to remove
Examples:
>>> keyword_processor.remove_keywords_from_list(["java", "python"]})
Raises:
AttributeError: If `keyword_list` is not a list. | [
"To",
"remove",
"keywords",
"present",
"in",
"list"
] | python | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/tools.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/tools.py#L132-L137 | def load_data(filename):
"""
:rtype : numpy matrix
"""
data = pandas.read_csv(filename, header=None, delimiter='\t', skiprows=9)
return data.as_matrix() | [
"def",
"load_data",
"(",
"filename",
")",
":",
"data",
"=",
"pandas",
".",
"read_csv",
"(",
"filename",
",",
"header",
"=",
"None",
",",
"delimiter",
"=",
"'\\t'",
",",
"skiprows",
"=",
"9",
")",
"return",
"data",
".",
"as_matrix",
"(",
")"
] | :rtype : numpy matrix | [
":",
"rtype",
":",
"numpy",
"matrix"
] | python | train |
staggerpkg/stagger | stagger/fileutil.py | https://github.com/staggerpkg/stagger/blob/6530db14afc5d7d8a4599b7f3b26158fb367d786/stagger/fileutil.py#L51-L61 | def opened(filename, mode):
"Open filename, or do nothing if filename is already an open file object"
if isinstance(filename, str):
file = open(filename, mode)
try:
yield file
finally:
if not file.closed:
file.close()
else:
yield file... | [
"def",
"opened",
"(",
"filename",
",",
"mode",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"file",
"=",
"open",
"(",
"filename",
",",
"mode",
")",
"try",
":",
"yield",
"file",
"finally",
":",
"if",
"not",
"file",
".",
"clos... | Open filename, or do nothing if filename is already an open file object | [
"Open",
"filename",
"or",
"do",
"nothing",
"if",
"filename",
"is",
"already",
"an",
"open",
"file",
"object"
] | python | train |
blockstack/blockstack-core | blockstack/lib/operations/announce.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/announce.py#L39-L75 | def process_announcement( sender_namerec, op, working_dir ):
"""
If the announcement is valid, then immediately record it.
"""
node_config = get_blockstack_opts()
# valid announcement
announce_hash = op['message_hash']
announcer_id = op['announcer_id']
# verify that it came from thi... | [
"def",
"process_announcement",
"(",
"sender_namerec",
",",
"op",
",",
"working_dir",
")",
":",
"node_config",
"=",
"get_blockstack_opts",
"(",
")",
"# valid announcement",
"announce_hash",
"=",
"op",
"[",
"'message_hash'",
"]",
"announcer_id",
"=",
"op",
"[",
"'an... | If the announcement is valid, then immediately record it. | [
"If",
"the",
"announcement",
"is",
"valid",
"then",
"immediately",
"record",
"it",
"."
] | python | train |
mlperf/training | reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/cluster/evaluator/launch_eval.py#L97-L102 | def _append_pairs(new_pairs):
""" Load the pairlist, add new stuff, save it out """
desired_pairs = restore_pairs() or []
desired_pairs += new_pairs
print("Adding {} new pairs, queue has {} pairs".format(len(new_pairs), len(desired_pairs)))
save_pairs(desired_pairs) | [
"def",
"_append_pairs",
"(",
"new_pairs",
")",
":",
"desired_pairs",
"=",
"restore_pairs",
"(",
")",
"or",
"[",
"]",
"desired_pairs",
"+=",
"new_pairs",
"print",
"(",
"\"Adding {} new pairs, queue has {} pairs\"",
".",
"format",
"(",
"len",
"(",
"new_pairs",
")",
... | Load the pairlist, add new stuff, save it out | [
"Load",
"the",
"pairlist",
"add",
"new",
"stuff",
"save",
"it",
"out"
] | python | train |
acorg/dark-matter | dark/titles.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/titles.py#L181-L200 | def coverageInfo(self):
"""
Return information about the bases found at each location in our title
sequence.
@return: A C{dict} whose keys are C{int} subject offsets and whose
values are unsorted lists of (score, base) 2-tuples, giving all the
bases from reads th... | [
"def",
"coverageInfo",
"(",
"self",
")",
":",
"result",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"titleAlignment",
"in",
"self",
":",
"for",
"hsp",
"in",
"titleAlignment",
".",
"hsps",
":",
"score",
"=",
"hsp",
".",
"score",
".",
"score",
"for",
"(... | Return information about the bases found at each location in our title
sequence.
@return: A C{dict} whose keys are C{int} subject offsets and whose
values are unsorted lists of (score, base) 2-tuples, giving all the
bases from reads that matched the subject at subject location,
... | [
"Return",
"information",
"about",
"the",
"bases",
"found",
"at",
"each",
"location",
"in",
"our",
"title",
"sequence",
"."
] | python | train |
CivicSpleen/ambry | ambry/orm/partition.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L841-L860 | def _update_names(self):
"""Update the derived names"""
d = dict(
table=self.table_name,
time=self.time,
space=self.space,
grain=self.grain,
variant=self.variant,
segment=self.segment
)
assert self.dataset
... | [
"def",
"_update_names",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"table",
"=",
"self",
".",
"table_name",
",",
"time",
"=",
"self",
".",
"time",
",",
"space",
"=",
"self",
".",
"space",
",",
"grain",
"=",
"self",
".",
"grain",
",",
"variant",
... | Update the derived names | [
"Update",
"the",
"derived",
"names"
] | python | train |
opendatateam/udata | udata/frontend/helpers.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/helpers.py#L350-L379 | def i18n_alternate_links():
"""Render the <link rel="alternate" hreflang />
if page is in a I18nBlueprint
"""
if (not request.endpoint or
not current_app.url_map.is_endpoint_expecting(request.endpoint,
'lang_code')):
return M... | [
"def",
"i18n_alternate_links",
"(",
")",
":",
"if",
"(",
"not",
"request",
".",
"endpoint",
"or",
"not",
"current_app",
".",
"url_map",
".",
"is_endpoint_expecting",
"(",
"request",
".",
"endpoint",
",",
"'lang_code'",
")",
")",
":",
"return",
"Markup",
"(",... | Render the <link rel="alternate" hreflang />
if page is in a I18nBlueprint | [
"Render",
"the",
"<link",
"rel",
"=",
"alternate",
"hreflang",
"/",
">"
] | python | train |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L5886-L5930 | def convert_objects(self, convert_dates=True, convert_numeric=False,
convert_timedeltas=True, copy=True):
"""
Attempt to infer better dtype for object columns.
.. deprecated:: 0.21.0
Parameters
----------
convert_dates : boolean, default True
... | [
"def",
"convert_objects",
"(",
"self",
",",
"convert_dates",
"=",
"True",
",",
"convert_numeric",
"=",
"False",
",",
"convert_timedeltas",
"=",
"True",
",",
"copy",
"=",
"True",
")",
":",
"msg",
"=",
"(",
"\"convert_objects is deprecated. To re-infer data dtypes fo... | Attempt to infer better dtype for object columns.
.. deprecated:: 0.21.0
Parameters
----------
convert_dates : boolean, default True
If True, convert to date where possible. If 'coerce', force
conversion, with unconvertible values becoming NaT.
convert_n... | [
"Attempt",
"to",
"infer",
"better",
"dtype",
"for",
"object",
"columns",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/tools/monitor/backend_overview.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/monitor/backend_overview.py#L21-L39 | def get_unique_backends():
"""Gets the unique backends that are available.
Returns:
list: Unique available backends.
Raises:
QiskitError: No backends available.
"""
backends = IBMQ.backends()
unique_hardware_backends = []
unique_names = []
for back in backends:
... | [
"def",
"get_unique_backends",
"(",
")",
":",
"backends",
"=",
"IBMQ",
".",
"backends",
"(",
")",
"unique_hardware_backends",
"=",
"[",
"]",
"unique_names",
"=",
"[",
"]",
"for",
"back",
"in",
"backends",
":",
"if",
"back",
".",
"name",
"(",
")",
"not",
... | Gets the unique backends that are available.
Returns:
list: Unique available backends.
Raises:
QiskitError: No backends available. | [
"Gets",
"the",
"unique",
"backends",
"that",
"are",
"available",
"."
] | python | test |
ninuxorg/nodeshot | nodeshot/core/layers/models/layer.py | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/core/layers/models/layer.py#L158-L164 | def node_contained_in_layer_area_validation(self):
"""
if layer defines an area, ensure node coordinates are contained in the area
"""
# if area is a polygon ensure it contains the node
if self.layer and isinstance(self.layer.area, Polygon) and not self.layer.area.contains(self.geometry):
ra... | [
"def",
"node_contained_in_layer_area_validation",
"(",
"self",
")",
":",
"# if area is a polygon ensure it contains the node",
"if",
"self",
".",
"layer",
"and",
"isinstance",
"(",
"self",
".",
"layer",
".",
"area",
",",
"Polygon",
")",
"and",
"not",
"self",
".",
... | if layer defines an area, ensure node coordinates are contained in the area | [
"if",
"layer",
"defines",
"an",
"area",
"ensure",
"node",
"coordinates",
"are",
"contained",
"in",
"the",
"area"
] | python | train |
chaoss/grimoirelab-sortinghat | sortinghat/utils.py | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/utils.py#L33-L84 | def merge_date_ranges(dates):
"""Merge date ranges.
Generator that merges ovelaped data ranges.
Default init and end dates (1900-01-01 and 2100-01-01) are considered range
limits and will be removed when a set of ranges overlap. For example:
* [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)]... | [
"def",
"merge_date_ranges",
"(",
"dates",
")",
":",
"if",
"not",
"dates",
":",
"return",
"sorted_dates",
"=",
"sorted",
"(",
"[",
"sorted",
"(",
"t",
")",
"for",
"t",
"in",
"dates",
"]",
")",
"saved",
"=",
"list",
"(",
"sorted_dates",
"[",
"0",
"]",
... | Merge date ranges.
Generator that merges ovelaped data ranges.
Default init and end dates (1900-01-01 and 2100-01-01) are considered range
limits and will be removed when a set of ranges overlap. For example:
* [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)]
--> (2008-01-01, 2010-01-... | [
"Merge",
"date",
"ranges",
"."
] | python | train |
aiortc/aiortc | aiortc/rtcdtlstransport.py | https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/rtcdtlstransport.py#L378-L459 | async def start(self, remoteParameters):
"""
Start DTLS transport negotiation with the parameters of the remote
DTLS transport.
:param: remoteParameters: An :class:`RTCDtlsParameters`.
"""
assert self._state == State.NEW
assert len(remoteParameters.fingerprints)
... | [
"async",
"def",
"start",
"(",
"self",
",",
"remoteParameters",
")",
":",
"assert",
"self",
".",
"_state",
"==",
"State",
".",
"NEW",
"assert",
"len",
"(",
"remoteParameters",
".",
"fingerprints",
")",
"if",
"self",
".",
"transport",
".",
"role",
"==",
"'... | Start DTLS transport negotiation with the parameters of the remote
DTLS transport.
:param: remoteParameters: An :class:`RTCDtlsParameters`. | [
"Start",
"DTLS",
"transport",
"negotiation",
"with",
"the",
"parameters",
"of",
"the",
"remote",
"DTLS",
"transport",
"."
] | python | train |
kislyuk/argcomplete | argcomplete/my_shlex.py | https://github.com/kislyuk/argcomplete/blob/f9eb0a2354d9e6153f687c463df98c16251d97ed/argcomplete/my_shlex.py#L108-L115 | def pop_source(self):
"Pop the input source stack."
self.instream.close()
(self.infile, self.instream, self.lineno) = self.filestack.popleft()
if self.debug:
print('shlex: popping to %s, line %d' \
% (self.instream, self.lineno))
self.state = ' ' | [
"def",
"pop_source",
"(",
"self",
")",
":",
"self",
".",
"instream",
".",
"close",
"(",
")",
"(",
"self",
".",
"infile",
",",
"self",
".",
"instream",
",",
"self",
".",
"lineno",
")",
"=",
"self",
".",
"filestack",
".",
"popleft",
"(",
")",
"if",
... | Pop the input source stack. | [
"Pop",
"the",
"input",
"source",
"stack",
"."
] | python | train |
avelino/bottle-auth | bottle_auth/core/httputil.py | https://github.com/avelino/bottle-auth/blob/db07e526864aeac05ee68444b47e5db29540ce18/bottle_auth/core/httputil.py#L88-L91 | def get_list(self, name):
"""Returns all values for the given header as a list."""
norm_name = HTTPHeaders._normalize_name(name)
return self._as_list.get(norm_name, []) | [
"def",
"get_list",
"(",
"self",
",",
"name",
")",
":",
"norm_name",
"=",
"HTTPHeaders",
".",
"_normalize_name",
"(",
"name",
")",
"return",
"self",
".",
"_as_list",
".",
"get",
"(",
"norm_name",
",",
"[",
"]",
")"
] | Returns all values for the given header as a list. | [
"Returns",
"all",
"values",
"for",
"the",
"given",
"header",
"as",
"a",
"list",
"."
] | python | test |
angr/angr | angr/state_plugins/symbolic_memory.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/symbolic_memory.py#L96-L114 | def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument
"""
Merge this SimMemory with the other SimMemory
"""
changed_bytes = self._changes_to_merge(others)
l.info("Merging %d bytes", len(changed_bytes))
l.info("... %s has chan... | [
"def",
"merge",
"(",
"self",
",",
"others",
",",
"merge_conditions",
",",
"common_ancestor",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"changed_bytes",
"=",
"self",
".",
"_changes_to_merge",
"(",
"others",
")",
"l",
".",
"info",
"(",
"\"Merging... | Merge this SimMemory with the other SimMemory | [
"Merge",
"this",
"SimMemory",
"with",
"the",
"other",
"SimMemory"
] | python | train |
tcalmant/ipopo | pelix/shell/report.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L576-L620 | def threads_list():
"""
Lists the active threads and their current code line
"""
results = {}
# pylint: disable=W0212
try:
# Extract frames
frames = sys._current_frames()
# Get the thread ID -> Thread mapping
names = threa... | [
"def",
"threads_list",
"(",
")",
":",
"results",
"=",
"{",
"}",
"# pylint: disable=W0212",
"try",
":",
"# Extract frames",
"frames",
"=",
"sys",
".",
"_current_frames",
"(",
")",
"# Get the thread ID -> Thread mapping",
"names",
"=",
"threading",
".",
"_active",
"... | Lists the active threads and their current code line | [
"Lists",
"the",
"active",
"threads",
"and",
"their",
"current",
"code",
"line"
] | python | train |
horazont/aioxmpp | aioxmpp/xso/query.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/query.py#L168-L184 | def eval_bool(self, expr):
"""
Evaluate the expression `expr` and return the truthness of its result.
A result of an expression is said to be true if it contains at least
one value. It has the same semantics as :func:`bool` on sequences.s
"""
result = expr.eval(self)
... | [
"def",
"eval_bool",
"(",
"self",
",",
"expr",
")",
":",
"result",
"=",
"expr",
".",
"eval",
"(",
"self",
")",
"iterator",
"=",
"iter",
"(",
"result",
")",
"try",
":",
"next",
"(",
"iterator",
")",
"except",
"StopIteration",
":",
"return",
"False",
"e... | Evaluate the expression `expr` and return the truthness of its result.
A result of an expression is said to be true if it contains at least
one value. It has the same semantics as :func:`bool` on sequences.s | [
"Evaluate",
"the",
"expression",
"expr",
"and",
"return",
"the",
"truthness",
"of",
"its",
"result",
".",
"A",
"result",
"of",
"an",
"expression",
"is",
"said",
"to",
"be",
"true",
"if",
"it",
"contains",
"at",
"least",
"one",
"value",
".",
"It",
"has",
... | python | train |
Miserlou/django-knockout-modeler | knockout_modeler/ko.py | https://github.com/Miserlou/django-knockout-modeler/blob/714d21cc5ed008f132cea01dbae9f214c2bf1b76/knockout_modeler/ko.py#L190-L205 | def ko(queryset, field_names=None):
"""
Converts a Django QuerySet into a complete Knockout implementation.
"""
try:
koDataString = ko_data(queryset, field_names)
koModelString = ko_model(queryset[0].__class__.__name__, field_names, data=True)
koBindingsString = ko_bindings(quer... | [
"def",
"ko",
"(",
"queryset",
",",
"field_names",
"=",
"None",
")",
":",
"try",
":",
"koDataString",
"=",
"ko_data",
"(",
"queryset",
",",
"field_names",
")",
"koModelString",
"=",
"ko_model",
"(",
"queryset",
"[",
"0",
"]",
".",
"__class__",
".",
"__nam... | Converts a Django QuerySet into a complete Knockout implementation. | [
"Converts",
"a",
"Django",
"QuerySet",
"into",
"a",
"complete",
"Knockout",
"implementation",
"."
] | python | train |
solocompt/plugs-core | plugs_core/utils.py | https://github.com/solocompt/plugs-core/blob/19fd23101fcfdabe657485f0a22e6b63e2b44f9d/plugs_core/utils.py#L27-L42 | def get_db_distinct(queryset, field, func, **params):
"""
Checks if a field / value pair exists in database
and continues generating values until it finds
a one that does not exist
func is the function that generates values and
params is the parameters that function takes
"""
while True... | [
"def",
"get_db_distinct",
"(",
"queryset",
",",
"field",
",",
"func",
",",
"*",
"*",
"params",
")",
":",
"while",
"True",
":",
"try",
":",
"value",
"=",
"func",
"(",
"*",
"*",
"params",
")",
"queryset",
".",
"get",
"(",
"*",
"*",
"{",
"field",
":... | Checks if a field / value pair exists in database
and continues generating values until it finds
a one that does not exist
func is the function that generates values and
params is the parameters that function takes | [
"Checks",
"if",
"a",
"field",
"/",
"value",
"pair",
"exists",
"in",
"database",
"and",
"continues",
"generating",
"values",
"until",
"it",
"finds",
"a",
"one",
"that",
"does",
"not",
"exist"
] | python | train |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L61-L91 | def route(self, resource, view, *urls, **kwargs):
"""Create an api view.
:param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource
:param str view: the view name
:param list urls: the urls of the view
:param dict kwargs: additional options of... | [
"def",
"route",
"(",
"self",
",",
"resource",
",",
"view",
",",
"*",
"urls",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
".",
"view",
"=",
"view",
"url_rule_options",
"=",
"kwargs",
".",
"get",
"(",
"'url_rule_options'",
")",
"or",
"dict",
"(",
")... | Create an api view.
:param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource
:param str view: the view name
:param list urls: the urls of the view
:param dict kwargs: additional options of the route | [
"Create",
"an",
"api",
"view",
"."
] | python | train |
janpipek/physt | physt/binnings.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L182-L192 | def bins(self):
"""Bins in the wider format (as edge pairs)
Returns
-------
bins: np.ndarray
shape=(bin_count, 2)
"""
if self._bins is None:
self._bins = make_bin_array(self.numpy_bins)
return self._bins | [
"def",
"bins",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bins",
"is",
"None",
":",
"self",
".",
"_bins",
"=",
"make_bin_array",
"(",
"self",
".",
"numpy_bins",
")",
"return",
"self",
".",
"_bins"
] | Bins in the wider format (as edge pairs)
Returns
-------
bins: np.ndarray
shape=(bin_count, 2) | [
"Bins",
"in",
"the",
"wider",
"format",
"(",
"as",
"edge",
"pairs",
")"
] | python | train |
CalebBell/thermo | thermo/phase_change.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/phase_change.py#L1094-L1155 | def load_all_methods(self):
r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,
and :obj:`all_methods` as a set of methods for which t... | [
"def",
"load_all_methods",
"(",
"self",
")",
":",
"methods",
"=",
"[",
"]",
"Tmins",
",",
"Tmaxs",
"=",
"[",
"]",
",",
"[",
"]",
"if",
"has_CoolProp",
"and",
"self",
".",
"CASRN",
"in",
"coolprop_dict",
":",
"methods",
".",
"append",
"(",
"COOLPROP",
... | r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,
and :obj:`all_methods` as a set of methods for which the data exists for.
Called ... | [
"r",
"Method",
"which",
"picks",
"out",
"coefficients",
"for",
"the",
"specified",
"chemical",
"from",
"the",
"various",
"dictionaries",
"and",
"DataFrames",
"storing",
"it",
".",
"All",
"data",
"is",
"stored",
"as",
"attributes",
".",
"This",
"method",
"also"... | python | valid |
istresearch/scrapy-cluster | rest/rest_service.py | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L347-L365 | def _setup_redis(self):
"""Returns a Redis Client"""
if not self.closed:
try:
self.logger.debug("Creating redis connection to host " +
str(self.settings['REDIS_HOST']))
self.redis_conn = redis.StrictRedis(host=self.settings['R... | [
"def",
"_setup_redis",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"closed",
":",
"try",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Creating redis connection to host \"",
"+",
"str",
"(",
"self",
".",
"settings",
"[",
"'REDIS_HOST'",
"]",
")",
... | Returns a Redis Client | [
"Returns",
"a",
"Redis",
"Client"
] | python | train |
aiogram/aiogram | aiogram/bot/bot.py | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L850-L885 | async def send_poll(self, chat_id: typing.Union[base.Integer, base.String],
question: base.String,
options: typing.List[base.String],
disable_notification: typing.Optional[base.Boolean],
reply_to_message_id: typing.Union[bas... | [
"async",
"def",
"send_poll",
"(",
"self",
",",
"chat_id",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"base",
".",
"String",
"]",
",",
"question",
":",
"base",
".",
"String",
",",
"options",
":",
"typing",
".",
"List",
"[",
"base",... | Use this method to send a native poll. A native poll can't be sent to a private chat.
On success, the sent Message is returned.
:param chat_id: Unique identifier for the target chat
or username of the target channel (in the format @channelusername).
A native poll can't be sent t... | [
"Use",
"this",
"method",
"to",
"send",
"a",
"native",
"poll",
".",
"A",
"native",
"poll",
"can",
"t",
"be",
"sent",
"to",
"a",
"private",
"chat",
".",
"On",
"success",
"the",
"sent",
"Message",
"is",
"returned",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/lstm.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/lstm.py#L486-L498 | def lstm_area_attention_base():
"""Hparams for LSTM with area attention."""
hparams = lstm_luong_attention()
hparams.batch_size = 16384
hparams.num_hidden_layers = 2
hparams.hidden_size = 1024
hparams.num_heads = 4
hparams.dropout = 0.2
hparams.learning_rate = 0.1
hparams.max_area_width = 2
hparams.... | [
"def",
"lstm_area_attention_base",
"(",
")",
":",
"hparams",
"=",
"lstm_luong_attention",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"16384",
"hparams",
".",
"num_hidden_layers",
"=",
"2",
"hparams",
".",
"hidden_size",
"=",
"1024",
"hparams",
".",
"num_heads"... | Hparams for LSTM with area attention. | [
"Hparams",
"for",
"LSTM",
"with",
"area",
"attention",
"."
] | python | train |
wummel/linkchecker | linkcheck/network/iputil.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/network/iputil.py#L104-L111 | def is_valid_ipv4 (ip):
"""
Return True if given ip is a valid IPv4 address.
"""
if not _ipv4_re.match(ip):
return False
a, b, c, d = [int(i) for i in ip.split(".")]
return a <= 255 and b <= 255 and c <= 255 and d <= 255 | [
"def",
"is_valid_ipv4",
"(",
"ip",
")",
":",
"if",
"not",
"_ipv4_re",
".",
"match",
"(",
"ip",
")",
":",
"return",
"False",
"a",
",",
"b",
",",
"c",
",",
"d",
"=",
"[",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"ip",
".",
"split",
"(",
"\".\"",... | Return True if given ip is a valid IPv4 address. | [
"Return",
"True",
"if",
"given",
"ip",
"is",
"a",
"valid",
"IPv4",
"address",
"."
] | python | train |
trailofbits/manticore | manticore/native/cpu/abstractcpu.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L803-L812 | def pop_int(self, force=False):
"""
Read a value from the stack and increment the stack pointer.
:param force: whether to ignore memory permissions
:return: Value read
"""
value = self.read_int(self.STACK, force=force)
self.STACK += self.address_bit_size // 8
... | [
"def",
"pop_int",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"value",
"=",
"self",
".",
"read_int",
"(",
"self",
".",
"STACK",
",",
"force",
"=",
"force",
")",
"self",
".",
"STACK",
"+=",
"self",
".",
"address_bit_size",
"//",
"8",
"return",
... | Read a value from the stack and increment the stack pointer.
:param force: whether to ignore memory permissions
:return: Value read | [
"Read",
"a",
"value",
"from",
"the",
"stack",
"and",
"increment",
"the",
"stack",
"pointer",
"."
] | python | valid |
hyperledger/sawtooth-core | cli/sawtooth_cli/rest_client.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/cli/sawtooth_cli/rest_client.py#L166-L209 | def _submit_request(self, url, params=None, data=None, headers=None,
method="GET"):
"""Submits the given request, and handles the errors appropriately.
Args:
url (str): the request to send.
params (dict): params to be passed along to get/post
... | [
"def",
"_submit_request",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"method",
"=",
"\"GET\"",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"if",
"self... | Submits the given request, and handles the errors appropriately.
Args:
url (str): the request to send.
params (dict): params to be passed along to get/post
data (bytes): the data to include in the request.
headers (dict): the headers to include in the request.
... | [
"Submits",
"the",
"given",
"request",
"and",
"handles",
"the",
"errors",
"appropriately",
"."
] | python | train |
ciena/afkak | afkak/kafkacodec.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L624-L652 | def create_message_set(requests, codec=CODEC_NONE):
"""
Create a message set from a list of requests.
Each request can have a list of messages and its own key. If codec is
:data:`CODEC_NONE`, return a list of raw Kafka messages. Otherwise, return
a list containing a single codec-encoded message.
... | [
"def",
"create_message_set",
"(",
"requests",
",",
"codec",
"=",
"CODEC_NONE",
")",
":",
"msglist",
"=",
"[",
"]",
"for",
"req",
"in",
"requests",
":",
"msglist",
".",
"extend",
"(",
"[",
"create_message",
"(",
"m",
",",
"key",
"=",
"req",
".",
"key",
... | Create a message set from a list of requests.
Each request can have a list of messages and its own key. If codec is
:data:`CODEC_NONE`, return a list of raw Kafka messages. Otherwise, return
a list containing a single codec-encoded message.
:param codec:
The encoding for the message set, one ... | [
"Create",
"a",
"message",
"set",
"from",
"a",
"list",
"of",
"requests",
"."
] | python | train |
twisted/txaws | txaws/s3/client.py | https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/s3/client.py#L453-L482 | def copy_object(self, source_bucket, source_object_name, dest_bucket=None,
dest_object_name=None, metadata={}, amz_headers={}):
"""
Copy an object stored in S3 from a source bucket to a destination
bucket.
@param source_bucket: The S3 bucket to copy the object from.
... | [
"def",
"copy_object",
"(",
"self",
",",
"source_bucket",
",",
"source_object_name",
",",
"dest_bucket",
"=",
"None",
",",
"dest_object_name",
"=",
"None",
",",
"metadata",
"=",
"{",
"}",
",",
"amz_headers",
"=",
"{",
"}",
")",
":",
"dest_bucket",
"=",
"des... | Copy an object stored in S3 from a source bucket to a destination
bucket.
@param source_bucket: The S3 bucket to copy the object from.
@param source_object_name: The name of the object to copy.
@param dest_bucket: Optionally, the S3 bucket to copy the object to.
Defaults to ... | [
"Copy",
"an",
"object",
"stored",
"in",
"S3",
"from",
"a",
"source",
"bucket",
"to",
"a",
"destination",
"bucket",
"."
] | python | train |
vtkiorg/vtki | vtki/plotting.py | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2144-L2147 | def remove_scalar_bar(self):
""" Removes scalar bar """
if hasattr(self, 'scalar_bar'):
self.remove_actor(self.scalar_bar, reset_camera=False) | [
"def",
"remove_scalar_bar",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'scalar_bar'",
")",
":",
"self",
".",
"remove_actor",
"(",
"self",
".",
"scalar_bar",
",",
"reset_camera",
"=",
"False",
")"
] | Removes scalar bar | [
"Removes",
"scalar",
"bar"
] | python | train |
ThomasChiroux/attowiki | src/attowiki/git_tools.py | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L136-L153 | def commit_history(filename):
"""Retrieve the commit history for a given filename.
Keyword Arguments:
:filename: (str) -- full name of the file
Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list
"""
result = []
repo = Repo()... | [
"def",
"commit_history",
"(",
"filename",
")",
":",
"result",
"=",
"[",
"]",
"repo",
"=",
"Repo",
"(",
")",
"for",
"commit",
"in",
"repo",
".",
"head",
".",
"commit",
".",
"iter_parents",
"(",
"paths",
"=",
"_delta_dir",
"(",
")",
"+",
"filename",
")... | Retrieve the commit history for a given filename.
Keyword Arguments:
:filename: (str) -- full name of the file
Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list | [
"Retrieve",
"the",
"commit",
"history",
"for",
"a",
"given",
"filename",
"."
] | python | train |
jonathf/chaospy | chaospy/quad/generator.py | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/generator.py#L9-L46 | def rule_generator(*funcs):
"""
Constructor for creating multivariate quadrature generator.
Args:
funcs (:py:data:typing.Callable):
One dimensional integration rule where each rule returns
``abscissas`` and ``weights`` as one dimensional arrays. They must
take on... | [
"def",
"rule_generator",
"(",
"*",
"funcs",
")",
":",
"dim",
"=",
"len",
"(",
"funcs",
")",
"tensprod_rule",
"=",
"create_tensorprod_function",
"(",
"funcs",
")",
"assert",
"hasattr",
"(",
"tensprod_rule",
",",
"\"__call__\"",
")",
"mv_rule",
"=",
"create_mv_r... | Constructor for creating multivariate quadrature generator.
Args:
funcs (:py:data:typing.Callable):
One dimensional integration rule where each rule returns
``abscissas`` and ``weights`` as one dimensional arrays. They must
take one positional argument ``order``.
Re... | [
"Constructor",
"for",
"creating",
"multivariate",
"quadrature",
"generator",
"."
] | python | train |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L294-L321 | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via distance
after superposition
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.n... | [
"def",
"partial_transform",
"(",
"self",
",",
"traj",
")",
":",
"if",
"self",
".",
"atom_indices",
"is",
"not",
"None",
":",
"sliced_traj",
"=",
"traj",
".",
"atom_slice",
"(",
"self",
".",
"atom_indices",
")",
"else",
":",
"sliced_traj",
"=",
"traj",
"r... | Featurize an MD trajectory into a vector space via distance
after superposition
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, shape=(n_frames, n_ref_frames)
... | [
"Featurize",
"an",
"MD",
"trajectory",
"into",
"a",
"vector",
"space",
"via",
"distance",
"after",
"superposition"
] | python | train |
cherrypy/cheroot | cheroot/server.py | https://github.com/cherrypy/cheroot/blob/2af3b1798d66da697957480d3a8b4831a405770b/cheroot/server.py#L1251-L1303 | def communicate(self):
"""Read each request and respond appropriately."""
request_seen = False
try:
while True:
# (re)set req to None so that if something goes wrong in
# the RequestHandlerClass constructor, the error doesn't
# get writ... | [
"def",
"communicate",
"(",
"self",
")",
":",
"request_seen",
"=",
"False",
"try",
":",
"while",
"True",
":",
"# (re)set req to None so that if something goes wrong in",
"# the RequestHandlerClass constructor, the error doesn't",
"# get written to the previous request.",
"req",
"=... | Read each request and respond appropriately. | [
"Read",
"each",
"request",
"and",
"respond",
"appropriately",
"."
] | python | train |
improbable-research/keanu | keanu-python/keanu/plots/traceplot.py | https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/plots/traceplot.py#L12-L37 | def traceplot(trace: sample_types, labels: List[Union[str, Tuple[str, str]]] = None, ax: Any = None,
x0: int = 0) -> Any:
"""
Plot samples values.
:param trace: result of MCMC run
:param labels: labels of vertices to be plotted. if None, all vertices are plotted.
:param ax: Matplotli... | [
"def",
"traceplot",
"(",
"trace",
":",
"sample_types",
",",
"labels",
":",
"List",
"[",
"Union",
"[",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"ax",
":",
"Any",
"=",
"None",
",",
"x0",
":",
"int",
"=",
"0",
... | Plot samples values.
:param trace: result of MCMC run
:param labels: labels of vertices to be plotted. if None, all vertices are plotted.
:param ax: Matplotlib axes
:param x0: index of first data point, used for sample stream plots | [
"Plot",
"samples",
"values",
"."
] | python | train |
fracpete/python-weka-wrapper3 | python/weka/core/dataset.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/dataset.py#L314-L323 | def insert_attribute(self, att, index):
"""
Inserts the attribute at the specified location.
:param att: the attribute to insert
:type att: Attribute
:param index: the index to insert the attribute at
:type index: int
"""
javabridge.call(self.jobject, "in... | [
"def",
"insert_attribute",
"(",
"self",
",",
"att",
",",
"index",
")",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"insertAttributeAt\"",
",",
"\"(Lweka/core/Attribute;I)V\"",
",",
"att",
".",
"jobject",
",",
"index",
")"
] | Inserts the attribute at the specified location.
:param att: the attribute to insert
:type att: Attribute
:param index: the index to insert the attribute at
:type index: int | [
"Inserts",
"the",
"attribute",
"at",
"the",
"specified",
"location",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/ec2.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L3624-L3649 | def _list_nodes_full(location=None):
'''
Return a list of the VMs that in this location
'''
provider = __active_provider_name__ or 'ec2'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
params = {'Action': 'DescribeInstances'}
instances = aws.query(params,... | [
"def",
"_list_nodes_full",
"(",
"location",
"=",
"None",
")",
":",
"provider",
"=",
"__active_provider_name__",
"or",
"'ec2'",
"if",
"':'",
"in",
"provider",
":",
"comps",
"=",
"provider",
".",
"split",
"(",
"':'",
")",
"provider",
"=",
"comps",
"[",
"0",
... | Return a list of the VMs that in this location | [
"Return",
"a",
"list",
"of",
"the",
"VMs",
"that",
"in",
"this",
"location"
] | python | train |
tanghaibao/goatools | goatools/go_search.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/go_search.py#L57-L65 | def _search_vals(self, compiled_pattern, fld_val):
"""Search for user-regex in scalar or iterable data values."""
matches = []
if isinstance(fld_val, set):
for val in fld_val:
self._search_val(matches, compiled_pattern, val)
elif isinstance(fld_val, str):
... | [
"def",
"_search_vals",
"(",
"self",
",",
"compiled_pattern",
",",
"fld_val",
")",
":",
"matches",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"fld_val",
",",
"set",
")",
":",
"for",
"val",
"in",
"fld_val",
":",
"self",
".",
"_search_val",
"(",
"matches",
"... | Search for user-regex in scalar or iterable data values. | [
"Search",
"for",
"user",
"-",
"regex",
"in",
"scalar",
"or",
"iterable",
"data",
"values",
"."
] | python | train |
sorgerlab/indra | indra/literature/deft_tools.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/deft_tools.py#L46-L84 | def get_text_content_for_pmids(pmids):
"""Get text content for articles given a list of their pmids
Parameters
----------
pmids : list of str
Returns
-------
text_content : list of str
"""
pmc_pmids = set(pmc_client.filter_pmids(pmids, source_type='fulltext'))
pmc_ids = []
... | [
"def",
"get_text_content_for_pmids",
"(",
"pmids",
")",
":",
"pmc_pmids",
"=",
"set",
"(",
"pmc_client",
".",
"filter_pmids",
"(",
"pmids",
",",
"source_type",
"=",
"'fulltext'",
")",
")",
"pmc_ids",
"=",
"[",
"]",
"for",
"pmid",
"in",
"pmc_pmids",
":",
"p... | Get text content for articles given a list of their pmids
Parameters
----------
pmids : list of str
Returns
-------
text_content : list of str | [
"Get",
"text",
"content",
"for",
"articles",
"given",
"a",
"list",
"of",
"their",
"pmids"
] | python | train |
ray-project/ray | examples/cython/cython_main.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L73-L85 | def example6():
"""Cython simple class"""
ray.init()
cls = ray.remote(cyth.simple_class)
a1 = cls.remote()
a2 = cls.remote()
result1 = ray.get(a1.increment.remote())
result2 = ray.get(a2.increment.remote())
print(result1, result2) | [
"def",
"example6",
"(",
")",
":",
"ray",
".",
"init",
"(",
")",
"cls",
"=",
"ray",
".",
"remote",
"(",
"cyth",
".",
"simple_class",
")",
"a1",
"=",
"cls",
".",
"remote",
"(",
")",
"a2",
"=",
"cls",
".",
"remote",
"(",
")",
"result1",
"=",
"ray"... | Cython simple class | [
"Cython",
"simple",
"class"
] | python | train |
apache/incubator-mxnet | python/mxnet/profiler.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L33-L67 | def set_config(**kwargs):
"""Set up the configure of profiler (only accepts keyword arguments).
Parameters
----------
filename : string,
output file for profile data
profile_all : boolean,
all profile types enabled
profile_symbolic : boolean,
whether to profile symbolic ... | [
"def",
"set_config",
"(",
"*",
"*",
"kwargs",
")",
":",
"kk",
"=",
"kwargs",
".",
"keys",
"(",
")",
"vv",
"=",
"kwargs",
".",
"values",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXSetProcessProfilerConfig",
"(",
"len",
"(",
"kwargs",
")",
",",
"c_st... | Set up the configure of profiler (only accepts keyword arguments).
Parameters
----------
filename : string,
output file for profile data
profile_all : boolean,
all profile types enabled
profile_symbolic : boolean,
whether to profile symbolic operators
profile_imperative ... | [
"Set",
"up",
"the",
"configure",
"of",
"profiler",
"(",
"only",
"accepts",
"keyword",
"arguments",
")",
"."
] | python | train |
SHDShim/pytheos | pytheos/eqn_hugoniot.py | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L25-L60 | def _dT_h_delta(T_in_kK, eta, k, threenk, c_v):
"""
internal function for calculation of temperature along a Hugoniot
:param T_in_kK: temperature in kK scale, see Jamieson for detail
:param eta: = 1 - rho0/rho
:param k: = [rho0, c0, s, gamma0, q, theta0]
:param threenk: see the definition in Ja... | [
"def",
"_dT_h_delta",
"(",
"T_in_kK",
",",
"eta",
",",
"k",
",",
"threenk",
",",
"c_v",
")",
":",
"rho0",
"=",
"k",
"[",
"0",
"]",
"# g/m^3",
"gamma0",
"=",
"k",
"[",
"3",
"]",
"# no unit",
"q",
"=",
"k",
"[",
"4",
"]",
"# no unit",
"theta0_in_kK... | internal function for calculation of temperature along a Hugoniot
:param T_in_kK: temperature in kK scale, see Jamieson for detail
:param eta: = 1 - rho0/rho
:param k: = [rho0, c0, s, gamma0, q, theta0]
:param threenk: see the definition in Jamieson 1983,
it is a correction term mostly for Jami... | [
"internal",
"function",
"for",
"calculation",
"of",
"temperature",
"along",
"a",
"Hugoniot"
] | python | train |
sastrarobotics/pyHerkulex | herkulex.py | https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L780-L796 | def get_position_d(self):
""" Get the D value of the current PID for position
"""
data = []
data.append(0x09)
data.append(self.servoid)
data.append(RAM_READ_REQ)
data.append(POSITION_KD_RAM)
data.append(BYTE2)
send_data(data)
rxdata = []
... | [
"def",
"get_position_d",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"data",
".",
"append",
"(",
"0x09",
")",
"data",
".",
"append",
"(",
"self",
".",
"servoid",
")",
"data",
".",
"append",
"(",
"RAM_READ_REQ",
")",
"data",
".",
"append",
"(",
"P... | Get the D value of the current PID for position | [
"Get",
"the",
"D",
"value",
"of",
"the",
"current",
"PID",
"for",
"position"
] | python | train |
pvlib/pvlib-python | pvlib/iotools/midc.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/iotools/midc.py#L91-L114 | def format_index_raw(data):
"""Create DatetimeIndex for the Dataframe localized to the timezone provided
as the label of the third column.
Parameters
----------
data: Dataframe
Must contain columns 'Year' and 'DOY'. Timezone must be found as the
label of the third (time) column.
... | [
"def",
"format_index_raw",
"(",
"data",
")",
":",
"tz_raw",
"=",
"data",
".",
"columns",
"[",
"3",
"]",
"timezone",
"=",
"TZ_MAP",
".",
"get",
"(",
"tz_raw",
",",
"tz_raw",
")",
"year",
"=",
"data",
".",
"Year",
".",
"apply",
"(",
"str",
")",
"jday... | Create DatetimeIndex for the Dataframe localized to the timezone provided
as the label of the third column.
Parameters
----------
data: Dataframe
Must contain columns 'Year' and 'DOY'. Timezone must be found as the
label of the third (time) column.
Returns
-------
data: Dat... | [
"Create",
"DatetimeIndex",
"for",
"the",
"Dataframe",
"localized",
"to",
"the",
"timezone",
"provided",
"as",
"the",
"label",
"of",
"the",
"third",
"column",
"."
] | python | train |
fjwCode/cerium | cerium/androiddriver.py | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L352-L370 | def view_packgets_list(self, option: str = '-e', keyword: str = '') -> list:
'''Show all packages.
Args:
option:
-f see their associated file
-d filter to only show disabled packages
-e filter to only show enabled packages
-s f... | [
"def",
"view_packgets_list",
"(",
"self",
",",
"option",
":",
"str",
"=",
"'-e'",
",",
"keyword",
":",
"str",
"=",
"''",
")",
"->",
"list",
":",
"if",
"option",
"not",
"in",
"[",
"'-f'",
",",
"'-d'",
",",
"'-e'",
",",
"'-s'",
",",
"'-3'",
",",
"'... | Show all packages.
Args:
option:
-f see their associated file
-d filter to only show disabled packages
-e filter to only show enabled packages
-s filter to only show system packages
-3 filter to only show third party pa... | [
"Show",
"all",
"packages",
"."
] | python | train |
openspending/babbage | babbage/query/drilldowns.py | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/drilldowns.py#L18-L28 | def apply(self, q, bindings, drilldowns):
""" Apply a set of grouping criteria and project them. """
info = []
for drilldown in self.parse(drilldowns):
for attribute in self.cube.model.match(drilldown):
info.append(attribute.ref)
table, column = attrib... | [
"def",
"apply",
"(",
"self",
",",
"q",
",",
"bindings",
",",
"drilldowns",
")",
":",
"info",
"=",
"[",
"]",
"for",
"drilldown",
"in",
"self",
".",
"parse",
"(",
"drilldowns",
")",
":",
"for",
"attribute",
"in",
"self",
".",
"cube",
".",
"model",
".... | Apply a set of grouping criteria and project them. | [
"Apply",
"a",
"set",
"of",
"grouping",
"criteria",
"and",
"project",
"them",
"."
] | python | train |
googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row_data.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row_data.py#L200-L235 | def find_cells(self, column_family_id, column):
"""Get a time series of cells stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_find_cells]
:end-before: [END bigtable_row_find_cells]
Args:
... | [
"def",
"find_cells",
"(",
"self",
",",
"column_family_id",
",",
"column",
")",
":",
"try",
":",
"column_family",
"=",
"self",
".",
"_cells",
"[",
"column_family_id",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"_MISSING_COLUMN_FAMILY",
".",
"form... | Get a time series of cells stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_find_cells]
:end-before: [END bigtable_row_find_cells]
Args:
column_family_id (str): The ID of the column family. Must b... | [
"Get",
"a",
"time",
"series",
"of",
"cells",
"stored",
"on",
"this",
"instance",
"."
] | python | train |
Yubico/yubikey-manager | ykman/cli/otp.py | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L98-L140 | def otp(ctx, access_code):
"""
Manage OTP Application.
The YubiKey provides two keyboard-based slots which can each be configured
with a credential. Several credential types are supported.
A slot configuration may be write-protected with an access code. This
prevents the configuration to be ov... | [
"def",
"otp",
"(",
"ctx",
",",
"access_code",
")",
":",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"=",
"OtpController",
"(",
"ctx",
".",
"obj",
"[",
"'dev'",
"]",
".",
"driver",
")",
"if",
"access_code",
"is",
"not",
"None",
":",
"if",
"access_cod... | Manage OTP Application.
The YubiKey provides two keyboard-based slots which can each be configured
with a credential. Several credential types are supported.
A slot configuration may be write-protected with an access code. This
prevents the configuration to be overwritten without the access code
p... | [
"Manage",
"OTP",
"Application",
"."
] | python | train |
sphinx-gallery/sphinx-gallery | sphinx_gallery/backreferences.py | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/backreferences.py#L111-L122 | def extract_object_names_from_docs(filename):
"""Add matches from the text blocks (must be full names!)"""
text = split_code_and_text_blocks(filename)[1]
text = '\n'.join(t[1] for t in text if t[0] == 'text')
regex = re.compile(r':(?:'
r'func(?:tion)?|'
r'me... | [
"def",
"extract_object_names_from_docs",
"(",
"filename",
")",
":",
"text",
"=",
"split_code_and_text_blocks",
"(",
"filename",
")",
"[",
"1",
"]",
"text",
"=",
"'\\n'",
".",
"join",
"(",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"text",
"if",
"t",
"[",
"0... | Add matches from the text blocks (must be full names!) | [
"Add",
"matches",
"from",
"the",
"text",
"blocks",
"(",
"must",
"be",
"full",
"names!",
")"
] | python | train |
cuihantao/andes | andes/utils/math.py | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/math.py#L123-L131 | def index(m, val):
"""
Return the indices of all the ``val`` in ``m``
"""
mm = np.array(m)
idx_tuple = np.where(mm == val)
idx = idx_tuple[0].tolist()
return idx | [
"def",
"index",
"(",
"m",
",",
"val",
")",
":",
"mm",
"=",
"np",
".",
"array",
"(",
"m",
")",
"idx_tuple",
"=",
"np",
".",
"where",
"(",
"mm",
"==",
"val",
")",
"idx",
"=",
"idx_tuple",
"[",
"0",
"]",
".",
"tolist",
"(",
")",
"return",
"idx"
... | Return the indices of all the ``val`` in ``m`` | [
"Return",
"the",
"indices",
"of",
"all",
"the",
"val",
"in",
"m"
] | python | train |
ubernostrum/django-flashpolicies | flashpolicies/policies.py | https://github.com/ubernostrum/django-flashpolicies/blob/fb04693504186dde859cce97bad6e83d2b380dc6/flashpolicies/policies.py#L200-L213 | def _add_header_domains_xml(self, document):
"""
Generates the XML elements for allowed header domains.
"""
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
'allow-http-request-headers-from'
)
... | [
"def",
"_add_header_domains_xml",
"(",
"self",
",",
"document",
")",
":",
"for",
"domain",
",",
"attrs",
"in",
"self",
".",
"header_domains",
".",
"items",
"(",
")",
":",
"header_element",
"=",
"document",
".",
"createElement",
"(",
"'allow-http-request-headers-... | Generates the XML elements for allowed header domains. | [
"Generates",
"the",
"XML",
"elements",
"for",
"allowed",
"header",
"domains",
"."
] | python | train |
romanz/trezor-agent | libagent/device/trezor.py | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/trezor.py#L76-L87 | def pubkey(self, identity, ecdh=False):
"""Return public key."""
curve_name = identity.get_curve_name(ecdh=ecdh)
log.debug('"%s" getting public key (%s) from %s',
identity.to_string(), curve_name, self)
addr = identity.get_bip32_address(ecdh=ecdh)
result = self.... | [
"def",
"pubkey",
"(",
"self",
",",
"identity",
",",
"ecdh",
"=",
"False",
")",
":",
"curve_name",
"=",
"identity",
".",
"get_curve_name",
"(",
"ecdh",
"=",
"ecdh",
")",
"log",
".",
"debug",
"(",
"'\"%s\" getting public key (%s) from %s'",
",",
"identity",
".... | Return public key. | [
"Return",
"public",
"key",
"."
] | python | train |
OSLL/jabba | jabba/dep_extractor.py | https://github.com/OSLL/jabba/blob/71c1d008ab497020fba6ffa12a600721eb3f5ef7/jabba/dep_extractor.py#L132-L138 | def get_includes(self, path):
"""
Get all includes from a config in a given path
"""
config = self.file_index.unfold_yaml(path)
return self.get_includes_from_dict(config, extract=True) | [
"def",
"get_includes",
"(",
"self",
",",
"path",
")",
":",
"config",
"=",
"self",
".",
"file_index",
".",
"unfold_yaml",
"(",
"path",
")",
"return",
"self",
".",
"get_includes_from_dict",
"(",
"config",
",",
"extract",
"=",
"True",
")"
] | Get all includes from a config in a given path | [
"Get",
"all",
"includes",
"from",
"a",
"config",
"in",
"a",
"given",
"path"
] | python | train |
pyGrowler/Growler | growler/core/router.py | https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/router.py#L281-L298 | def routerify(obj):
"""
Scan through attributes of object parameter looking for any which
match a route signature.
A router will be created and added to the object with parameter.
Args:
obj (object): The object (with attributes) from which to
setup a router
Returns:
... | [
"def",
"routerify",
"(",
"obj",
")",
":",
"router",
"=",
"Router",
"(",
")",
"for",
"info",
"in",
"get_routing_attributes",
"(",
"obj",
")",
":",
"router",
".",
"add_route",
"(",
"*",
"info",
")",
"obj",
".",
"__growler_router",
"=",
"router",
"return",
... | Scan through attributes of object parameter looking for any which
match a route signature.
A router will be created and added to the object with parameter.
Args:
obj (object): The object (with attributes) from which to
setup a router
Returns:
Router: The router created from... | [
"Scan",
"through",
"attributes",
"of",
"object",
"parameter",
"looking",
"for",
"any",
"which",
"match",
"a",
"route",
"signature",
".",
"A",
"router",
"will",
"be",
"created",
"and",
"added",
"to",
"the",
"object",
"with",
"parameter",
"."
] | python | train |
FutunnOpen/futuquant | futuquant/common/sys_config.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/sys_config.py#L23-L45 | def set_client_info(cls, client_id, client_ver):
"""
.. py:function:: set_client_info(cls, client_id, client_ver)
设置调用api的客户端信息, 非必调接口
:param client_id: str, 客户端标识
:param client_ver: int, 客户端版本号
:return: None
:example:
.. code:: python
from ... | [
"def",
"set_client_info",
"(",
"cls",
",",
"client_id",
",",
"client_ver",
")",
":",
"SysConfig",
".",
"CLINET_ID",
"=",
"client_id",
"SysConfig",
".",
"CLIENT_VER",
"=",
"client_ver"
] | .. py:function:: set_client_info(cls, client_id, client_ver)
设置调用api的客户端信息, 非必调接口
:param client_id: str, 客户端标识
:param client_ver: int, 客户端版本号
:return: None
:example:
.. code:: python
from futuquant import *
SysConfig.set_client_info("MyFutuQuant", ... | [
"..",
"py",
":",
"function",
"::",
"set_client_info",
"(",
"cls",
"client_id",
"client_ver",
")"
] | python | train |
bitesofcode/projexui | projexui/widgets/xmultitagedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmultitagedit.py#L542-L573 | def mousePressEvent( self, event ):
"""
Make sure on a mouse release event that we have a current item. If
no item is current, then our edit item will become current.
:param event | <QMouseReleaseEvent>
"""
item = self.itemAt(event.pos())
... | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"item",
"=",
"self",
".",
"itemAt",
"(",
"event",
".",
"pos",
"(",
")",
")",
"# set the tag creation item as active\r",
"if",
"item",
"is",
"None",
":",
"create_item",
"=",
"self",
".",
"create... | Make sure on a mouse release event that we have a current item. If
no item is current, then our edit item will become current.
:param event | <QMouseReleaseEvent> | [
"Make",
"sure",
"on",
"a",
"mouse",
"release",
"event",
"that",
"we",
"have",
"a",
"current",
"item",
".",
"If",
"no",
"item",
"is",
"current",
"then",
"our",
"edit",
"item",
"will",
"become",
"current",
".",
":",
"param",
"event",
"|",
"<QMouseReleaseEv... | python | train |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsHandle_Edit.py | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsHandle_Edit.py#L1377-L1562 | def GetTechSupport(self, pathPattern, ucsManager=False, ucsMgmt=False, chassisId=None, cimcId=None, adapterId=None,
iomId=None, fexId=None, rackServerId=None, rackAdapterId=None, timeoutSec=600,
removeFromUcs=False, dumpXml=None):
"""
Creates and downloads the technical support data for the respecti... | [
"def",
"GetTechSupport",
"(",
"self",
",",
"pathPattern",
",",
"ucsManager",
"=",
"False",
",",
"ucsMgmt",
"=",
"False",
",",
"chassisId",
"=",
"None",
",",
"cimcId",
"=",
"None",
",",
"adapterId",
"=",
"None",
",",
"iomId",
"=",
"None",
",",
"fexId",
... | Creates and downloads the technical support data for the respective UCSM.
- pathPattern specifies the path of the tech support file to be downloaded. File should be a tar file.
- ucsManager, if provided as True then technical support data for the entire UCSM instance will be created and downloaded.
- ucsMgmt, ... | [
"Creates",
"and",
"downloads",
"the",
"technical",
"support",
"data",
"for",
"the",
"respective",
"UCSM",
".",
"-",
"pathPattern",
"specifies",
"the",
"path",
"of",
"the",
"tech",
"support",
"file",
"to",
"be",
"downloaded",
".",
"File",
"should",
"be",
"a",... | python | train |
hawkular/hawkular-client-python | hawkular/metrics.py | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/metrics.py#L131-L147 | def push(self, metric_type, metric_id, value, timestamp=None):
"""
Pushes a single metric_id, datapoint combination to the server.
This method is an assistant method for the put method by removing the need to
create data structures first.
:param metric_type: MetricType to be ma... | [
"def",
"push",
"(",
"self",
",",
"metric_type",
",",
"metric_id",
",",
"value",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"type",
"(",
"timestamp",
")",
"is",
"datetime",
":",
"timestamp",
"=",
"datetime_to_time_millis",
"(",
"timestamp",
")",
"item",... | Pushes a single metric_id, datapoint combination to the server.
This method is an assistant method for the put method by removing the need to
create data structures first.
:param metric_type: MetricType to be matched (required)
:param metric_id: Exact string matching metric id
... | [
"Pushes",
"a",
"single",
"metric_id",
"datapoint",
"combination",
"to",
"the",
"server",
"."
] | python | train |
MoseleyBioinformaticsLab/ctfile | ctfile/ctfile.py | https://github.com/MoseleyBioinformaticsLab/ctfile/blob/eae864126cd9102207df5d363a3222256a0f1396/ctfile/ctfile.py#L110-L119 | def print_file(self, file_format='ctfile', f=sys.stdout):
"""Print representation of :class:`~ctfile.ctfile.CTfile`.
:param str file_format: Format to use: ``ctfile`` or ``json``.
:param f: Print to file or stdout.
:type f: File-like
:return: None.
:rtype: :py:obj:`None... | [
"def",
"print_file",
"(",
"self",
",",
"file_format",
"=",
"'ctfile'",
",",
"f",
"=",
"sys",
".",
"stdout",
")",
":",
"print",
"(",
"self",
".",
"writestr",
"(",
"file_format",
"=",
"file_format",
")",
",",
"file",
"=",
"f",
")"
] | Print representation of :class:`~ctfile.ctfile.CTfile`.
:param str file_format: Format to use: ``ctfile`` or ``json``.
:param f: Print to file or stdout.
:type f: File-like
:return: None.
:rtype: :py:obj:`None`. | [
"Print",
"representation",
"of",
":",
"class",
":",
"~ctfile",
".",
"ctfile",
".",
"CTfile",
"."
] | python | train |
sanger-pathogens/Fastaq | pyfastaq/tasks.py | https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L568-L577 | def sort_by_name(infile, outfile):
'''Sorts input sequence file by sort -d -k1,1, writes sorted output file.'''
seqs = {}
file_to_dict(infile, seqs)
#seqs = list(seqs.values())
#seqs.sort()
fout = utils.open_file_write(outfile)
for name in sorted(seqs):
print(seqs[name], file=fout)
... | [
"def",
"sort_by_name",
"(",
"infile",
",",
"outfile",
")",
":",
"seqs",
"=",
"{",
"}",
"file_to_dict",
"(",
"infile",
",",
"seqs",
")",
"#seqs = list(seqs.values())",
"#seqs.sort()",
"fout",
"=",
"utils",
".",
"open_file_write",
"(",
"outfile",
")",
"for",
"... | Sorts input sequence file by sort -d -k1,1, writes sorted output file. | [
"Sorts",
"input",
"sequence",
"file",
"by",
"sort",
"-",
"d",
"-",
"k1",
"1",
"writes",
"sorted",
"output",
"file",
"."
] | python | valid |
BernardFW/bernard | src/bernard/i18n/translator.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L120-L138 | def best_for_flags(self, flags: Flags) -> List[TransItem]:
"""
Given `flags`, find all items of this sentence that have an equal
matching score and put them in a list.
"""
best_score: int = 0
best_list: List[TransItem] = []
for item in self.items:
sc... | [
"def",
"best_for_flags",
"(",
"self",
",",
"flags",
":",
"Flags",
")",
"->",
"List",
"[",
"TransItem",
"]",
":",
"best_score",
":",
"int",
"=",
"0",
"best_list",
":",
"List",
"[",
"TransItem",
"]",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"... | Given `flags`, find all items of this sentence that have an equal
matching score and put them in a list. | [
"Given",
"flags",
"find",
"all",
"items",
"of",
"this",
"sentence",
"that",
"have",
"an",
"equal",
"matching",
"score",
"and",
"put",
"them",
"in",
"a",
"list",
"."
] | python | train |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/refconverters/bib.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/refconverters/bib.py#L10-L33 | def _ref_bib(key, ref):
'''Convert a single reference to bibtex format
'''
s = ''
s += '@{}{{{},\n'.format(ref['type'], key)
entry_lines = []
for k, v in ref.items():
if k == 'type':
continue
# Handle authors/editors
if k == 'authors':
entry_lin... | [
"def",
"_ref_bib",
"(",
"key",
",",
"ref",
")",
":",
"s",
"=",
"''",
"s",
"+=",
"'@{}{{{},\\n'",
".",
"format",
"(",
"ref",
"[",
"'type'",
"]",
",",
"key",
")",
"entry_lines",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"ref",
".",
"items",
"(",... | Convert a single reference to bibtex format | [
"Convert",
"a",
"single",
"reference",
"to",
"bibtex",
"format"
] | python | train |
honzamach/pynspect | pynspect/gparser.py | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/gparser.py#L290-L296 | def p_and_expression(tok):
"""and_expression : or_p_expression OP_AND and_expression
| or_p_expression"""
if len(tok) == 4:
tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
else:
tok[0] = tok[1] | [
"def",
"p_and_expression",
"(",
"tok",
")",
":",
"if",
"len",
"(",
"tok",
")",
"==",
"4",
":",
"tok",
"[",
"0",
"]",
"=",
"LogicalBinOpRule",
"(",
"tok",
"[",
"2",
"]",
",",
"tok",
"[",
"1",
"]",
",",
"tok",
"[",
"3",
"]",
")",
"else",
":",
... | and_expression : or_p_expression OP_AND and_expression
| or_p_expression | [
"and_expression",
":",
"or_p_expression",
"OP_AND",
"and_expression",
"|",
"or_p_expression"
] | python | train |
google/grr | grr/client/grr_response_client/client_utils_windows.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_utils_windows.py#L134-L193 | def FindProxies():
"""Tries to find proxies by interrogating all the user's settings.
This function is a modified urillib.getproxies_registry() from the
standard library. We just store the proxy value in the environment
for urllib to find it.
TODO(user): Iterate through all the possible values if one proxy
... | [
"def",
"FindProxies",
"(",
")",
":",
"proxies",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"100",
")",
":",
"try",
":",
"sid",
"=",
"winreg",
".",
"EnumKey",
"(",
"winreg",
".",
"HKEY_USERS",
",",
"i",
")",
"except",
"OSError",
":",... | Tries to find proxies by interrogating all the user's settings.
This function is a modified urillib.getproxies_registry() from the
standard library. We just store the proxy value in the environment
for urllib to find it.
TODO(user): Iterate through all the possible values if one proxy
fails, in case more th... | [
"Tries",
"to",
"find",
"proxies",
"by",
"interrogating",
"all",
"the",
"user",
"s",
"settings",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.