repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
almcc/cinder-data | cinder_data/cache.py | https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/cache.py#L55-L67 | def get_record(self, name, record_id):
"""Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`... | [
"def",
"get_record",
"(",
"self",
",",
"name",
",",
"record_id",
")",
":",
"if",
"name",
"in",
"self",
".",
"_cache",
":",
"if",
"record_id",
"in",
"self",
".",
"_cache",
"[",
"name",
"]",
":",
"return",
"self",
".",
"_cache",
"[",
"name",
"]",
"["... | Retrieve a record with a given type name and record id.
Args:
name (string): The name which the record is stored under.
record_id (int): The id of the record requested.
Returns:
:class:`cinder_data.model.CinderModel`: The cached model. | [
"Retrieve",
"a",
"record",
"with",
"a",
"given",
"type",
"name",
"and",
"record",
"id",
"."
] | python | train | 36.153846 |
sryza/spark-timeseries | python/sparkts/models/GARCH.py | https://github.com/sryza/spark-timeseries/blob/280aa887dc08ab114411245268f230fdabb76eec/python/sparkts/models/GARCH.py#L9-L24 | def fit_model(ts, sc=None):
"""
Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model
"""
assert sc != None, "Missing SparkContext"
jvm = sc.... | [
"def",
"fit_model",
"(",
"ts",
",",
"sc",
"=",
"None",
")",
":",
"assert",
"sc",
"!=",
"None",
",",
"\"Missing SparkContext\"",
"jvm",
"=",
"sc",
".",
"_jvm",
"jmodel",
"=",
"jvm",
".",
"com",
".",
"cloudera",
".",
"sparkts",
".",
"models",
".",
"GAR... | Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model | [
"Fits",
"a",
"GARCH",
"(",
"1",
"1",
")",
"model",
"to",
"the",
"given",
"time",
"series",
".",
"Parameters",
"----------",
"ts",
":",
"the",
"time",
"series",
"to",
"which",
"we",
"want",
"to",
"fit",
"a",
"GARCH",
"model",
"as",
"a",
"Numpy",
"arra... | python | train | 27.875 |
pandas-dev/pandas | pandas/io/pytables.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L2307-L2316 | def set_version(self):
""" compute and set our version """
version = _ensure_decoded(
getattr(self.group._v_attrs, 'pandas_version', None))
try:
self.version = tuple(int(x) for x in version.split('.'))
if len(self.version) == 2:
self.version = ... | [
"def",
"set_version",
"(",
"self",
")",
":",
"version",
"=",
"_ensure_decoded",
"(",
"getattr",
"(",
"self",
".",
"group",
".",
"_v_attrs",
",",
"'pandas_version'",
",",
"None",
")",
")",
"try",
":",
"self",
".",
"version",
"=",
"tuple",
"(",
"int",
"(... | compute and set our version | [
"compute",
"and",
"set",
"our",
"version"
] | python | train | 39.8 |
ND-CSE-30151/tock | tock/syntax.py | https://github.com/ND-CSE-30151/tock/blob/b8d21901aaf0e6ac913c2afa855f5b5a882a16c6/tock/syntax.py#L85-L94 | def parse_multiple(s, f, values=None):
"""Parse multiple comma-separated elements, each of which is parsed
using function f."""
if values is None: values = []
values.append(f(s))
if s.pos < len(s) and s.cur == ',':
s.pos += 1
return parse_multiple(s, f, values)
else:
r... | [
"def",
"parse_multiple",
"(",
"s",
",",
"f",
",",
"values",
"=",
"None",
")",
":",
"if",
"values",
"is",
"None",
":",
"values",
"=",
"[",
"]",
"values",
".",
"append",
"(",
"f",
"(",
"s",
")",
")",
"if",
"s",
".",
"pos",
"<",
"len",
"(",
"s",... | Parse multiple comma-separated elements, each of which is parsed
using function f. | [
"Parse",
"multiple",
"comma",
"-",
"separated",
"elements",
"each",
"of",
"which",
"is",
"parsed",
"using",
"function",
"f",
"."
] | python | train | 32.3 |
cmcginty/PyWeather | weather/services/_base.py | https://github.com/cmcginty/PyWeather/blob/8c25d9cd1fa921e0a6e460d523656279cac045cb/weather/services/_base.py#L63-L67 | def publish(self):
'''
Perform HTTP session to transmit defined weather values.
'''
return self._publish( self.args, self.server, self.URI) | [
"def",
"publish",
"(",
"self",
")",
":",
"return",
"self",
".",
"_publish",
"(",
"self",
".",
"args",
",",
"self",
".",
"server",
",",
"self",
".",
"URI",
")"
] | Perform HTTP session to transmit defined weather values. | [
"Perform",
"HTTP",
"session",
"to",
"transmit",
"defined",
"weather",
"values",
"."
] | python | test | 31.8 |
jameslyons/pycipher | pycipher/railfence.py | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/railfence.py#L34-L48 | def decipher(self,string,keep_punct=False):
"""Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spaci... | [
"def",
"decipher",
"(",
"self",
",",
"string",
",",
"keep_punct",
"=",
"False",
")",
":",
"if",
"not",
"keep_punct",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"ind",
"=",
"range",
"(",
"len",
"(",
"string",
")",
")",
... | Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default i... | [
"Decipher",
"string",
"using",
"Railfence",
"cipher",
"according",
"to",
"initialised",
"key",
"."
] | python | train | 42.6 |
google/brotli | research/brotlidump.py | https://github.com/google/brotli/blob/4b2b2d4f83ffeaac7708e44409fe34896a01a278/research/brotlidump.py#L571-L580 | def value(self, index, extra):
"""Returns ('Simple', #codewords) or ('Complex', HSKIP)
"""
if index==1:
if extra>3:
raise ValueError('value: extra out of range')
return 'Simple', extra+1
if extra:
raise ValueError('value: extra out of r... | [
"def",
"value",
"(",
"self",
",",
"index",
",",
"extra",
")",
":",
"if",
"index",
"==",
"1",
":",
"if",
"extra",
">",
"3",
":",
"raise",
"ValueError",
"(",
"'value: extra out of range'",
")",
"return",
"'Simple'",
",",
"extra",
"+",
"1",
"if",
"extra",... | Returns ('Simple', #codewords) or ('Complex', HSKIP) | [
"Returns",
"(",
"Simple",
"#codewords",
")",
"or",
"(",
"Complex",
"HSKIP",
")"
] | python | test | 34.9 |
universalcore/unicore.distribute | unicore/distribute/utils.py | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L158-L174 | def get_schema(repo, content_type):
"""
Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_schemas',
... | [
"def",
"get_schema",
"(",
"repo",
",",
"content_type",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo",
".",
"working_dir",
",",
"'_schemas'",
",",
"'%s.avsc'",
"%",
"(",
"content_type",
",",
")",
")",
",",
"'r'... | Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict | [
"Return",
"a",
"schema",
"for",
"a",
"content",
"type",
"in",
"a",
"repository",
"."
] | python | train | 29.941176 |
dadadel/pyment | pyment/pyment.py | https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L262-L287 | def diff(self, source_path='', target_path='', which=-1):
"""Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_pa... | [
"def",
"diff",
"(",
"self",
",",
"source_path",
"=",
"''",
",",
"target_path",
"=",
"''",
",",
"which",
"=",
"-",
"1",
")",
":",
"list_from",
",",
"list_to",
"=",
"self",
".",
"compute_before_after",
"(",
")",
"if",
"source_path",
".",
"startswith",
"(... | Build the diff between original docstring and proposed docstring.
:type which: int
-> -1 means all the dosctrings of the file
-> >=0 means the index of the docstring to proceed (Default value = -1)
:param source_path: (Default value = '')
:param target_path: (Default value... | [
"Build",
"the",
"diff",
"between",
"original",
"docstring",
"and",
"proposed",
"docstring",
"."
] | python | train | 43.307692 |
pyannote/pyannote-metrics | pyannote/metrics/base.py | https://github.com/pyannote/pyannote-metrics/blob/b433fec3bd37ca36fe026a428cd72483d646871a/pyannote/metrics/base.py#L384-L394 | def compute_metric(self, components):
"""Compute recall from `components`"""
numerator = components[RECALL_RELEVANT_RETRIEVED]
denominator = components[RECALL_RELEVANT]
if denominator == 0.:
if numerator == 0:
return 1.
else:
raise ... | [
"def",
"compute_metric",
"(",
"self",
",",
"components",
")",
":",
"numerator",
"=",
"components",
"[",
"RECALL_RELEVANT_RETRIEVED",
"]",
"denominator",
"=",
"components",
"[",
"RECALL_RELEVANT",
"]",
"if",
"denominator",
"==",
"0.",
":",
"if",
"numerator",
"=="... | Compute recall from `components` | [
"Compute",
"recall",
"from",
"components"
] | python | train | 34.454545 |
clinicedc/edc-notification | edc_notification/site_notifications.py | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/site_notifications.py#L100-L136 | def update_notification_list(self, apps=None, schema_editor=None, verbose=False):
"""Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notificatio... | [
"def",
"update_notification_list",
"(",
"self",
",",
"apps",
"=",
"None",
",",
"schema_editor",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"Notification",
"=",
"(",
"apps",
"or",
"django_apps",
")",
".",
"get_model",
"(",
"\"edc_notification.notifica... | Updates the notification model to ensure all registered
notifications classes are listed.
Typically called from a post_migrate signal.
Also, in tests you can register a notification and the Notification
class (not model) will automatically call this method if the
named notifica... | [
"Updates",
"the",
"notification",
"model",
"to",
"ensure",
"all",
"registered",
"notifications",
"classes",
"are",
"listed",
"."
] | python | train | 44.918919 |
leancloud/python-sdk | leancloud/query.py | https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/query.py#L95-L108 | def or_(cls, *queries):
"""
根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query
"""
if len(queries) < 2:
raise ValueError('or_ need two queries at least')
if not all(x._query_class._class_name == queries[0]._query_class._class_name f... | [
"def",
"or_",
"(",
"cls",
",",
"*",
"queries",
")",
":",
"if",
"len",
"(",
"queries",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'or_ need two queries at least'",
")",
"if",
"not",
"all",
"(",
"x",
".",
"_query_class",
".",
"_class_name",
"==",
"... | 根据传入的 Query 对象,构造一个新的 OR 查询。
:param queries: 需要构造的子查询列表
:rtype: Query | [
"根据传入的",
"Query",
"对象,构造一个新的",
"OR",
"查询。"
] | python | train | 36.214286 |
a1ezzz/wasp-general | wasp_general/thread.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/thread.py#L76-L93 | def critical_section_lock(lock=None, blocking=True, timeout=None, raise_exception=True):
""" An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object
instead of a function that returns a lock with which a function protection will be made
:param lock: lock with which a fun... | [
"def",
"critical_section_lock",
"(",
"lock",
"=",
"None",
",",
"blocking",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"raise_exception",
"=",
"True",
")",
":",
"def",
"lock_getter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"lo... | An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object
instead of a function that returns a lock with which a function protection will be made
:param lock: lock with which a function will be protected
:param blocking: same as blocking in :func:`.critical_section_dynamic... | [
"An",
"a",
"wrapper",
"for",
":",
"func",
":",
".",
"critical_section_dynamic_lock",
"function",
"call",
"but",
"uses",
"a",
"static",
"lock",
"object",
"instead",
"of",
"a",
"function",
"that",
"returns",
"a",
"lock",
"with",
"which",
"a",
"function",
"prot... | python | train | 47.333333 |
zabuldon/teslajsonpy | teslajsonpy/controller.py | https://github.com/zabuldon/teslajsonpy/blob/673ecdb5c9483160fb1b97e30e62f2c863761c39/teslajsonpy/controller.py#L302-L328 | def command(self, vehicle_id, name, data=None, wake_if_asleep=True):
"""Post name command to the vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the... | [
"def",
"command",
"(",
"self",
",",
"vehicle_id",
",",
"name",
",",
"data",
"=",
"None",
",",
"wake_if_asleep",
"=",
"True",
")",
":",
"data",
"=",
"data",
"or",
"{",
"}",
"return",
"self",
".",
"post",
"(",
"vehicle_id",
",",
"'command/%s'",
"%",
"n... | Post name command to the vehicle_id.
Parameters
----------
vehicle_id : string
Identifier for the car on the owner-api endpoint. Confusingly it
is not the vehicle_id field for identifying the car across
different endpoints.
https://tesla-api.timdo... | [
"Post",
"name",
"command",
"to",
"the",
"vehicle_id",
"."
] | python | train | 35.555556 |
SFDO-Tooling/CumulusCI | cumulusci/utils.py | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/utils.py#L341-L366 | def zip_clean_metaxml(zip_src, logger=None):
""" Given a zipfile, cleans all *-meta.xml files in the zip for
deployment by stripping all <packageVersions/> elements
"""
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_DEFLATED)
changed = []
for name in zip_src.namelist():
co... | [
"def",
"zip_clean_metaxml",
"(",
"zip_src",
",",
"logger",
"=",
"None",
")",
":",
"zip_dest",
"=",
"zipfile",
".",
"ZipFile",
"(",
"io",
".",
"BytesIO",
"(",
")",
",",
"\"w\"",
",",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"changed",
"=",
"[",
"]",
"for",
... | Given a zipfile, cleans all *-meta.xml files in the zip for
deployment by stripping all <packageVersions/> elements | [
"Given",
"a",
"zipfile",
"cleans",
"all",
"*",
"-",
"meta",
".",
"xml",
"files",
"in",
"the",
"zip",
"for",
"deployment",
"by",
"stripping",
"all",
"<packageVersions",
"/",
">",
"elements"
] | python | train | 41.038462 |
datawire/quark | quarkc/compiler.py | https://github.com/datawire/quark/blob/df0058a148b077c0aff535eb6ee382605c556273/quarkc/compiler.py#L743-L786 | def visit_Method(self, method):
"""
Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance.
"""
resolved_method = method.resolved.type
def get_params(method, extra_bindings):
# The Method should... | [
"def",
"visit_Method",
"(",
"self",
",",
"method",
")",
":",
"resolved_method",
"=",
"method",
".",
"resolved",
".",
"type",
"def",
"get_params",
"(",
"method",
",",
"extra_bindings",
")",
":",
"# The Method should already be the resolved version.",
"result",
"=",
... | Ensure method has the same signature matching method on parent interface.
:param method: L{quarkc.ast.Method} instance. | [
"Ensure",
"method",
"has",
"the",
"same",
"signature",
"matching",
"method",
"on",
"parent",
"interface",
"."
] | python | train | 54.659091 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/importstring.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/importstring.py#L21-L47 | def import_item(name):
"""Import and return bar given the string foo.bar."""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
# Note: the original code for this was the following. We've left it
# visible for now in case the new implementation shows any problems down
# th... | [
"def",
"import_item",
"(",
"name",
")",
":",
"package",
"=",
"'.'",
".",
"join",
"(",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
":",
"-",
"1",
"]",
")",
"obj",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"# Note: th... | Import and return bar given the string foo.bar. | [
"Import",
"and",
"return",
"bar",
"given",
"the",
"string",
"foo",
".",
"bar",
"."
] | python | test | 35.111111 |
ranaroussi/ezibpy | ezibpy/ezibpy.py | https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1121-L1137 | def registerTrailingStop(self, tickerId, orderId=0, quantity=1,
lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs):
""" adds trailing stop to monitor list """
ticksize = self.contractDetails(tickerId)["m_minTick"]
trailingStop = self.trailingStops[tickerId] = {
... | [
"def",
"registerTrailingStop",
"(",
"self",
",",
"tickerId",
",",
"orderId",
"=",
"0",
",",
"quantity",
"=",
"1",
",",
"lastPrice",
"=",
"0",
",",
"trailPercent",
"=",
"100.",
",",
"trailAmount",
"=",
"0.",
",",
"parentId",
"=",
"0",
",",
"*",
"*",
"... | adds trailing stop to monitor list | [
"adds",
"trailing",
"stop",
"to",
"monitor",
"list"
] | python | train | 34.823529 |
bitesofcode/projexui | projexui/xhistorystack.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xhistorystack.py#L210-L222 | def indexOf(self, url):
"""
Returns the index of the inputed url for this stack. If the url is \
not found, then -1 is returned.
:param url | <str>
:return <int>
"""
for i, (m_url, _) in enumerate(self._stack):
if m_url ==... | [
"def",
"indexOf",
"(",
"self",
",",
"url",
")",
":",
"for",
"i",
",",
"(",
"m_url",
",",
"_",
")",
"in",
"enumerate",
"(",
"self",
".",
"_stack",
")",
":",
"if",
"m_url",
"==",
"url",
":",
"return",
"i",
"return",
"-",
"1"
] | Returns the index of the inputed url for this stack. If the url is \
not found, then -1 is returned.
:param url | <str>
:return <int> | [
"Returns",
"the",
"index",
"of",
"the",
"inputed",
"url",
"for",
"this",
"stack",
".",
"If",
"the",
"url",
"is",
"\\",
"not",
"found",
"then",
"-",
"1",
"is",
"returned",
".",
":",
"param",
"url",
"|",
"<str",
">",
":",
"return",
"<int",
">"
] | python | train | 27.461538 |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L5173-L5193 | def _consolidate(self, inplace=False):
"""
Compute NDFrame with "consolidated" internals (data of each dtype
grouped together in a single ndarray).
Parameters
----------
inplace : boolean, default False
If False return new object, otherwise modify existing ob... | [
"def",
"_consolidate",
"(",
"self",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"inplace",
":",
"self",
".",
"_consolidate_inplace",
"(",
")",
"else",
":",
"f",
"=",
"lambda",
... | Compute NDFrame with "consolidated" internals (data of each dtype
grouped together in a single ndarray).
Parameters
----------
inplace : boolean, default False
If False return new object, otherwise modify existing object
Returns
-------
consolidated ... | [
"Compute",
"NDFrame",
"with",
"consolidated",
"internals",
"(",
"data",
"of",
"each",
"dtype",
"grouped",
"together",
"in",
"a",
"single",
"ndarray",
")",
"."
] | python | train | 33 |
openstack/networking-cisco | networking_cisco/apps/saf/agent/vdp/ovs_vdp.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/agent/vdp/ovs_vdp.py#L723-L759 | def provision_vdp_overlay_networks(self, port_uuid, mac, net_uuid,
segmentation_id, lvid, oui):
"""Provisions a overlay type network configured using VDP.
:param port_uuid: the uuid of the VM port.
:param mac: the MAC address of the VM.
:param net_... | [
"def",
"provision_vdp_overlay_networks",
"(",
"self",
",",
"port_uuid",
",",
"mac",
",",
"net_uuid",
",",
"segmentation_id",
",",
"lvid",
",",
"oui",
")",
":",
"lldpad_port",
"=",
"self",
".",
"lldpad_info",
"if",
"lldpad_port",
":",
"ovs_cb_data",
"=",
"{",
... | Provisions a overlay type network configured using VDP.
:param port_uuid: the uuid of the VM port.
:param mac: the MAC address of the VM.
:param net_uuid: the uuid of the network associated with this vlan.
:param segmentation_id: the VID for 'vlan' or tunnel ID for 'tunnel'
:lvi... | [
"Provisions",
"a",
"overlay",
"type",
"network",
"configured",
"using",
"VDP",
"."
] | python | train | 50.540541 |
PrefPy/prefpy | prefpy/gmmra.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmmra.py#L80-L98 | def _pos(self, k):
"""
Description:
Position k breaking
Parameters:
k: position k is used for the breaking
"""
if k < 2:
raise ValueError("k smaller than 2")
G = np.zeros((self.m, self.m))
for i in range(self.m):
... | [
"def",
"_pos",
"(",
"self",
",",
"k",
")",
":",
"if",
"k",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"k smaller than 2\"",
")",
"G",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"m",
",",
"self",
".",
"m",
")",
")",
"for",
"i",
"in",
"r... | Description:
Position k breaking
Parameters:
k: position k is used for the breaking | [
"Description",
":",
"Position",
"k",
"breaking",
"Parameters",
":",
"k",
":",
"position",
"k",
"is",
"used",
"for",
"the",
"breaking"
] | python | train | 28.736842 |
synw/dataswim | dataswim/charts/chartjs.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/charts/chartjs.py#L19-L52 | def _get_chartjs_chart(self, xcol, ycol, chart_type, label=None, opts={},
style={}, options={}, **kwargs):
"""
Get Chartjs html
"""
try:
xdata = list(self.df[xcol])
except Exception as e:
self.err(e, self._get_chartjs_chart,
... | [
"def",
"_get_chartjs_chart",
"(",
"self",
",",
"xcol",
",",
"ycol",
",",
"chart_type",
",",
"label",
"=",
"None",
",",
"opts",
"=",
"{",
"}",
",",
"style",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
... | Get Chartjs html | [
"Get",
"Chartjs",
"html"
] | python | train | 35.676471 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/util/config.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/config.py#L370-L379 | def _enable_profiling():
""" Start profiling and register callback to print stats when the program
exits.
"""
import cProfile
import atexit
global _profiler
_profiler = cProfile.Profile()
_profiler.enable()
atexit.register(_profile_atexit) | [
"def",
"_enable_profiling",
"(",
")",
":",
"import",
"cProfile",
"import",
"atexit",
"global",
"_profiler",
"_profiler",
"=",
"cProfile",
".",
"Profile",
"(",
")",
"_profiler",
".",
"enable",
"(",
")",
"atexit",
".",
"register",
"(",
"_profile_atexit",
")"
] | Start profiling and register callback to print stats when the program
exits. | [
"Start",
"profiling",
"and",
"register",
"callback",
"to",
"print",
"stats",
"when",
"the",
"program",
"exits",
"."
] | python | train | 26.6 |
aiogram/aiogram | aiogram/types/input_media.py | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_media.py#L209-L216 | def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]):
"""
Attach list of media
:param medias:
"""
for media in medias:
self.attach(media) | [
"def",
"attach_many",
"(",
"self",
",",
"*",
"medias",
":",
"typing",
".",
"Union",
"[",
"InputMedia",
",",
"typing",
".",
"Dict",
"]",
")",
":",
"for",
"media",
"in",
"medias",
":",
"self",
".",
"attach",
"(",
"media",
")"
] | Attach list of media
:param medias: | [
"Attach",
"list",
"of",
"media"
] | python | train | 25 |
gbiggs/rtctree | rtctree/component.py | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/component.py#L1107-L1112 | def conf_sets(self):
'''The dictionary of configuration sets in this component, if any.'''
with self._mutex:
if not self._conf_sets:
self._parse_configuration()
return self._conf_sets | [
"def",
"conf_sets",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_conf_sets",
":",
"self",
".",
"_parse_configuration",
"(",
")",
"return",
"self",
".",
"_conf_sets"
] | The dictionary of configuration sets in this component, if any. | [
"The",
"dictionary",
"of",
"configuration",
"sets",
"in",
"this",
"component",
"if",
"any",
"."
] | python | train | 38.333333 |
mikedh/trimesh | trimesh/rendering.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/rendering.py#L27-L58 | def convert_to_vertexlist(geometry, **kwargs):
"""
Try to convert various geometry objects to the constructor
args for a pyglet indexed vertex list.
Parameters
------------
obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float
Object to render
Returns
------------
args : tu... | [
"def",
"convert_to_vertexlist",
"(",
"geometry",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"util",
".",
"is_instance_named",
"(",
"geometry",
",",
"'Trimesh'",
")",
":",
"return",
"mesh_to_vertexlist",
"(",
"geometry",
",",
"*",
"*",
"kwargs",
")",
"elif",
... | Try to convert various geometry objects to the constructor
args for a pyglet indexed vertex list.
Parameters
------------
obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float
Object to render
Returns
------------
args : tuple
Args to be passed to pyglet indexed vertex list
... | [
"Try",
"to",
"convert",
"various",
"geometry",
"objects",
"to",
"the",
"constructor",
"args",
"for",
"a",
"pyglet",
"indexed",
"vertex",
"list",
"."
] | python | train | 35.8125 |
disqus/gargoyle | gargoyle/models.py | https://github.com/disqus/gargoyle/blob/47a79e34b093d56e11c344296d6b78854ed35f12/gargoyle/models.py#L127-L151 | def add_condition(self, manager, condition_set, field_name, condition, exclude=False, commit=True):
"""
Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_s... | [
"def",
"add_condition",
"(",
"self",
",",
"manager",
",",
"condition_set",
",",
"field_name",
",",
"condition",
",",
"exclude",
"=",
"False",
",",
"commit",
"=",
"True",
")",
":",
"condition_set",
"=",
"manager",
".",
"get_condition_set_by_id",
"(",
"condition... | Adds a new condition and registers it in the global ``gargoyle`` switch manager.
If ``commit`` is ``False``, the data will not be written to the database.
>>> switch = gargoyle['my_switch'] #doctest: +SKIP
>>> condition_set_id = condition_set.get_id() #doctest: +SKIP
>>> switch.add_con... | [
"Adds",
"a",
"new",
"condition",
"and",
"registers",
"it",
"in",
"the",
"global",
"gargoyle",
"switch",
"manager",
"."
] | python | train | 43.72 |
minorg/pastpy | py/src/pastpy/gen/database/impl/online/online_database_object_detail_image.py | https://github.com/minorg/pastpy/blob/7d5d6d511629481850216565e7451b5dcb8027a9/py/src/pastpy/gen/database/impl/online/online_database_object_detail_image.py#L381-L413 | def read(cls, iprot):
'''
Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
'''
i... | [
"def",
"read",
"(",
"cls",
",",
"iprot",
")",
":",
"init_kwds",
"=",
"{",
"}",
"iprot",
".",
"read_struct_begin",
"(",
")",
"while",
"True",
":",
"ifield_name",
",",
"ifield_type",
",",
"_ifield_id",
"=",
"iprot",
".",
"read_field_begin",
"(",
")",
"if",... | Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage | [
"Read",
"a",
"new",
"object",
"from",
"the",
"given",
"input",
"protocol",
"and",
"return",
"the",
"object",
"."
] | python | train | 44 |
PMEAL/OpenPNM | openpnm/utils/Project.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/utils/Project.py#L531-L602 | def export_data(self, phases=[], filename=None, filetype='vtp'):
r"""
Export the pore and throat data from the given object(s) into the
specified file and format.
Parameters
----------
phases : list of OpenPNM Phase Objects
The data on each supplied phase wil... | [
"def",
"export_data",
"(",
"self",
",",
"phases",
"=",
"[",
"]",
",",
"filename",
"=",
"None",
",",
"filetype",
"=",
"'vtp'",
")",
":",
"project",
"=",
"self",
"network",
"=",
"self",
".",
"network",
"if",
"filename",
"is",
"None",
":",
"filename",
"... | r"""
Export the pore and throat data from the given object(s) into the
specified file and format.
Parameters
----------
phases : list of OpenPNM Phase Objects
The data on each supplied phase will be added to file
filename : string
The file name t... | [
"r",
"Export",
"the",
"pore",
"and",
"throat",
"data",
"from",
"the",
"given",
"object",
"(",
"s",
")",
"into",
"the",
"specified",
"file",
"and",
"format",
"."
] | python | train | 46.833333 |
pyrogram/pyrogram | pyrogram/client/methods/decorators/on_raw_update.py | https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/methods/decorators/on_raw_update.py#L27-L53 | def on_raw_update(
self=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling raw updates.
This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`.
Args:
group (``int``, *optional*)... | [
"def",
"on_raw_update",
"(",
"self",
"=",
"None",
",",
"group",
":",
"int",
"=",
"0",
")",
"->",
"callable",
":",
"def",
"decorator",
"(",
"func",
":",
"callable",
")",
"->",
"Tuple",
"[",
"Handler",
",",
"int",
"]",
":",
"if",
"isinstance",
"(",
"... | Use this decorator to automatically register a function for handling raw updates.
This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`.
Args:
group (``int``, *optional*):
The group identifier, defaults to 0. | [
"Use",
"this",
"decorator",
"to",
"automatically",
"register",
"a",
"function",
"for",
"handling",
"raw",
"updates",
".",
"This",
"does",
"the",
"same",
"thing",
"as",
":",
"meth",
":",
"add_handler",
"using",
"the",
":",
"class",
":",
"RawUpdateHandler",
".... | python | train | 29.851852 |
idlesign/uwsgiconf | uwsgiconf/runtime/monitoring.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/runtime/monitoring.py#L50-L73 | def set(self, value, mode=None):
"""Sets metric value.
:param int|long value: New value.
:param str|unicode mode: Update mode.
* None - Unconditional update.
* max - Sets metric value if it is greater that the current one.
* min - Sets metric value if it is... | [
"def",
"set",
"(",
"self",
",",
"value",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"==",
"'max'",
":",
"func",
"=",
"uwsgi",
".",
"metric_set_max",
"elif",
"mode",
"==",
"'min'",
":",
"func",
"=",
"uwsgi",
".",
"metric_set_min",
"else",
":",
... | Sets metric value.
:param int|long value: New value.
:param str|unicode mode: Update mode.
* None - Unconditional update.
* max - Sets metric value if it is greater that the current one.
* min - Sets metric value if it is less that the current one.
:rtype:... | [
"Sets",
"metric",
"value",
"."
] | python | train | 24.333333 |
TUNE-Archive/freight_forwarder | freight_forwarder/cli/deploy.py | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/cli/deploy.py#L63-L90 | def deploy(self, args, **extra_args):
"""Deploy a docker container to a specific container ship (host)
:param args:
:type args:
"""
if not isinstance(args, argparse.Namespace):
raise TypeError(logger.error("args should of an instance of argparse.Namespace"))
... | [
"def",
"deploy",
"(",
"self",
",",
"args",
",",
"*",
"*",
"extra_args",
")",
":",
"if",
"not",
"isinstance",
"(",
"args",
",",
"argparse",
".",
"Namespace",
")",
":",
"raise",
"TypeError",
"(",
"logger",
".",
"error",
"(",
"\"args should of an instance of ... | Deploy a docker container to a specific container ship (host)
:param args:
:type args: | [
"Deploy",
"a",
"docker",
"container",
"to",
"a",
"specific",
"container",
"ship",
"(",
"host",
")"
] | python | train | 35.821429 |
googlefonts/glyphsLib | Lib/glyphsLib/parser.py | https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/parser.py#L91-L139 | def _parse(self, text, i):
"""Recursive function to parse a single dictionary, list, or value."""
m = self.start_dict_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
return self._parse_dict(text, i)
m = self.start_list_re.match(text, i)
... | [
"def",
"_parse",
"(",
"self",
",",
"text",
",",
"i",
")",
":",
"m",
"=",
"self",
".",
"start_dict_re",
".",
"match",
"(",
"text",
",",
"i",
")",
"if",
"m",
":",
"parsed",
"=",
"m",
".",
"group",
"(",
"0",
")",
"i",
"+=",
"len",
"(",
"parsed",... | Recursive function to parse a single dictionary, list, or value. | [
"Recursive",
"function",
"to",
"parse",
"a",
"single",
"dictionary",
"list",
"or",
"value",
"."
] | python | train | 31.897959 |
numenta/nupic | src/nupic/algorithms/temporal_memory.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L665-L692 | def _createSegment(cls, connections, lastUsedIterationForSegment, cell,
iteration, maxSegmentsPerCell):
"""
Create a segment on the connections, enforcing the maxSegmentsPerCell
parameter.
"""
# Enforce maxSegmentsPerCell.
while connections.numSegments(cell) >= maxSegmentsPe... | [
"def",
"_createSegment",
"(",
"cls",
",",
"connections",
",",
"lastUsedIterationForSegment",
",",
"cell",
",",
"iteration",
",",
"maxSegmentsPerCell",
")",
":",
"# Enforce maxSegmentsPerCell.",
"while",
"connections",
".",
"numSegments",
"(",
"cell",
")",
">=",
"max... | Create a segment on the connections, enforcing the maxSegmentsPerCell
parameter. | [
"Create",
"a",
"segment",
"on",
"the",
"connections",
"enforcing",
"the",
"maxSegmentsPerCell",
"parameter",
"."
] | python | valid | 37.178571 |
acutesoftware/AIKIF | aikif/toolbox/interface_windows_tools.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/interface_windows_tools.py#L57-L71 | def launch_app(app_path, params=[], time_before_kill_app=15):
"""
start an app
"""
import subprocess
try:
res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True)
print('res = ', res)
if res == 0:
return True
else:
re... | [
"def",
"launch_app",
"(",
"app_path",
",",
"params",
"=",
"[",
"]",
",",
"time_before_kill_app",
"=",
"15",
")",
":",
"import",
"subprocess",
"try",
":",
"res",
"=",
"subprocess",
".",
"call",
"(",
"[",
"app_path",
",",
"params",
"]",
",",
"timeout",
"... | start an app | [
"start",
"an",
"app"
] | python | train | 31.266667 |
SecurityInnovation/PGPy | pgpy/pgp.py | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2093-L2153 | def verify(self, subject, signature=None):
"""
Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is de... | [
"def",
"verify",
"(",
"self",
",",
"subject",
",",
"signature",
"=",
"None",
")",
":",
"sspairs",
"=",
"[",
"]",
"# some type checking",
"if",
"not",
"isinstance",
"(",
"subject",
",",
"(",
"type",
"(",
"None",
")",
",",
"PGPMessage",
",",
"PGPKey",
",... | Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is detached, it should be specified here.
:type signature: :... | [
"Verify",
"a",
"subject",
"with",
"a",
"signature",
"using",
"this",
"key",
"."
] | python | train | 47.311475 |
mlperf/training | reinforcement/tensorflow/minigo/bigtable_input.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L468-L500 | def moves_from_games(self, start_game, end_game, moves, shuffle,
column_family, column):
"""Dataset of samples and/or shuffled moves from game range.
Args:
n: an integer indicating how many past games should be sourced.
moves: an integer indicating how man... | [
"def",
"moves_from_games",
"(",
"self",
",",
"start_game",
",",
"end_game",
",",
"moves",
",",
"shuffle",
",",
"column_family",
",",
"column",
")",
":",
"start_row",
"=",
"ROW_PREFIX",
".",
"format",
"(",
"start_game",
")",
"end_row",
"=",
"ROW_PREFIX",
".",... | Dataset of samples and/or shuffled moves from game range.
Args:
n: an integer indicating how many past games should be sourced.
moves: an integer indicating how many moves should be sampled
from those N games.
column_family: name of the column family containing move... | [
"Dataset",
"of",
"samples",
"and",
"/",
"or",
"shuffled",
"moves",
"from",
"game",
"range",
"."
] | python | train | 50.969697 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py#L2861-L2922 | def parse_requirements(strs):
"""Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof.
"""
# create a steppable iterator, so we can handle \-continuations
lines = iter(yield_lines(strs))
def scan_list(ITEM, TERMINATOR, ... | [
"def",
"parse_requirements",
"(",
"strs",
")",
":",
"# create a steppable iterator, so we can handle \\-continuations",
"lines",
"=",
"iter",
"(",
"yield_lines",
"(",
"strs",
")",
")",
"def",
"scan_list",
"(",
"ITEM",
",",
"TERMINATOR",
",",
"line",
",",
"p",
",",... | Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof. | [
"Yield",
"Requirement",
"objects",
"for",
"each",
"specification",
"in",
"strs"
] | python | test | 31.790323 |
aliyun/aliyun-odps-python-sdk | odps/ml/metrics/regression.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/ml/metrics/regression.py#L221-L237 | def residual_histogram(df, col_true, col_pred=None):
"""
Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: s... | [
"def",
"residual_histogram",
"(",
"df",
",",
"col_true",
",",
"col_pred",
"=",
"None",
")",
":",
"if",
"not",
"col_pred",
":",
"col_pred",
"=",
"get_field_name_by_role",
"(",
"df",
",",
"FieldRole",
".",
"PREDICTED_VALUE",
")",
"return",
"_run_evaluation_node",
... | Compute histogram of residuals of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str
:param col_true: column name of predicted value, 'predicti... | [
"Compute",
"histogram",
"of",
"residuals",
"of",
"a",
"predicted",
"DataFrame",
"."
] | python | train | 38.529412 |
androguard/androguard | androguard/core/androconf.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/androconf.py#L266-L277 | def rrmdir(directory):
"""
Recursivly delete a directory
:param directory: directory to remove
"""
for root, dirs, files in os.walk(directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root,... | [
"def",
"rrmdir",
"(",
"directory",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
",",
"topdown",
"=",
"False",
")",
":",
"for",
"name",
"in",
"files",
":",
"os",
".",
"remove",
"(",
"os",
".",
"pat... | Recursivly delete a directory
:param directory: directory to remove | [
"Recursivly",
"delete",
"a",
"directory"
] | python | train | 28.333333 |
saltstack/salt | salt/cloud/clouds/gce.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/gce.py#L2383-L2436 | def create_attach_volumes(name, kwargs, call=None):
'''
.. versionadded:: 2017.7.0
Create and attach multiple volumes to a node. The 'volumes' and 'node'
arguments are required, where 'node' is a libcloud node, and 'volumes'
is a list of maps, where each map contains:
size
The size of ... | [
"def",
"create_attach_volumes",
"(",
"name",
",",
"kwargs",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_attach_volumes action must be called with '",
"'-a or --action.'",
")",
"volumes",
"=... | .. versionadded:: 2017.7.0
Create and attach multiple volumes to a node. The 'volumes' and 'node'
arguments are required, where 'node' is a libcloud node, and 'volumes'
is a list of maps, where each map contains:
size
The size of the new disk in GB. Required.
type
The disk type, e... | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | python | train | 32.240741 |
pywbem/pywbem | pywbem_mock/_wbemconnection_mock.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1206-L1233 | def _get_class_repo(self, namespace):
"""
Returns the class repository for the specified CIM namespace
within the mock repository. This is the original instance variable,
so any modifications will change the mock repository.
Validates that the namespace exists in the mock reposi... | [
"def",
"_get_class_repo",
"(",
"self",
",",
"namespace",
")",
":",
"self",
".",
"_validate_namespace",
"(",
"namespace",
")",
"if",
"namespace",
"not",
"in",
"self",
".",
"classes",
":",
"self",
".",
"classes",
"[",
"namespace",
"]",
"=",
"NocaseDict",
"("... | Returns the class repository for the specified CIM namespace
within the mock repository. This is the original instance variable,
so any modifications will change the mock repository.
Validates that the namespace exists in the mock repository.
If the class repository does not contain th... | [
"Returns",
"the",
"class",
"repository",
"for",
"the",
"specified",
"CIM",
"namespace",
"within",
"the",
"mock",
"repository",
".",
"This",
"is",
"the",
"original",
"instance",
"variable",
"so",
"any",
"modifications",
"will",
"change",
"the",
"mock",
"repositor... | python | train | 30.5 |
bxlab/bx-python | lib/bx_extras/pstat.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L543-L555 | def pl (listoflists):
"""
Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None
"""
for row in listoflists:
if row[-1] == '\n':
print(row, end=' ')
else:
print(row)
return None | [
"def",
"pl",
"(",
"listoflists",
")",
":",
"for",
"row",
"in",
"listoflists",
":",
"if",
"row",
"[",
"-",
"1",
"]",
"==",
"'\\n'",
":",
"print",
"(",
"row",
",",
"end",
"=",
"' '",
")",
"else",
":",
"print",
"(",
"row",
")",
"return",
"None"
] | Prints a list of lists, 1 list (row) at a time.
Usage: pl(listoflists)
Returns: None | [
"Prints",
"a",
"list",
"of",
"lists",
"1",
"list",
"(",
"row",
")",
"at",
"a",
"time",
"."
] | python | train | 19.230769 |
OnroerendErfgoed/pyramid_urireferencer | pyramid_urireferencer/models.py | https://github.com/OnroerendErfgoed/pyramid_urireferencer/blob/c6ee4ba863e32ced304b9cf00f3f5b450757a29a/pyramid_urireferencer/models.py#L114-L121 | def load_from_json(data):
"""
Load a :class:`Item` from a dictionary ot string (that will be parsed
as json)
"""
if isinstance(data, str):
data = json.loads(data)
return Item(data['title'], data['uri']) | [
"def",
"load_from_json",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"return",
"Item",
"(",
"data",
"[",
"'title'",
"]",
",",
"data",
"[",
"'uri'",
"]",
")"
] | Load a :class:`Item` from a dictionary ot string (that will be parsed
as json) | [
"Load",
"a",
":",
"class",
":",
"Item",
"from",
"a",
"dictionary",
"ot",
"string",
"(",
"that",
"will",
"be",
"parsed",
"as",
"json",
")"
] | python | train | 31.875 |
addok/addok | addok/fuzzy.py | https://github.com/addok/addok/blob/46a270d76ec778d2b445c2be753e5c6ba070a9b2/addok/fuzzy.py#L11-L38 | def make_fuzzy(word, max=1):
"""Naive neighborhoods algo."""
# inversions
neighbors = []
for i in range(0, len(word) - 1):
neighbor = list(word)
neighbor[i], neighbor[i+1] = neighbor[i+1], neighbor[i]
neighbors.append(''.join(neighbor))
# substitutions
for letter in strin... | [
"def",
"make_fuzzy",
"(",
"word",
",",
"max",
"=",
"1",
")",
":",
"# inversions",
"neighbors",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"word",
")",
"-",
"1",
")",
":",
"neighbor",
"=",
"list",
"(",
"word",
")",
"nei... | Naive neighborhoods algo. | [
"Naive",
"neighborhoods",
"algo",
"."
] | python | test | 33.607143 |
log2timeline/plaso | plaso/parsers/recycler.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/recycler.py#L227-L273 | def ParseFileObject(self, parser_mediator, file_object):
"""Parses a Windows Recycler INFO2 file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
R... | [
"def",
"ParseFileObject",
"(",
"self",
",",
"parser_mediator",
",",
"file_object",
")",
":",
"# Since this header value is really generic it is hard not to use filename",
"# as an indicator too.",
"# TODO: Rethink this and potentially make a better test.",
"filename",
"=",
"parser_medi... | Parses a Windows Recycler INFO2 file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
Raises:
UnableToParseFile: when the file cannot be parsed. | [
"Parses",
"a",
"Windows",
"Recycler",
"INFO2",
"file",
"-",
"like",
"object",
"."
] | python | train | 34.425532 |
MacHu-GWU/superjson-project | superjson/pkg/dateutil/zoneinfo/rebuild.py | https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/zoneinfo/rebuild.py#L14-L42 | def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
"""Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
filename is the timezone tarball from ftp.iana.org/tz.
"""
tmpdir = tempfile.mkdtemp()
zonedir = os.path.join(tmpdir, "zoneinfo")
moduledir = os.... | [
"def",
"rebuild",
"(",
"filename",
",",
"tag",
"=",
"None",
",",
"format",
"=",
"\"gz\"",
",",
"zonegroups",
"=",
"[",
"]",
",",
"metadata",
"=",
"None",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"zonedir",
"=",
"os",
".",
"pat... | Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
filename is the timezone tarball from ftp.iana.org/tz. | [
"Rebuild",
"the",
"internal",
"timezone",
"info",
"in",
"dateutil",
"/",
"zoneinfo",
"/",
"zoneinfo",
"*",
"tar",
"*"
] | python | valid | 39.172414 |
PonteIneptique/collatinus-python | pycollatinus/lemme.py | https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemme.py#L143-L152 | def ajRadical(self, i, r=None):
""" Ajoute le radical r de numéro i à la map des radicaux du lemme.
:param i: Index de radical
:type i: int
:param r: Radical à ajouter
:type r: Radical
"""
if r:
self._radicaux[i].append(r) | [
"def",
"ajRadical",
"(",
"self",
",",
"i",
",",
"r",
"=",
"None",
")",
":",
"if",
"r",
":",
"self",
".",
"_radicaux",
"[",
"i",
"]",
".",
"append",
"(",
"r",
")"
] | Ajoute le radical r de numéro i à la map des radicaux du lemme.
:param i: Index de radical
:type i: int
:param r: Radical à ajouter
:type r: Radical | [
"Ajoute",
"le",
"radical",
"r",
"de",
"numéro",
"i",
"à",
"la",
"map",
"des",
"radicaux",
"du",
"lemme",
"."
] | python | train | 28.2 |
helixyte/everest | everest/repositories/manager.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/repositories/manager.py#L54-L89 | def new(self, repo_type, name=None, make_default=False,
repository_class=None, aggregate_class=None,
configuration=None):
"""
Creates a new repository of the given type. If the root repository
domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`)
... | [
"def",
"new",
"(",
"self",
",",
"repo_type",
",",
"name",
"=",
"None",
",",
"make_default",
"=",
"False",
",",
"repository_class",
"=",
"None",
",",
"aggregate_class",
"=",
"None",
",",
"configuration",
"=",
"None",
")",
":",
"if",
"name",
"==",
"REPOSIT... | Creates a new repository of the given type. If the root repository
domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`)
is passed as a repository name, the type string is used as the name;
if no name is passed, a unique name is created automatically. | [
"Creates",
"a",
"new",
"repository",
"of",
"the",
"given",
"type",
".",
"If",
"the",
"root",
"repository",
"domain",
"(",
"see",
":",
"class",
":",
"everest",
".",
"repositories",
".",
"constants",
".",
"REPOSITORY_DOMAINS",
")",
"is",
"passed",
"as",
"a",... | python | train | 47.055556 |
google/grr | grr/server/grr_response_server/authorization/auth_manager.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/authorization/auth_manager.py#L107-L118 | def CheckPermissions(self, username, subject):
"""Checks if a given user has access to a given subject."""
if subject in self.authorized_users:
return ((username in self.authorized_users[subject]) or
self.group_access_manager.MemberOfAuthorizedGroup(
username, subject))
... | [
"def",
"CheckPermissions",
"(",
"self",
",",
"username",
",",
"subject",
")",
":",
"if",
"subject",
"in",
"self",
".",
"authorized_users",
":",
"return",
"(",
"(",
"username",
"in",
"self",
".",
"authorized_users",
"[",
"subject",
"]",
")",
"or",
"self",
... | Checks if a given user has access to a given subject. | [
"Checks",
"if",
"a",
"given",
"user",
"has",
"access",
"to",
"a",
"given",
"subject",
"."
] | python | train | 48 |
daviddrysdale/python-phonenumbers | python/phonenumbers/re_util.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/re_util.py#L27-L39 | def fullmatch(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning a match
object if the whole string matches, or None if no match was found."""
# Build a version of the pattern with a non-capturing group around it.
# This is needed to get m.end() to correctly rep... | [
"def",
"fullmatch",
"(",
"pattern",
",",
"string",
",",
"flags",
"=",
"0",
")",
":",
"# Build a version of the pattern with a non-capturing group around it.",
"# This is needed to get m.end() to correctly report the size of the",
"# matched expression (as per the final doctest above).",
... | Try to apply the pattern at the start of the string, returning a match
object if the whole string matches, or None if no match was found. | [
"Try",
"to",
"apply",
"the",
"pattern",
"at",
"the",
"start",
"of",
"the",
"string",
"returning",
"a",
"match",
"object",
"if",
"the",
"whole",
"string",
"matches",
"or",
"None",
"if",
"no",
"match",
"was",
"found",
"."
] | python | train | 54.846154 |
kejbaly2/metrique | metrique/metrique.py | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/metrique.py#L332-L353 | def get_cube(self, cube, init=True, name=None, copy_config=True, **kwargs):
'''wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of... | [
"def",
"get_cube",
"(",
"self",
",",
"cube",
",",
"init",
"=",
"True",
",",
"name",
"=",
"None",
",",
"copy_config",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"name",
"or",
"cube",
"config",
"=",
"copy",
"(",
"self",
".",
"conf... | wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of the cube
:param copy_config: apply config of calling cube to new?
... | [
"wrapper",
"for",
":",
"func",
":",
"metrique",
".",
"utils",
".",
"get_cube"
] | python | train | 47.136364 |
PatrikValkovic/grammpy | grammpy/transforms/EpsilonRulesRemove/remove_rules_with_epsilon.py | https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/transforms/EpsilonRulesRemove/remove_rules_with_epsilon.py#L66-L103 | def remove_rules_with_epsilon(grammar, inplace=False):
# type: (Grammar, bool) -> Grammar
"""
Remove epsilon rules.
:param grammar: Grammar where rules remove
:param inplace: True if transformation should be performed in place, false otherwise.
False by default.
:return: Grammar without epsi... | [
"def",
"remove_rules_with_epsilon",
"(",
"grammar",
",",
"inplace",
"=",
"False",
")",
":",
"# type: (Grammar, bool) -> Grammar",
"# copy if required",
"if",
"inplace",
"is",
"False",
":",
"grammar",
"=",
"copy",
"(",
"grammar",
")",
"# find nonterminals rewritable to e... | Remove epsilon rules.
:param grammar: Grammar where rules remove
:param inplace: True if transformation should be performed in place, false otherwise.
False by default.
:return: Grammar without epsilon rules. | [
"Remove",
"epsilon",
"rules",
".",
":",
"param",
"grammar",
":",
"Grammar",
"where",
"rules",
"remove",
":",
"param",
"inplace",
":",
"True",
"if",
"transformation",
"should",
"be",
"performed",
"in",
"place",
"false",
"otherwise",
".",
"False",
"by",
"defau... | python | train | 41.631579 |
sbuss/pypercube | pypercube/expression.py | https://github.com/sbuss/pypercube/blob/e9d2cca9c004b8bad6d1e0b68b080f887a186a22/pypercube/expression.py#L298-L308 | def ge(self, event_property, value):
"""A greater-than-or-equal-to filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.ge('elapsed_ms', 500)
>>> print(filtered)
request(elapsed_ms).ge(elapsed_ms, 500)
"""
c = self... | [
"def",
"ge",
"(",
"self",
",",
"event_property",
",",
"value",
")",
":",
"c",
"=",
"self",
".",
"copy",
"(",
")",
"c",
".",
"filters",
".",
"append",
"(",
"filters",
".",
"GE",
"(",
"event_property",
",",
"value",
")",
")",
"return",
"c"
] | A greater-than-or-equal-to filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.ge('elapsed_ms', 500)
>>> print(filtered)
request(elapsed_ms).ge(elapsed_ms, 500) | [
"A",
"greater",
"-",
"than",
"-",
"or",
"-",
"equal",
"-",
"to",
"filter",
"chain",
"."
] | python | train | 35.818182 |
andialbrecht/sqlparse | sqlparse/engine/statement_splitter.py | https://github.com/andialbrecht/sqlparse/blob/913b56e34edc7e3025feea4744dbd762774805c3/sqlparse/engine/statement_splitter.py#L28-L78 | def _change_splitlevel(self, ttype, value):
"""Get the new split level (increase, decrease or remain equal)"""
# parenthesis increase/decrease a level
if ttype is T.Punctuation and value == '(':
return 1
elif ttype is T.Punctuation and value == ')':
return -1
... | [
"def",
"_change_splitlevel",
"(",
"self",
",",
"ttype",
",",
"value",
")",
":",
"# parenthesis increase/decrease a level",
"if",
"ttype",
"is",
"T",
".",
"Punctuation",
"and",
"value",
"==",
"'('",
":",
"return",
"1",
"elif",
"ttype",
"is",
"T",
".",
"Punctu... | Get the new split level (increase, decrease or remain equal) | [
"Get",
"the",
"new",
"split",
"level",
"(",
"increase",
"decrease",
"or",
"remain",
"equal",
")"
] | python | train | 35.27451 |
spencerahill/aospy | aospy/utils/vertcoord.py | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L78-L89 | def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0):
"""Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
defined at pressure levels. Requires specification of values at surface
and top of atmosphere.
"""
pha... | [
"def",
"to_phalf_from_pfull",
"(",
"arr",
",",
"val_toa",
"=",
"0",
",",
"val_sfc",
"=",
"0",
")",
":",
"phalf",
"=",
"np",
".",
"zeros",
"(",
"(",
"arr",
".",
"shape",
"[",
"0",
"]",
"+",
"1",
",",
"arr",
".",
"shape",
"[",
"1",
"]",
",",
"a... | Compute data at half pressure levels from values at full levels.
Could be the pressure array itself, but it could also be any other data
defined at pressure levels. Requires specification of values at surface
and top of atmosphere. | [
"Compute",
"data",
"at",
"half",
"pressure",
"levels",
"from",
"values",
"at",
"full",
"levels",
"."
] | python | train | 39.75 |
numenta/htmresearch | htmresearch/algorithms/faulty_temporal_memory.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/faulty_temporal_memory.py#L46-L78 | def killCells(self, percent = 0.05):
"""
Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead.
"""
if self.zombiePermutation is None:
self.zombiePermutation = numpy.... | [
"def",
"killCells",
"(",
"self",
",",
"percent",
"=",
"0.05",
")",
":",
"if",
"self",
".",
"zombiePermutation",
"is",
"None",
":",
"self",
".",
"zombiePermutation",
"=",
"numpy",
".",
"random",
".",
"permutation",
"(",
"self",
".",
"numberOfCells",
"(",
... | Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead. | [
"Changes",
"the",
"percentage",
"of",
"cells",
"that",
"are",
"now",
"considered",
"dead",
".",
"The",
"first",
"time",
"you",
"call",
"this",
"method",
"a",
"permutation",
"list",
"is",
"set",
"up",
".",
"Calls",
"change",
"the",
"number",
"of",
"cells",
... | python | train | 36.969697 |
nerdvegas/rez | src/rez/vendor/distlib/locators.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/locators.py#L313-L370 | def locate(self, requirement, prereleases=False):
"""
Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``Tr... | [
"def",
"locate",
"(",
"self",
",",
"requirement",
",",
"prereleases",
"=",
"False",
")",
":",
"result",
"=",
"None",
"r",
"=",
"parse_requirement",
"(",
"requirement",
")",
"if",
"r",
"is",
"None",
":",
"raise",
"DistlibException",
"(",
"'Not a valid require... | Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be loc... | [
"Find",
"the",
"most",
"recent",
"distribution",
"which",
"matches",
"the",
"given",
"requirement",
"."
] | python | train | 43.241379 |
tensorflow/tensor2tensor | tensor2tensor/models/research/transformer_moe.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L365-L395 | def transformer_moe_2k():
"""Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
*... | [
"def",
"transformer_moe_2k",
"(",
")",
":",
"hparams",
"=",
"transformer_moe_8k",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2048",
"hparams",
".",
"default_ff",
"=",
"\"sep\"",
"# hparams.layer_types contains the network architecture:",
"encoder_archi",
"=",
"\"a/a/... | Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
* Layer 0: a - a - sepm (self-a... | [
"Base",
"transformers",
"model",
"with",
"moe",
"."
] | python | train | 28.064516 |
SpriteLink/NIPAP | nipap-www/nipapwww/controllers/error.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap-www/nipapwww/controllers/error.py#L67-L73 | def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
request = self._py_object.request
request.environ['PATH_INFO'] = '/%s' % path
return PkgResourcesParser('pylons', 'pylons')(request.environ, self.start_re... | [
"def",
"_serve_file",
"(",
"self",
",",
"path",
")",
":",
"request",
"=",
"self",
".",
"_py_object",
".",
"request",
"request",
".",
"environ",
"[",
"'PATH_INFO'",
"]",
"=",
"'/%s'",
"%",
"path",
"return",
"PkgResourcesParser",
"(",
"'pylons'",
",",
"'pylo... | Call Paste's FileApp (a WSGI application) to serve the file
at the specified path | [
"Call",
"Paste",
"s",
"FileApp",
"(",
"a",
"WSGI",
"application",
")",
"to",
"serve",
"the",
"file",
"at",
"the",
"specified",
"path"
] | python | train | 45.857143 |
GetmeUK/MongoFrames | mongoframes/frames.py | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L218-L232 | def insert(self):
"""Insert this document"""
from mongoframes.queries import to_refs
# Send insert signal
signal('insert').send(self.__class__, frames=[self])
# Prepare the document to be inserted
document = to_refs(self._document)
# Insert the document and upd... | [
"def",
"insert",
"(",
"self",
")",
":",
"from",
"mongoframes",
".",
"queries",
"import",
"to_refs",
"# Send insert signal",
"signal",
"(",
"'insert'",
")",
".",
"send",
"(",
"self",
".",
"__class__",
",",
"frames",
"=",
"[",
"self",
"]",
")",
"# Prepare th... | Insert this document | [
"Insert",
"this",
"document"
] | python | train | 32.333333 |
COALAIP/pycoalaip | coalaip/data_formats.py | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L56-L80 | def _data_format_resolver(data_format, resolver_dict):
"""Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
... | [
"def",
"_data_format_resolver",
"(",
"data_format",
",",
"resolver_dict",
")",
":",
"try",
":",
"data_format",
"=",
"DataFormat",
"(",
"data_format",
")",
"except",
"ValueError",
":",
"supported_formats",
"=",
"', '",
".",
"join",
"(",
"[",
"\"'{}'\"",
".",
"f... | Resolve a value from :attr:`resolver_dict` based on the
:attr:`data_format`.
Args:
data_format (:class:`~.DataFormat` or str): The data format;
must be a member of :class:`~.DataFormat` or a string
equivalent.
resolver_dict (dict): the resolving dict. Can hold any value
... | [
"Resolve",
"a",
"value",
"from",
":",
"attr",
":",
"resolver_dict",
"based",
"on",
"the",
":",
"attr",
":",
"data_format",
"."
] | python | train | 40.88 |
wglass/lighthouse | lighthouse/reporter.py | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/reporter.py#L49-L54 | def on_service_add(self, service):
"""
When a new service is added, a worker thread is launched to
periodically run the checks for that service.
"""
self.launch_thread(service.name, self.check_loop, service) | [
"def",
"on_service_add",
"(",
"self",
",",
"service",
")",
":",
"self",
".",
"launch_thread",
"(",
"service",
".",
"name",
",",
"self",
".",
"check_loop",
",",
"service",
")"
] | When a new service is added, a worker thread is launched to
periodically run the checks for that service. | [
"When",
"a",
"new",
"service",
"is",
"added",
"a",
"worker",
"thread",
"is",
"launched",
"to",
"periodically",
"run",
"the",
"checks",
"for",
"that",
"service",
"."
] | python | train | 40.333333 |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py#L296-L300 | def _disable_encryption(self):
# () -> None
"""Enable encryption methods for ciphers that support them."""
self.encrypt = self._disabled_encrypt
self.decrypt = self._disabled_decrypt | [
"def",
"_disable_encryption",
"(",
"self",
")",
":",
"# () -> None",
"self",
".",
"encrypt",
"=",
"self",
".",
"_disabled_encrypt",
"self",
".",
"decrypt",
"=",
"self",
".",
"_disabled_decrypt"
] | Enable encryption methods for ciphers that support them. | [
"Enable",
"encryption",
"methods",
"for",
"ciphers",
"that",
"support",
"them",
"."
] | python | train | 42 |
Erotemic/utool | _broken/_grave.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/_broken/_grave.py#L47-L64 | def roundrobin(*iterables):
"""roundrobin('ABC', 'D', 'EF') --> A D E B F C"""
raise NotImplementedError('not sure if this implementation is correct')
# http://stackoverflow.com/questions/11125212/interleaving-lists-in-python
#sentinel = object()
#return (x for x in chain(*zip_longest(fillvalue=sent... | [
"def",
"roundrobin",
"(",
"*",
"iterables",
")",
":",
"raise",
"NotImplementedError",
"(",
"'not sure if this implementation is correct'",
")",
"# http://stackoverflow.com/questions/11125212/interleaving-lists-in-python",
"#sentinel = object()",
"#return (x for x in chain(*zip_longest(fi... | roundrobin('ABC', 'D', 'EF') --> A D E B F C | [
"roundrobin",
"(",
"ABC",
"D",
"EF",
")",
"--",
">",
"A",
"D",
"E",
"B",
"F",
"C"
] | python | train | 39.611111 |
sbg/sevenbridges-python | sevenbridges/models/division.py | https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/division.py#L34-L47 | def query(cls, offset=None, limit=None, api=None):
"""
Query (List) divisions.
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: Api instance.
:return: Collection object.
"""
api = api if api else cls._API
return super(... | [
"def",
"query",
"(",
"cls",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"api",
"=",
"None",
")",
":",
"api",
"=",
"api",
"if",
"api",
"else",
"cls",
".",
"_API",
"return",
"super",
"(",
"Division",
",",
"cls",
")",
".",
"_query",
... | Query (List) divisions.
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: Api instance.
:return: Collection object. | [
"Query",
"(",
"List",
")",
"divisions",
"."
] | python | train | 31.214286 |
RedHatInsights/insights-core | insights/client/connection.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L722-L766 | def _legacy_upload_archive(self, data_collected, duration):
'''
Do an HTTPS upload of the archive
'''
file_name = os.path.basename(data_collected)
try:
from insights.contrib import magic
m = magic.open(magic.MAGIC_MIME)
m.load()
mim... | [
"def",
"_legacy_upload_archive",
"(",
"self",
",",
"data_collected",
",",
"duration",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"data_collected",
")",
"try",
":",
"from",
"insights",
".",
"contrib",
"import",
"magic",
"m",
"=",
"... | Do an HTTPS upload of the archive | [
"Do",
"an",
"HTTPS",
"upload",
"of",
"the",
"archive"
] | python | train | 39.066667 |
saltstack/salt | salt/beacons/btmp.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/btmp.py#L266-L331 | def beacon(config):
'''
Read the last btmp file and return information on the failed logins
'''
ret = []
users = {}
groups = {}
defaults = None
for config_item in config:
if 'users' in config_item:
users = config_item['users']
if 'groups' in config_item:
... | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"users",
"=",
"{",
"}",
"groups",
"=",
"{",
"}",
"defaults",
"=",
"None",
"for",
"config_item",
"in",
"config",
":",
"if",
"'users'",
"in",
"config_item",
":",
"users",
"=",
"config_item... | Read the last btmp file and return information on the failed logins | [
"Read",
"the",
"last",
"btmp",
"file",
"and",
"return",
"information",
"on",
"the",
"failed",
"logins"
] | python | train | 34.515152 |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2156-L2172 | def insertPDF(self, docsrc, from_page=-1, to_page=-1, start_at=-1, rotate=-1, links=1):
"""Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'."""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
if id... | [
"def",
"insertPDF",
"(",
"self",
",",
"docsrc",
",",
"from_page",
"=",
"-",
"1",
",",
"to_page",
"=",
"-",
"1",
",",
"start_at",
"=",
"-",
"1",
",",
"rotate",
"=",
"-",
"1",
",",
"links",
"=",
"1",
")",
":",
"if",
"self",
".",
"isClosed",
"or",... | Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'. | [
"Copy",
"page",
"range",
"[",
"from",
"to",
"]",
"of",
"source",
"PDF",
"starting",
"as",
"page",
"number",
"start_at",
"."
] | python | train | 44.176471 |
google/grr | grr/client/grr_response_client/comms.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/comms.py#L790-L829 | def run(self):
"""Main thread for processing messages."""
self.OnStartup()
try:
while True:
message = self._in_queue.get()
# A message of None is our terminal message.
if message is None:
break
try:
self.HandleMessage(message)
# Catch a... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"OnStartup",
"(",
")",
"try",
":",
"while",
"True",
":",
"message",
"=",
"self",
".",
"_in_queue",
".",
"get",
"(",
")",
"# A message of None is our terminal message.",
"if",
"message",
"is",
"None",
":",
... | Main thread for processing messages. | [
"Main",
"thread",
"for",
"processing",
"messages",
"."
] | python | train | 36.1 |
saltstack/salt | salt/spm/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/__init__.py#L382-L389 | def _local_install(self, args, pkg_name=None):
'''
Install a package from a file
'''
if len(args) < 2:
raise SPMInvocationError('A package file must be specified')
self._install(args) | [
"def",
"_local_install",
"(",
"self",
",",
"args",
",",
"pkg_name",
"=",
"None",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"raise",
"SPMInvocationError",
"(",
"'A package file must be specified'",
")",
"self",
".",
"_install",
"(",
"args",
")... | Install a package from a file | [
"Install",
"a",
"package",
"from",
"a",
"file"
] | python | train | 28.625 |
NatLibFi/Skosify | skosify/infer.py | https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/infer.py#L94-L112 | def rdfs_classes(rdf):
"""Perform RDFS subclass inference.
Mark all resources with a subclass type with the upper class."""
# find out the subclass mappings
upperclasses = {} # key: class val: set([superclass1, superclass2..])
for s, o in rdf.subject_objects(RDFS.subClassOf):
upperclasses... | [
"def",
"rdfs_classes",
"(",
"rdf",
")",
":",
"# find out the subclass mappings",
"upperclasses",
"=",
"{",
"}",
"# key: class val: set([superclass1, superclass2..])",
"for",
"s",
",",
"o",
"in",
"rdf",
".",
"subject_objects",
"(",
"RDFS",
".",
"subClassOf",
")",
":"... | Perform RDFS subclass inference.
Mark all resources with a subclass type with the upper class. | [
"Perform",
"RDFS",
"subclass",
"inference",
"."
] | python | train | 39.263158 |
spdx/tools-python | spdx/parsers/rdf.py | https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L144-L162 | def get_extr_license_ident(self, extr_lic):
"""
Return an a license identifier from an ExtractedLicense or None.
"""
identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None)))
if not identifier_tripples:
self.error = True
... | [
"def",
"get_extr_license_ident",
"(",
"self",
",",
"extr_lic",
")",
":",
"identifier_tripples",
"=",
"list",
"(",
"self",
".",
"graph",
".",
"triples",
"(",
"(",
"extr_lic",
",",
"self",
".",
"spdx_namespace",
"[",
"'licenseId'",
"]",
",",
"None",
")",
")"... | Return an a license identifier from an ExtractedLicense or None. | [
"Return",
"an",
"a",
"license",
"identifier",
"from",
"an",
"ExtractedLicense",
"or",
"None",
"."
] | python | valid | 35.894737 |
polyaxon/rhea | rhea/manager.py | https://github.com/polyaxon/rhea/blob/f47b59777cd996d834a0497a1ab442541aaa8a62/rhea/manager.py#L329-L369 | def get_uri(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `UriSpec`... | [
"def",
"get_uri",
"(",
"self",
",",
"key",
",",
"is_list",
"=",
"False",
",",
"is_optional",
"=",
"False",
",",
"is_secret",
"=",
"False",
",",
"is_local",
"=",
"False",
",",
"default",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"if",
"is_li... | Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If ... | [
"Get",
"a",
"the",
"value",
"corresponding",
"to",
"the",
"key",
"and",
"converts",
"it",
"to",
"UriSpec",
"."
] | python | train | 43.95122 |
shoebot/shoebot | lib/photobot/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L726-L735 | def flip(self, axis=HORIZONTAL):
"""Flips the layer, either HORIZONTAL or VERTICAL.
"""
if axis == HORIZONTAL:
self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT)
if axis == VERTICAL:
self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM) | [
"def",
"flip",
"(",
"self",
",",
"axis",
"=",
"HORIZONTAL",
")",
":",
"if",
"axis",
"==",
"HORIZONTAL",
":",
"self",
".",
"img",
"=",
"self",
".",
"img",
".",
"transpose",
"(",
"Image",
".",
"FLIP_LEFT_RIGHT",
")",
"if",
"axis",
"==",
"VERTICAL",
":"... | Flips the layer, either HORIZONTAL or VERTICAL. | [
"Flips",
"the",
"layer",
"either",
"HORIZONTAL",
"or",
"VERTICAL",
"."
] | python | valid | 29.5 |
dyve/django-bootstrap3 | bootstrap3/forms.py | https://github.com/dyve/django-bootstrap3/blob/1d4095ba113a1faff228f9592bdad4f0b3aed653/bootstrap3/forms.py#L41-L46 | def render_formset(formset, **kwargs):
"""
Render a formset to a Bootstrap layout
"""
renderer_cls = get_formset_renderer(**kwargs)
return renderer_cls(formset, **kwargs).render() | [
"def",
"render_formset",
"(",
"formset",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer_cls",
"=",
"get_formset_renderer",
"(",
"*",
"*",
"kwargs",
")",
"return",
"renderer_cls",
"(",
"formset",
",",
"*",
"*",
"kwargs",
")",
".",
"render",
"(",
")"
] | Render a formset to a Bootstrap layout | [
"Render",
"a",
"formset",
"to",
"a",
"Bootstrap",
"layout"
] | python | train | 32.333333 |
oscarlazoarjona/fast | fast/magnetic_field.py | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/magnetic_field.py#L114-L160 | def paschen_back_energies(fine_state, Bz):
r"""Return Paschen-Back regime energies for a given fine state and\
magnetic field.
>>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2))
>>> Bz = 200.0
>>> Bz = Bz/10000
>>> for f_group in paschen_back_energies(ground_state, Bz):
... ... | [
"def",
"paschen_back_energies",
"(",
"fine_state",
",",
"Bz",
")",
":",
"element",
"=",
"fine_state",
".",
"element",
"isotope",
"=",
"fine_state",
".",
"isotope",
"N",
"=",
"fine_state",
".",
"n",
"L",
"=",
"fine_state",
".",
"l",
"J",
"=",
"fine_state",
... | r"""Return Paschen-Back regime energies for a given fine state and\
magnetic field.
>>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2))
>>> Bz = 200.0
>>> Bz = Bz/10000
>>> for f_group in paschen_back_energies(ground_state, Bz):
... print(f_group)
[1.51284728917866e-24 3.8048... | [
"r",
"Return",
"Paschen",
"-",
"Back",
"regime",
"energies",
"for",
"a",
"given",
"fine",
"state",
"and",
"\\",
"magnetic",
"field",
".",
">>>",
"ground_state",
"=",
"State",
"(",
"Rb",
"87",
"5",
"0",
"1",
"/",
"Integer",
"(",
"2",
"))",
">>>",
"Bz"... | python | train | 33.382979 |
Parsely/schemato | schemato/schemadef.py | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L89-L118 | def _schema_nodes(self):
"""parse self._ontology_file into a graph"""
name, ext = os.path.splitext(self._ontology_file)
if ext in ['.ttl']:
self._ontology_parser_function = \
lambda s: rdflib.Graph().parse(s, format='n3')
else:
self._ontology_parse... | [
"def",
"_schema_nodes",
"(",
"self",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"self",
".",
"_ontology_file",
")",
"if",
"ext",
"in",
"[",
"'.ttl'",
"]",
":",
"self",
".",
"_ontology_parser_function",
"=",
"lambda",
"s... | parse self._ontology_file into a graph | [
"parse",
"self",
".",
"_ontology_file",
"into",
"a",
"graph"
] | python | train | 38.533333 |
PSU-OIT-ARC/elasticmodels | elasticmodels/analysis.py | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/analysis.py#L52-L60 | def collect_analysis(using):
"""
generate the analysis settings from Python land
"""
python_analysis = defaultdict(dict)
for index in registry.indexes_for_connection(using):
python_analysis.update(index._doc_type.mapping._collect_analysis())
return stringer(python_analysis) | [
"def",
"collect_analysis",
"(",
"using",
")",
":",
"python_analysis",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"index",
"in",
"registry",
".",
"indexes_for_connection",
"(",
"using",
")",
":",
"python_analysis",
".",
"update",
"(",
"index",
".",
"_doc_type... | generate the analysis settings from Python land | [
"generate",
"the",
"analysis",
"settings",
"from",
"Python",
"land"
] | python | train | 33.222222 |
shendo/websnort | websnort/ids/suricata.py | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/suricata.py#L66-L88 | def run(self, pcap):
"""
Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
tmpdir = None
try:
tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
proc = Popen(self._s... | [
"def",
"run",
"(",
"self",
",",
"pcap",
")",
":",
"tmpdir",
"=",
"None",
"try",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'tmpsuri'",
")",
"proc",
"=",
"Popen",
"(",
"self",
".",
"_suri_cmd",
"(",
"pcap",
",",
"tmpdir",
"... | Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts | [
"Runs",
"suricata",
"against",
"the",
"supplied",
"pcap",
"."
] | python | train | 38.347826 |
faucamp/python-gsmmodem | tools/gsmtermlib/trie.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/trie.py#L117-L123 | def _allKeys(self, prefix):
""" Private implementation method. Use keys() instead. """
global dictItemsIter
result = [prefix + self.key] if self.key != None else []
for key, trie in dictItemsIter(self.slots):
result.extend(trie._allKeys(prefix + key))
... | [
"def",
"_allKeys",
"(",
"self",
",",
"prefix",
")",
":",
"global",
"dictItemsIter",
"result",
"=",
"[",
"prefix",
"+",
"self",
".",
"key",
"]",
"if",
"self",
".",
"key",
"!=",
"None",
"else",
"[",
"]",
"for",
"key",
",",
"trie",
"in",
"dictItemsIter"... | Private implementation method. Use keys() instead. | [
"Private",
"implementation",
"method",
".",
"Use",
"keys",
"()",
"instead",
"."
] | python | train | 46.714286 |
rigetti/pyquil | pyquil/paulis.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/paulis.py#L714-L739 | def check_commutation(pauli_list, pauli_two):
"""
Check if commuting a PauliTerm commutes with a list of other terms by natural calculation.
Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the
number of anti-coincidences (which must always be even for commuting Pau... | [
"def",
"check_commutation",
"(",
"pauli_list",
",",
"pauli_two",
")",
":",
"def",
"coincident_parity",
"(",
"p1",
",",
"p2",
")",
":",
"non_similar",
"=",
"0",
"p1_indices",
"=",
"set",
"(",
"p1",
".",
"_ops",
".",
"keys",
"(",
")",
")",
"p2_indices",
... | Check if commuting a PauliTerm commutes with a list of other terms by natural calculation.
Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the
number of anti-coincidences (which must always be even for commuting PauliTerms)
instead of the no. of coincidences, as in the... | [
"Check",
"if",
"commuting",
"a",
"PauliTerm",
"commutes",
"with",
"a",
"list",
"of",
"other",
"terms",
"by",
"natural",
"calculation",
".",
"Uses",
"the",
"result",
"in",
"Section",
"3",
"of",
"arXiv",
":",
"1405",
".",
"5749v2",
"modified",
"slightly",
"h... | python | train | 38.538462 |
bio2bel/bio2bel | src/bio2bel/manager/flask_manager.py | https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/flask_manager.py#L75-L98 | def _add_admin(self, app, **kwargs):
"""Add a Flask Admin interface to an application.
:param flask.Flask app: A Flask application
:param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`
:rtype: flask_admin.Admin
"""
from flask_admin import Admi... | [
"def",
"_add_admin",
"(",
"self",
",",
"app",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"flask_admin",
"import",
"Admin",
"from",
"flask_admin",
".",
"contrib",
".",
"sqla",
"import",
"ModelView",
"admin",
"=",
"Admin",
"(",
"app",
",",
"*",
"*",
"kwa... | Add a Flask Admin interface to an application.
:param flask.Flask app: A Flask application
:param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin`
:rtype: flask_admin.Admin | [
"Add",
"a",
"Flask",
"Admin",
"interface",
"to",
"an",
"application",
"."
] | python | valid | 34.75 |
hydraplatform/hydra-base | hydra_base/db/model.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L909-L928 | def add_group(self, name, desc, status):
"""
Add a new group to a network.
"""
existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first()
if existing_group is not None:
raise HydraError("A resou... | [
"def",
"add_group",
"(",
"self",
",",
"name",
",",
"desc",
",",
"status",
")",
":",
"existing_group",
"=",
"get_session",
"(",
")",
".",
"query",
"(",
"ResourceGroup",
")",
".",
"filter",
"(",
"ResourceGroup",
".",
"name",
"==",
"name",
",",
"ResourceGro... | Add a new group to a network. | [
"Add",
"a",
"new",
"group",
"to",
"a",
"network",
"."
] | python | train | 31.3 |
pytroll/trollimage | trollimage/xrimage.py | https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L227-L274 | def save(self, filename, fformat=None, fill_value=None, compute=True,
keep_palette=False, cmap=None, **format_kwargs):
"""Save the image to the given *filename*.
Args:
filename (str): Output filename
fformat (str): File format of output file (optional). Can be
... | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"fformat",
"=",
"None",
",",
"fill_value",
"=",
"None",
",",
"compute",
"=",
"True",
",",
"keep_palette",
"=",
"False",
",",
"cmap",
"=",
"None",
",",
"*",
"*",
"format_kwargs",
")",
":",
"fformat",
"... | Save the image to the given *filename*.
Args:
filename (str): Output filename
fformat (str): File format of output file (optional). Can be
one of many image formats supported by the
`rasterio` or `PIL` libraries ('jpg', 'png',
... | [
"Save",
"the",
"image",
"to",
"the",
"given",
"*",
"filename",
"*",
"."
] | python | train | 57.104167 |
OpenAgInitiative/openag_python | openag/cli/firmware/base.py | https://github.com/OpenAgInitiative/openag_python/blob/f6202340292bbf7185e1a7d4290188c0dacbb8d0/openag/cli/firmware/base.py#L49-L56 | def writeln(self, data):
"""
Write a line of text to the file
:param data: The text to write
"""
self.f.write(" "*self.indent_level)
self.f.write(data + "\n") | [
"def",
"writeln",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"f",
".",
"write",
"(",
"\" \"",
"*",
"self",
".",
"indent_level",
")",
"self",
".",
"f",
".",
"write",
"(",
"data",
"+",
"\"\\n\"",
")"
] | Write a line of text to the file
:param data: The text to write | [
"Write",
"a",
"line",
"of",
"text",
"to",
"the",
"file"
] | python | train | 25 |
davidmcclure/textplot | textplot/matrix.py | https://github.com/davidmcclure/textplot/blob/889b949a637d99097ecec44ed4bfee53b1964dee/textplot/matrix.py#L50-L63 | def set_pair(self, term1, term2, value, **kwargs):
"""
Set the value for a pair of terms.
Args:
term1 (str)
term2 (str)
value (mixed)
"""
key = self.key(term1, term2)
self.keys.update([term1, term2])
self.pairs[key] = value | [
"def",
"set_pair",
"(",
"self",
",",
"term1",
",",
"term2",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"self",
".",
"key",
"(",
"term1",
",",
"term2",
")",
"self",
".",
"keys",
".",
"update",
"(",
"[",
"term1",
",",
"term2",
"... | Set the value for a pair of terms.
Args:
term1 (str)
term2 (str)
value (mixed) | [
"Set",
"the",
"value",
"for",
"a",
"pair",
"of",
"terms",
"."
] | python | train | 21.785714 |
aegirhall/console-menu | consolemenu/menu_component.py | https://github.com/aegirhall/console-menu/blob/1a28959d6f1dd6ac79c87b11efd8529d05532422/consolemenu/menu_component.py#L92-L102 | def calculate_content_width(self):
"""
Calculate the width of inner content of the border. This will be the width of the menu borders,
minus the left and right padding, and minus the two vertical border characters.
For example, given a border width of 77, with left and right margins eac... | [
"def",
"calculate_content_width",
"(",
"self",
")",
":",
"return",
"self",
".",
"calculate_border_width",
"(",
")",
"-",
"self",
".",
"padding",
".",
"left",
"-",
"self",
".",
"padding",
".",
"right",
"-",
"2"
] | Calculate the width of inner content of the border. This will be the width of the menu borders,
minus the left and right padding, and minus the two vertical border characters.
For example, given a border width of 77, with left and right margins each set to 2, the content
width would be 71 (77 -... | [
"Calculate",
"the",
"width",
"of",
"inner",
"content",
"of",
"the",
"border",
".",
"This",
"will",
"be",
"the",
"width",
"of",
"the",
"menu",
"borders",
"minus",
"the",
"left",
"and",
"right",
"padding",
"and",
"minus",
"the",
"two",
"vertical",
"border",
... | python | train | 50.454545 |
Tanganelli/CoAPthon3 | coapthon/serializer.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/serializer.py#L20-L129 | def deserialize(datagram, source):
"""
De-serialize a stream of byte to a message.
:param datagram: the incoming udp message
:param source: the source address and port (ip, port)
:return: the message
:rtype: Message
"""
try:
fmt = "!BBH"
... | [
"def",
"deserialize",
"(",
"datagram",
",",
"source",
")",
":",
"try",
":",
"fmt",
"=",
"\"!BBH\"",
"pos",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"s",
"=",
"struct",
".",
"Struct",
"(",
"fmt",
")",
"values",
"=",
"s",
".",
"unpack_from",
... | De-serialize a stream of byte to a message.
:param datagram: the incoming udp message
:param source: the source address and port (ip, port)
:return: the message
:rtype: Message | [
"De",
"-",
"serialize",
"a",
"stream",
"of",
"byte",
"to",
"a",
"message",
"."
] | python | train | 43.590909 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15156-L15177 | def vsubg(v1, v2, ndim):
"""
Compute the difference between two double precision
vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html
:param v1: First vector (minuend).
:type v1: Array of floats
:param v2: Second vector (subtrahend).
:t... | [
"def",
"vsubg",
"(",
"v1",
",",
"v2",
",",
"ndim",
")",
":",
"v1",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"v1",
")",
"v2",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"v2",
")",
"vout",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"ndim",
")",
... | Compute the difference between two double precision
vectors of arbitrary dimension.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html
:param v1: First vector (minuend).
:type v1: Array of floats
:param v2: Second vector (subtrahend).
:type v2: Array of floats
:param nd... | [
"Compute",
"the",
"difference",
"between",
"two",
"double",
"precision",
"vectors",
"of",
"arbitrary",
"dimension",
"."
] | python | train | 31.409091 |
cltl/KafNafParserPy | KafNafParserPy/markable_data.py | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/markable_data.py#L261-L277 | def remove_markables(self,list_mark_ids):
"""
Removes a list of markables from the layer
@type list_term_ids: list
@param list_term_ids: list of markable identifiers to be removed
"""
nodes_to_remove = set()
for markable in self:
if markable.get_id()... | [
"def",
"remove_markables",
"(",
"self",
",",
"list_mark_ids",
")",
":",
"nodes_to_remove",
"=",
"set",
"(",
")",
"for",
"markable",
"in",
"self",
":",
"if",
"markable",
".",
"get_id",
"(",
")",
"in",
"list_mark_ids",
":",
"nodes_to_remove",
".",
"add",
"("... | Removes a list of markables from the layer
@type list_term_ids: list
@param list_term_ids: list of markable identifiers to be removed | [
"Removes",
"a",
"list",
"of",
"markables",
"from",
"the",
"layer"
] | python | train | 38.117647 |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L4312-L4321 | def _parse_caps_devices_features(node):
'''
Parse the devices or features list of the domain capatilities
'''
result = {}
for child in node:
if child.get('supported') == 'yes':
enums = [_parse_caps_enum(node) for node in child.findall('enum')]
result[child.tag] = {ite... | [
"def",
"_parse_caps_devices_features",
"(",
"node",
")",
":",
"result",
"=",
"{",
"}",
"for",
"child",
"in",
"node",
":",
"if",
"child",
".",
"get",
"(",
"'supported'",
")",
"==",
"'yes'",
":",
"enums",
"=",
"[",
"_parse_caps_enum",
"(",
"node",
")",
"... | Parse the devices or features list of the domain capatilities | [
"Parse",
"the",
"devices",
"or",
"features",
"list",
"of",
"the",
"domain",
"capatilities"
] | python | train | 37.2 |
bristosoft/financial | finance.py | https://github.com/bristosoft/financial/blob/382c4fef610d67777d7109d9d0ae230ab67ca20f/finance.py#L90-L100 | def syd(c, s, l):
""" This accountancy function computes sum of the years
digits depreciation for an asset purchased for cash
with a known life span and salvage value. The depreciation
is returned as a list in python.
c = historcal cost or price paid
s = the expected salvage proceeds
l =... | [
"def",
"syd",
"(",
"c",
",",
"s",
",",
"l",
")",
":",
"return",
"[",
"(",
"c",
"-",
"s",
")",
"*",
"(",
"x",
"/",
"(",
"l",
"*",
"(",
"l",
"+",
"1",
")",
"/",
"2",
")",
")",
"for",
"x",
"in",
"range",
"(",
"l",
",",
"0",
",",
"-",
... | This accountancy function computes sum of the years
digits depreciation for an asset purchased for cash
with a known life span and salvage value. The depreciation
is returned as a list in python.
c = historcal cost or price paid
s = the expected salvage proceeds
l = expected useful life of the ... | [
"This",
"accountancy",
"function",
"computes",
"sum",
"of",
"the",
"years",
"digits",
"depreciation",
"for",
"an",
"asset",
"purchased",
"for",
"cash",
"with",
"a",
"known",
"life",
"span",
"and",
"salvage",
"value",
".",
"The",
"depreciation",
"is",
"returned... | python | train | 40.818182 |
Jammy2211/PyAutoLens | autolens/data/array/mask.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L69-L86 | def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
... | [
"def",
"circular",
"(",
"cls",
",",
"shape",
",",
"pixel_scale",
",",
"radius_arcsec",
",",
"centre",
"=",
"(",
"0.",
",",
"0.",
")",
",",
"invert",
"=",
"False",
")",
":",
"mask",
"=",
"mask_util",
".",
"mask_circular_from_shape_pixel_scale_and_radius",
"("... | Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
... | [
"Setup",
"a",
"mask",
"where",
"unmasked",
"pixels",
"are",
"within",
"a",
"circle",
"of",
"an",
"input",
"arc",
"second",
"radius",
"and",
"centre",
"."
] | python | valid | 50.722222 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L525-L543 | def load_payload(self, payload, serializer=None):
"""Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based.
... | [
"def",
"load_payload",
"(",
"self",
",",
"payload",
",",
"serializer",
"=",
"None",
")",
":",
"if",
"serializer",
"is",
"None",
":",
"serializer",
"=",
"self",
".",
"serializer",
"is_text",
"=",
"self",
".",
"is_text_serializer",
"else",
":",
"is_text",
"=... | Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based. | [
"Loads",
"the",
"encoded",
"object",
".",
"This",
"function",
"raises",
":",
"class",
":",
"BadPayload",
"if",
"the",
"payload",
"is",
"not",
"valid",
".",
"The",
"serializer",
"parameter",
"can",
"be",
"used",
"to",
"override",
"the",
"serializer",
"stored"... | python | test | 43.263158 |
saltstack/salt | salt/modules/boto_elasticache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elasticache.py#L362-L387 | def get_all_cache_subnet_groups(name=None, region=None, key=None,
keyid=None, profile=None):
'''
Return a list of all cache subnet groups with details
CLI example::
salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1
'''
conn = _get_conn(re... | [
"def",
"get_all_cache_subnet_groups",
"(",
"name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
... | Return a list of all cache subnet groups with details
CLI example::
salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1 | [
"Return",
"a",
"list",
"of",
"all",
"cache",
"subnet",
"groups",
"with",
"details"
] | python | train | 39.346154 |
django-import-export/django-import-export | import_export/resources.py | https://github.com/django-import-export/django-import-export/blob/127f00d03fd0ad282615b064b7f444a639e6ff0c/import_export/resources.py#L259-L267 | def get_or_init_instance(self, instance_loader, row):
"""
Either fetches an already existing instance or initializes a new one.
"""
instance = self.get_instance(instance_loader, row)
if instance:
return (instance, False)
else:
return (self.init_ins... | [
"def",
"get_or_init_instance",
"(",
"self",
",",
"instance_loader",
",",
"row",
")",
":",
"instance",
"=",
"self",
".",
"get_instance",
"(",
"instance_loader",
",",
"row",
")",
"if",
"instance",
":",
"return",
"(",
"instance",
",",
"False",
")",
"else",
":... | Either fetches an already existing instance or initializes a new one. | [
"Either",
"fetches",
"an",
"already",
"existing",
"instance",
"or",
"initializes",
"a",
"new",
"one",
"."
] | python | train | 36.555556 |
pypyr/pypyr-cli | pypyr/utils/filesystem.py | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/utils/filesystem.py#L341-L354 | def dump(self, file, payload):
"""Dump json oject to open file output.
Writes json with 2 spaces indentation.
Args:
file: Open file-like object. Must be open for writing.
payload: The Json object to write to file.
Returns:
None.
"""
... | [
"def",
"dump",
"(",
"self",
",",
"file",
",",
"payload",
")",
":",
"json",
".",
"dump",
"(",
"payload",
",",
"file",
",",
"indent",
"=",
"2",
",",
"ensure_ascii",
"=",
"False",
")"
] | Dump json oject to open file output.
Writes json with 2 spaces indentation.
Args:
file: Open file-like object. Must be open for writing.
payload: The Json object to write to file.
Returns:
None. | [
"Dump",
"json",
"oject",
"to",
"open",
"file",
"output",
"."
] | python | train | 25.857143 |
liminspace/dju-common | dju_common/tools.py | https://github.com/liminspace/dju-common/blob/c68860bb84d454a35e66275841c20f38375c2135/dju_common/tools.py#L53-L67 | def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True):
"""
Convert result from datetime_to_dtstr to datetime in timezone UTC0.
"""
try:
dt = datetime.datetime.utcfromtimestamp(int(dtstr, 36) / 1e3)
if to_tz:
dt = timezone.make_aware(dt, timezone=pytz.UTC)
i... | [
"def",
"dtstr_to_datetime",
"(",
"dtstr",
",",
"to_tz",
"=",
"None",
",",
"fail_silently",
"=",
"True",
")",
":",
"try",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"int",
"(",
"dtstr",
",",
"36",
")",
"/",
"1e3",
")",
... | Convert result from datetime_to_dtstr to datetime in timezone UTC0. | [
"Convert",
"result",
"from",
"datetime_to_dtstr",
"to",
"datetime",
"in",
"timezone",
"UTC0",
"."
] | python | train | 32.133333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.