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 |
|---|---|---|---|---|---|---|---|---|---|
apache/spark | python/pyspark/sql/readwriter.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/readwriter.py#L116-L125 | def option(self, key, value):
"""Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values.
If it isn't set, it uses the default value, session local timezone.
"""
self._jreader = self._jreader.option(key, to_str(value))
return self | [
"def",
"option",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_jreader",
"=",
"self",
".",
"_jreader",
".",
"option",
"(",
"key",
",",
"to_str",
"(",
"value",
")",
")",
"return",
"self"
] | Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values.
If it isn't set, it uses the default value, session local timezone. | [
"Adds",
"an",
"input",
"option",
"for",
"the",
"underlying",
"data",
"source",
"."
] | python | train | 49.5 |
guaix-ucm/pyemir | emirdrp/products.py | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/products.py#L97-L105 | def convert_out(self, obj):
"""Write EMIRUUID header on reduction"""
newobj = super(ProcessedImageProduct, self).convert_out(obj)
if newobj:
hdulist = newobj.open()
hdr = hdulist[0].header
if 'EMIRUUID' not in hdr:
hdr['EMIRUUID'] = str(uuid.uuid1())
return newobj | [
"def",
"convert_out",
"(",
"self",
",",
"obj",
")",
":",
"newobj",
"=",
"super",
"(",
"ProcessedImageProduct",
",",
"self",
")",
".",
"convert_out",
"(",
"obj",
")",
"if",
"newobj",
":",
"hdulist",
"=",
"newobj",
".",
"open",
"(",
")",
"hdr",
"=",
"h... | Write EMIRUUID header on reduction | [
"Write",
"EMIRUUID",
"header",
"on",
"reduction"
] | python | train | 37.777778 |
odooku/odooku | odooku/services/websocket/requests.py | https://github.com/odooku/odooku/blob/52dff30a9b75299eaac043f06a4943c9be759bd6/odooku/services/websocket/requests.py#L48-L68 | def _handle_exception(self, exception):
"""Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response."""
try:
return super(WebSocketRpcRequest, self)._handle_exception(exception)
except Exception:
if not isinstance(exception, (odoo.exceptions.Warning, odoo.http.SessionExpiredException, odoo.exceptions.except_orm)):
_logger.exception("Exception during JSON request handling.")
error = {
'code': 200,
'message': "Odoo Server Error",
'data': odoo.http.serialize_exception(exception)
}
if isinstance(exception, odoo.http.AuthenticationError):
error['code'] = 100
error['message'] = "Odoo Session Invalid"
if isinstance(exception, odoo.http.SessionExpiredException):
error['code'] = 100
error['message'] = "Odoo Session Expired"
return self._json_response(error=error) | [
"def",
"_handle_exception",
"(",
"self",
",",
"exception",
")",
":",
"try",
":",
"return",
"super",
"(",
"WebSocketRpcRequest",
",",
"self",
")",
".",
"_handle_exception",
"(",
"exception",
")",
"except",
"Exception",
":",
"if",
"not",
"isinstance",
"(",
"ex... | Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response. | [
"Called",
"within",
"an",
"except",
"block",
"to",
"allow",
"converting",
"exceptions",
"to",
"arbitrary",
"responses",
".",
"Anything",
"returned",
"(",
"except",
"None",
")",
"will",
"be",
"used",
"as",
"response",
"."
] | python | train | 52.333333 |
kivy/python-for-android | pythonforandroid/recipe.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/recipe.py#L440-L448 | def prebuild_arch(self, arch):
'''Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.'''
prebuild = "prebuild_{}".format(arch.arch.replace('-', '_'))
if hasattr(self, prebuild):
getattr(self, prebuild)()
else:
info('{} has no {}, skipping'.format(self.name, prebuild)) | [
"def",
"prebuild_arch",
"(",
"self",
",",
"arch",
")",
":",
"prebuild",
"=",
"\"prebuild_{}\"",
".",
"format",
"(",
"arch",
".",
"arch",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"prebuild",
")",
":",
"getat... | Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so. | [
"Run",
"any",
"pre",
"-",
"build",
"tasks",
"for",
"the",
"Recipe",
".",
"By",
"default",
"this",
"checks",
"if",
"any",
"prebuild_archname",
"methods",
"exist",
"for",
"the",
"archname",
"of",
"the",
"current",
"architecture",
"and",
"runs",
"them",
"if",
... | python | train | 50 |
avalente/appmetrics | appmetrics/histogram.py | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/histogram.py#L272-L279 | def _put(self, timestamp, value):
"""Replace the value associated with "timestamp" or add the new value"""
idx = self._lookup(timestamp)
if idx is not None:
self._values[idx] = (timestamp, value)
else:
self._values.append((timestamp, value)) | [
"def",
"_put",
"(",
"self",
",",
"timestamp",
",",
"value",
")",
":",
"idx",
"=",
"self",
".",
"_lookup",
"(",
"timestamp",
")",
"if",
"idx",
"is",
"not",
"None",
":",
"self",
".",
"_values",
"[",
"idx",
"]",
"=",
"(",
"timestamp",
",",
"value",
... | Replace the value associated with "timestamp" or add the new value | [
"Replace",
"the",
"value",
"associated",
"with",
"timestamp",
"or",
"add",
"the",
"new",
"value"
] | python | train | 36.375 |
senaite/senaite.core | bika/lims/idserver.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/idserver.py#L353-L358 | def get_ids_with_prefix(portal_type, prefix):
"""Return a list of ids sharing the same portal type and prefix
"""
brains = search_by_prefix(portal_type, prefix)
ids = map(api.get_id, brains)
return ids | [
"def",
"get_ids_with_prefix",
"(",
"portal_type",
",",
"prefix",
")",
":",
"brains",
"=",
"search_by_prefix",
"(",
"portal_type",
",",
"prefix",
")",
"ids",
"=",
"map",
"(",
"api",
".",
"get_id",
",",
"brains",
")",
"return",
"ids"
] | Return a list of ids sharing the same portal type and prefix | [
"Return",
"a",
"list",
"of",
"ids",
"sharing",
"the",
"same",
"portal",
"type",
"and",
"prefix"
] | python | train | 36 |
GoogleCloudPlatform/datastore-ndb-python | demo/app/fibo.py | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/demo/app/fibo.py#L46-L63 | def memoizing_fibonacci(n):
"""A memoizing recursive Fibonacci to exercise RPCs."""
if n <= 1:
raise ndb.Return(n)
key = ndb.Key(FibonacciMemo, str(n))
memo = yield key.get_async(ndb_should_cache=False)
if memo is not None:
assert memo.arg == n
logging.info('memo hit: %d -> %d', n, memo.value)
raise ndb.Return(memo.value)
logging.info('memo fail: %d', n)
a = yield memoizing_fibonacci(n - 1)
b = yield memoizing_fibonacci(n - 2)
ans = a + b
memo = FibonacciMemo(key=key, arg=n, value=ans)
logging.info('memo write: %d -> %d', n, memo.value)
yield memo.put_async(ndb_should_cache=False)
raise ndb.Return(ans) | [
"def",
"memoizing_fibonacci",
"(",
"n",
")",
":",
"if",
"n",
"<=",
"1",
":",
"raise",
"ndb",
".",
"Return",
"(",
"n",
")",
"key",
"=",
"ndb",
".",
"Key",
"(",
"FibonacciMemo",
",",
"str",
"(",
"n",
")",
")",
"memo",
"=",
"yield",
"key",
".",
"g... | A memoizing recursive Fibonacci to exercise RPCs. | [
"A",
"memoizing",
"recursive",
"Fibonacci",
"to",
"exercise",
"RPCs",
"."
] | python | train | 35.222222 |
rbarrois/django_xworkflows | django_xworkflows/models.py | https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L115-L123 | def contribute_to_class(self, cls, name):
"""Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute.
"""
super(StateField, self).contribute_to_class(cls, name)
parent_property = getattr(cls, self.name, None)
setattr(cls, self.name, StateFieldProperty(self, parent_property)) | [
"def",
"contribute_to_class",
"(",
"self",
",",
"cls",
",",
"name",
")",
":",
"super",
"(",
"StateField",
",",
"self",
")",
".",
"contribute_to_class",
"(",
"cls",
",",
"name",
")",
"parent_property",
"=",
"getattr",
"(",
"cls",
",",
"self",
".",
"name",... | Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute. | [
"Contribute",
"the",
"state",
"to",
"a",
"Model",
"."
] | python | train | 38.444444 |
wummel/patool | patoolib/__init__.py | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L427-L430 | def make_file_readable (filename):
"""Make file user readable if it is not a link."""
if not os.path.islink(filename):
util.set_mode(filename, stat.S_IRUSR) | [
"def",
"make_file_readable",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"filename",
")",
":",
"util",
".",
"set_mode",
"(",
"filename",
",",
"stat",
".",
"S_IRUSR",
")"
] | Make file user readable if it is not a link. | [
"Make",
"file",
"user",
"readable",
"if",
"it",
"is",
"not",
"a",
"link",
"."
] | python | train | 42.25 |
rfarley3/Kibana | kibana/manager.py | https://github.com/rfarley3/Kibana/blob/3df1e13be18edfb39ec173d8d2bbe9e90be61022/kibana/manager.py#L161-L163 | def json_dumps(self, obj):
"""Serializer for consistency"""
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) | [
"def",
"json_dumps",
"(",
"self",
",",
"obj",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")"
] | Serializer for consistency | [
"Serializer",
"for",
"consistency"
] | python | train | 48.666667 |
kennethreitz/requests-html | requests_html.py | https://github.com/kennethreitz/requests-html/blob/b59a9f2fb9333d7d467154a0fd82978efdb9d23b/requests_html.py#L119-L136 | def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers.
"""
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._html:
self._encoding = html_to_unicode(self.default_encoding, self._html)[0]
# Fall back to requests' detected encoding if decode fails.
try:
self.raw_html.decode(self.encoding, errors='replace')
except UnicodeDecodeError:
self._encoding = self.default_encoding
return self._encoding if self._encoding else self.default_encoding | [
"def",
"encoding",
"(",
"self",
")",
"->",
"_Encoding",
":",
"if",
"self",
".",
"_encoding",
":",
"return",
"self",
".",
"_encoding",
"# Scan meta tags for charset.",
"if",
"self",
".",
"_html",
":",
"self",
".",
"_encoding",
"=",
"html_to_unicode",
"(",
"se... | The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers. | [
"The",
"encoding",
"string",
"to",
"be",
"used",
"extracted",
"from",
"the",
"HTML",
"and",
":",
"class",
":",
"HTMLResponse",
"<HTMLResponse",
">",
"headers",
"."
] | python | train | 38.222222 |
fhcrc/taxtastic | taxtastic/refpkg.py | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L256-L260 | def resource_md5(self, resource):
"""Return the stored MD5 sum for a particular named resource."""
if not(resource in self.contents['md5']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.contents['md5'][resource] | [
"def",
"resource_md5",
"(",
"self",
",",
"resource",
")",
":",
"if",
"not",
"(",
"resource",
"in",
"self",
".",
"contents",
"[",
"'md5'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"No such resource %r in refpkg\"",
"%",
"(",
"resource",
",",
")",
")",
... | Return the stored MD5 sum for a particular named resource. | [
"Return",
"the",
"stored",
"MD5",
"sum",
"for",
"a",
"particular",
"named",
"resource",
"."
] | python | train | 54.8 |
thiagopbueno/pyrddl | pyrddl/parser.py | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/parser.py#L343-L350 | def p_pvar_list(self, p):
'''pvar_list : pvar_list pvar_def
| empty'''
if p[1] is None:
p[0] = []
else:
p[1].append(p[2])
p[0] = p[1] | [
"def",
"p_pvar_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"p",
"[",
"1",
"]",
"is",
"None",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
"... | pvar_list : pvar_list pvar_def
| empty | [
"pvar_list",
":",
"pvar_list",
"pvar_def",
"|",
"empty"
] | python | train | 25.875 |
adamheins/r12 | r12/arm.py | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L36-L39 | def r12_serial_port(port):
''' Create a serial connect to the arm. '''
return serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY,
stopbits=STOP_BITS, bytesize=BYTE_SIZE) | [
"def",
"r12_serial_port",
"(",
"port",
")",
":",
"return",
"serial",
".",
"Serial",
"(",
"port",
",",
"baudrate",
"=",
"BAUD_RATE",
",",
"parity",
"=",
"PARITY",
",",
"stopbits",
"=",
"STOP_BITS",
",",
"bytesize",
"=",
"BYTE_SIZE",
")"
] | Create a serial connect to the arm. | [
"Create",
"a",
"serial",
"connect",
"to",
"the",
"arm",
"."
] | python | train | 50.5 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/werkzeug/debug/tbtools.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/werkzeug/debug/tbtools.py#L152-L169 | def get_current_traceback(ignore_system_exceptions=False,
show_hidden_frames=False, skip=0):
"""Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter.
"""
exc_type, exc_value, tb = sys.exc_info()
if ignore_system_exceptions and exc_type in system_exceptions:
raise
for x in range_type(skip):
if tb.tb_next is None:
break
tb = tb.tb_next
tb = Traceback(exc_type, exc_value, tb)
if not show_hidden_frames:
tb.filter_hidden_frames()
return tb | [
"def",
"get_current_traceback",
"(",
"ignore_system_exceptions",
"=",
"False",
",",
"show_hidden_frames",
"=",
"False",
",",
"skip",
"=",
"0",
")",
":",
"exc_type",
",",
"exc_value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"ignore_system_except... | Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter. | [
"Get",
"the",
"current",
"exception",
"info",
"as",
"Traceback",
"object",
".",
"Per",
"default",
"calling",
"this",
"method",
"will",
"reraise",
"system",
"exceptions",
"such",
"as",
"generator",
"exit",
"system",
"exit",
"or",
"others",
".",
"This",
"behavio... | python | test | 40.666667 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/pefile.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/pefile.py#L944-L971 | def dump(self, indentation=0):
"""Returns a string representation of the structure."""
dump = []
dump.append('[%s]' % self.name)
# Refer to the __set_format__ method for an explanation
# of the following construct.
for keys in self.__keys__:
for key in keys:
val = getattr(self, key)
if isinstance(val, int) or isinstance(val, long):
val_str = '0x%-8X' % (val)
if key == 'TimeDateStamp' or key == 'dwTimeStamp':
try:
val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
except exceptions.ValueError, e:
val_str += ' [INVALID TIME]'
else:
val_str = ''.join(filter(lambda c:c != '\0', str(val)))
dump.append('0x%-8X 0x%-3X %-30s %s' % (
self.__field_offsets__[key] + self.__file_offset__,
self.__field_offsets__[key], key+':', val_str))
return dump | [
"def",
"dump",
"(",
"self",
",",
"indentation",
"=",
"0",
")",
":",
"dump",
"=",
"[",
"]",
"dump",
".",
"append",
"(",
"'[%s]'",
"%",
"self",
".",
"name",
")",
"# Refer to the __set_format__ method for an explanation",
"# of the following construct.",
"for",
"ke... | Returns a string representation of the structure. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"structure",
"."
] | python | train | 40.321429 |
wummel/patool | patoolib/programs/cpio.py | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/cpio.py#L44-L56 | def create_cpio(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a CPIO archive."""
cmdlist = [util.shell_quote(cmd), '--create']
if verbosity > 1:
cmdlist.append('-v')
if len(filenames) != 0:
findcmd = ['find']
findcmd.extend([util.shell_quote(x) for x in filenames])
findcmd.extend(['-print0', '|'])
cmdlist[0:0] = findcmd
cmdlist.append('-0')
cmdlist.extend([">", util.shell_quote(archive)])
return (cmdlist, {'shell': True}) | [
"def",
"create_cpio",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"cmdlist",
"=",
"[",
"util",
".",
"shell_quote",
"(",
"cmd",
")",
",",
"'--create'",
"]",
"if",
"verbosity",
">",
"1",... | Create a CPIO archive. | [
"Create",
"a",
"CPIO",
"archive",
"."
] | python | train | 39.384615 |
PrefPy/prefpy | prefpy/aggregate.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/aggregate.py#L55-L69 | def get_alternatives(self, rank):
"""
Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist.
"""
if self.ranks_to_alts is None:
raise ValueError("Aggregate ranking must be created first")
try:
alts = self.ranks_to_alts[rank]
return alts
except KeyError:
raise KeyError("No ranking \"{}\" found in ".format(str(rank)) +
"the aggregate ranking") | [
"def",
"get_alternatives",
"(",
"self",
",",
"rank",
")",
":",
"if",
"self",
".",
"ranks_to_alts",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Aggregate ranking must be created first\"",
")",
"try",
":",
"alts",
"=",
"self",
".",
"ranks_to_alts",
"[",
"r... | Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist. | [
"Description",
":",
"Returns",
"the",
"alternative",
"(",
"s",
")",
"with",
"the",
"given",
"ranking",
"in",
"the",
"computed",
"aggregate",
"ranking",
".",
"An",
"error",
"is",
"thrown",
"if",
"the",
"ranking",
"does",
"not",
"exist",
"."
] | python | train | 39.866667 |
char16t/wa | wa/api.py | https://github.com/char16t/wa/blob/ee28bf47665ea57f3a03a08dfc0a5daaa33d8121/wa/api.py#L130-L150 | def copy_tree_and_replace_vars(self, src, dst):
"""
Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться
"""
if os.path.isdir(src):
copy_tree(src, self.temp_dir)
elif os.path.isfile(src):
shutil.copy(src, self.temp_dir)
for root, subdirs, files in os.walk(self.temp_dir, topdown=False):
for file in files:
self.replace_f(os.path.join(root, file))
for subdir in subdirs:
self.replace_d(os.path.join(root, subdir))
copy_tree(self.temp_dir, dst)
# Очистить временную директорию
shutil.rmtree(self.temp_dir)
os.makedirs(self.temp_dir) | [
"def",
"copy_tree_and_replace_vars",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"src",
")",
":",
"copy_tree",
"(",
"src",
",",
"self",
".",
"temp_dir",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"... | Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться | [
"Если",
"передается",
"директория",
"в",
"качестве",
"аргумента",
"то",
"будет",
"рассматриваться",
"как",
"шаблон",
"именно",
"её",
"содержимое!!",
"Оно",
"же",
"и",
"будет",
"копироваться"
] | python | train | 36.714286 |
ethereum/web3.py | web3/pm.py | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L531-L539 | def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
return self.registry._get_release_id(package_name, version) | [
"def",
"get_release_id",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"version",
":",
"str",
")",
"->",
"bytes",
":",
"validate_package_name",
"(",
"package_name",
")",
"validate_package_version",
"(",
"version",
")",
"self",
".",
"_validate_set_registry",
... | Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry. | [
"Returns",
"the",
"32",
"byte",
"identifier",
"of",
"a",
"release",
"for",
"the",
"given",
"package",
"name",
"and",
"version",
"if",
"they",
"are",
"available",
"on",
"the",
"current",
"registry",
"."
] | python | train | 46.888889 |
b3j0f/aop | b3j0f/aop/advice/core.py | https://github.com/b3j0f/aop/blob/22b9ba335d103edd929c25eb6dbb94037d3615bc/b3j0f/aop/advice/core.py#L208-L218 | def _namematcher(regex):
"""Checks if a target name matches with an input regular expression."""
matcher = re_compile(regex)
def match(target):
target_name = getattr(target, '__name__', '')
result = matcher.match(target_name)
return result
return match | [
"def",
"_namematcher",
"(",
"regex",
")",
":",
"matcher",
"=",
"re_compile",
"(",
"regex",
")",
"def",
"match",
"(",
"target",
")",
":",
"target_name",
"=",
"getattr",
"(",
"target",
",",
"'__name__'",
",",
"''",
")",
"result",
"=",
"matcher",
".",
"ma... | Checks if a target name matches with an input regular expression. | [
"Checks",
"if",
"a",
"target",
"name",
"matches",
"with",
"an",
"input",
"regular",
"expression",
"."
] | python | train | 25.909091 |
hvac/hvac | hvac/api/secrets_engines/aws.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/secrets_engines/aws.py#L17-L68 | def configure_root_iam_credentials(self, access_key, secret_key, region=None, iam_endpoint=None, sts_endpoint=None,
max_retries=-1, mount_point=DEFAULT_MOUNT_POINT):
"""Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest
precedence first. If credentials already exist, this will overwrite them.
The official AWS SDK is used for sourcing credentials from env vars, shared files, or IAM/ECS instances.
* Static credentials provided to the API as a payload
* Credentials in the AWS_ACCESS_KEY, AWS_SECRET_KEY, and AWS_REGION environment variables on the server
* Shared credentials files
* Assigned IAM role or ECS task role credentials
At present, this endpoint does not confirm that the provided AWS credentials are valid AWS credentials with
proper permissions.
Supported methods:
POST: /{mount_point}/config/root. Produces: 204 (empty body)
:param access_key: Specifies the AWS access key ID.
:type access_key: str | unicode
:param secret_key: Specifies the AWS secret access key.
:type secret_key: str | unicode
:param region: Specifies the AWS region. If not set it will use the AWS_REGION env var, AWS_DEFAULT_REGION env
var, or us-east-1 in that order.
:type region: str | unicode
:param iam_endpoint: Specifies a custom HTTP IAM endpoint to use.
:type iam_endpoint: str | unicode
:param sts_endpoint: Specifies a custom HTTP STS endpoint to use.
:type sts_endpoint: str | unicode
:param max_retries: Number of max retries the client should use for recoverable errors. The default (-1) falls
back to the AWS SDK's default behavior.
:type max_retries: int
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
params = {
'access_key': access_key,
'secret_key': secret_key,
'region': region,
'iam_endpoint': iam_endpoint,
'sts_endpoint': sts_endpoint,
'max_retries': max_retries,
}
api_path = '/v1/{mount_point}/config/root'.format(mount_point=mount_point)
return self._adapter.post(
url=api_path,
json=params,
) | [
"def",
"configure_root_iam_credentials",
"(",
"self",
",",
"access_key",
",",
"secret_key",
",",
"region",
"=",
"None",
",",
"iam_endpoint",
"=",
"None",
",",
"sts_endpoint",
"=",
"None",
",",
"max_retries",
"=",
"-",
"1",
",",
"mount_point",
"=",
"DEFAULT_MOU... | Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest
precedence first. If credentials already exist, this will overwrite them.
The official AWS SDK is used for sourcing credentials from env vars, shared files, or IAM/ECS instances.
* Static credentials provided to the API as a payload
* Credentials in the AWS_ACCESS_KEY, AWS_SECRET_KEY, and AWS_REGION environment variables on the server
* Shared credentials files
* Assigned IAM role or ECS task role credentials
At present, this endpoint does not confirm that the provided AWS credentials are valid AWS credentials with
proper permissions.
Supported methods:
POST: /{mount_point}/config/root. Produces: 204 (empty body)
:param access_key: Specifies the AWS access key ID.
:type access_key: str | unicode
:param secret_key: Specifies the AWS secret access key.
:type secret_key: str | unicode
:param region: Specifies the AWS region. If not set it will use the AWS_REGION env var, AWS_DEFAULT_REGION env
var, or us-east-1 in that order.
:type region: str | unicode
:param iam_endpoint: Specifies a custom HTTP IAM endpoint to use.
:type iam_endpoint: str | unicode
:param sts_endpoint: Specifies a custom HTTP STS endpoint to use.
:type sts_endpoint: str | unicode
:param max_retries: Number of max retries the client should use for recoverable errors. The default (-1) falls
back to the AWS SDK's default behavior.
:type max_retries: int
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the request.
:rtype: requests.Response | [
"Configure",
"the",
"root",
"IAM",
"credentials",
"to",
"communicate",
"with",
"AWS",
"."
] | python | train | 49.019231 |
hvac/hvac | hvac/v1/__init__.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/v1/__init__.py#L1313-L1329 | def get_role_secret_id(self, role_name, secret_id, mount_point='approle'):
"""POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
url = '/v1/auth/{0}/role/{1}/secret-id/lookup'.format(mount_point, role_name)
params = {
'secret_id': secret_id
}
return self._adapter.post(url, json=params).json() | [
"def",
"get_role_secret_id",
"(",
"self",
",",
"role_name",
",",
"secret_id",
",",
"mount_point",
"=",
"'approle'",
")",
":",
"url",
"=",
"'/v1/auth/{0}/role/{1}/secret-id/lookup'",
".",
"format",
"(",
"mount_point",
",",
"role_name",
")",
"params",
"=",
"{",
"'... | POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
:rtype: | [
"POST",
"/",
"auth",
"/",
"<mount_point",
">",
"/",
"role",
"/",
"<role",
"name",
">",
"/",
"secret",
"-",
"id",
"/",
"lookup"
] | python | train | 31.764706 |
flo-compbio/genometools | genometools/expression/gene_table.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L97-L100 | def genes(self):
"""Return a list of all genes."""
return [ExpGene.from_series(g)
for i, g in self.reset_index().iterrows()] | [
"def",
"genes",
"(",
"self",
")",
":",
"return",
"[",
"ExpGene",
".",
"from_series",
"(",
"g",
")",
"for",
"i",
",",
"g",
"in",
"self",
".",
"reset_index",
"(",
")",
".",
"iterrows",
"(",
")",
"]"
] | Return a list of all genes. | [
"Return",
"a",
"list",
"of",
"all",
"genes",
"."
] | python | train | 38.25 |
tdryer/hangups | hangups/conversation.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L825-L834 | def _add_conversation(self, conversation, events=[],
event_cont_token=None):
"""Add new conversation from hangouts_pb2.Conversation"""
# pylint: disable=dangerous-default-value
conv_id = conversation.conversation_id.id
logger.debug('Adding new conversation: {}'.format(conv_id))
conv = Conversation(self._client, self._user_list, conversation,
events, event_cont_token)
self._conv_dict[conv_id] = conv
return conv | [
"def",
"_add_conversation",
"(",
"self",
",",
"conversation",
",",
"events",
"=",
"[",
"]",
",",
"event_cont_token",
"=",
"None",
")",
":",
"# pylint: disable=dangerous-default-value",
"conv_id",
"=",
"conversation",
".",
"conversation_id",
".",
"id",
"logger",
".... | Add new conversation from hangouts_pb2.Conversation | [
"Add",
"new",
"conversation",
"from",
"hangouts_pb2",
".",
"Conversation"
] | python | valid | 51.4 |
Jammy2211/PyAutoLens | autolens/model/profiles/light_profiles.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/light_profiles.py#L315-L327 | def intensities_from_grid_radii(self, grid_radii):
"""
Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
"""
np.seterr(all='ignore')
return np.multiply(self.intensity, np.exp(
np.multiply(-self.sersic_constant,
np.add(np.power(np.divide(grid_radii, self.effective_radius), 1. / self.sersic_index), -1)))) | [
"def",
"intensities_from_grid_radii",
"(",
"self",
",",
"grid_radii",
")",
":",
"np",
".",
"seterr",
"(",
"all",
"=",
"'ignore'",
")",
"return",
"np",
".",
"multiply",
"(",
"self",
".",
"intensity",
",",
"np",
".",
"exp",
"(",
"np",
".",
"multiply",
"(... | Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid. | [
"Calculate",
"the",
"intensity",
"of",
"the",
"Sersic",
"light",
"profile",
"on",
"a",
"grid",
"of",
"radial",
"coordinates",
"."
] | python | valid | 43.538462 |
skorch-dev/skorch | skorch/toy.py | https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/skorch/toy.py#L69-L85 | def reset_params(self):
"""(Re)set all parameters."""
units = [self.input_units]
units += [self.hidden_units] * self.num_hidden
units += [self.output_units]
sequence = []
for u0, u1 in zip(units, units[1:]):
sequence.append(nn.Linear(u0, u1))
sequence.append(self.nonlin)
sequence.append(nn.Dropout(self.dropout))
sequence = sequence[:-2]
if self.output_nonlin:
sequence.append(self.output_nonlin)
self.sequential = nn.Sequential(*sequence) | [
"def",
"reset_params",
"(",
"self",
")",
":",
"units",
"=",
"[",
"self",
".",
"input_units",
"]",
"units",
"+=",
"[",
"self",
".",
"hidden_units",
"]",
"*",
"self",
".",
"num_hidden",
"units",
"+=",
"[",
"self",
".",
"output_units",
"]",
"sequence",
"=... | (Re)set all parameters. | [
"(",
"Re",
")",
"set",
"all",
"parameters",
"."
] | python | train | 32.176471 |
noxdafox/vminspect | vminspect/comparator.py | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/comparator.py#L418-L423 | def makedirs(path):
"""Creates the directory tree if non existing."""
path = Path(path)
if not path.exists():
path.mkdir(parents=True) | [
"def",
"makedirs",
"(",
"path",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"if",
"not",
"path",
".",
"exists",
"(",
")",
":",
"path",
".",
"mkdir",
"(",
"parents",
"=",
"True",
")"
] | Creates the directory tree if non existing. | [
"Creates",
"the",
"directory",
"tree",
"if",
"non",
"existing",
"."
] | python | train | 25 |
AguaClara/aguaclara | aguaclara/design/lfom.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L108-L116 | def n_orifices_per_row_max(self):
"""A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe.
"""
c = math.pi * pipe.ID_SDR(self.nom_diam_pipe, self.sdr)
b = self.orifice_diameter + self.s_orifice
return math.floor(c/b) | [
"def",
"n_orifices_per_row_max",
"(",
"self",
")",
":",
"c",
"=",
"math",
".",
"pi",
"*",
"pipe",
".",
"ID_SDR",
"(",
"self",
".",
"nom_diam_pipe",
",",
"self",
".",
"sdr",
")",
"b",
"=",
"self",
".",
"orifice_diameter",
"+",
"self",
".",
"s_orifice",
... | A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe. | [
"A",
"bound",
"on",
"the",
"number",
"of",
"orifices",
"allowed",
"in",
"each",
"row",
".",
"The",
"distance",
"between",
"consecutive",
"orifices",
"must",
"be",
"enough",
"to",
"retain",
"structural",
"integrity",
"of",
"the",
"pipe",
"."
] | python | train | 40.777778 |
sci-bots/svg-model | docs/generate_modules.py | https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/docs/generate_modules.py#L215-L228 | def is_excluded(root, excludes):
"""
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
sep = os.path.sep
if not root.endswith(sep):
root += sep
for exclude in excludes:
if root.startswith(exclude):
return True
return False | [
"def",
"is_excluded",
"(",
"root",
",",
"excludes",
")",
":",
"sep",
"=",
"os",
".",
"path",
".",
"sep",
"if",
"not",
"root",
".",
"endswith",
"(",
"sep",
")",
":",
"root",
"+=",
"sep",
"for",
"exclude",
"in",
"excludes",
":",
"if",
"root",
".",
... | Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar". | [
"Check",
"if",
"the",
"directory",
"is",
"in",
"the",
"exclude",
"list",
"."
] | python | train | 29.285714 |
archman/beamline | beamline/mathutils.py | https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/mathutils.py#L264-L278 | def transFringe(beta=None, rho=None):
""" Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array
"""
m = np.eye(6, 6, dtype=np.float64)
if None in (beta, rho):
print("warning: 'theta', 'rho' should be positive float numbers.")
return m
else:
m[1, 0] = np.tan(beta) / rho
m[3, 2] = -np.tan(beta) / rho
return m | [
"def",
"transFringe",
"(",
"beta",
"=",
"None",
",",
"rho",
"=",
"None",
")",
":",
"m",
"=",
"np",
".",
"eye",
"(",
"6",
",",
"6",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"None",
"in",
"(",
"beta",
",",
"rho",
")",
":",
"print",
... | Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array | [
"Transport",
"matrix",
"of",
"fringe",
"field"
] | python | train | 30.533333 |
senaite/senaite.core | bika/lims/api/security.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/api/security.py#L275-L299 | def grant_permission_for(brain_or_object, permission, roles, acquire=0):
"""Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: The roles the permission to be granted to
:param acquire: Flag to acquire the permission
"""
obj = api.get_object(brain_or_object)
valid_roles = get_valid_roles_for(obj)
to_grant = list(get_roles_for_permission(permission, obj))
if isinstance(roles, basestring):
roles = [roles]
for role in roles:
if role not in to_grant:
if role not in valid_roles:
raise ValueError("The Role '{}' is invalid.".format(role))
# Append the role
to_grant.append(role)
manage_permission_for(obj, permission, to_grant, acquire=acquire) | [
"def",
"grant_permission_for",
"(",
"brain_or_object",
",",
"permission",
",",
"roles",
",",
"acquire",
"=",
"0",
")",
":",
"obj",
"=",
"api",
".",
"get_object",
"(",
"brain_or_object",
")",
"valid_roles",
"=",
"get_valid_roles_for",
"(",
"obj",
")",
"to_grant... | Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: The roles the permission to be granted to
:param acquire: Flag to acquire the permission | [
"Grant",
"the",
"permission",
"for",
"the",
"object",
"to",
"the",
"defined",
"roles"
] | python | train | 36.48 |
offu/WeRoBot | werobot/client.py | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/client.py#L82-L95 | def grant_token(self):
"""
获取 Access Token。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": self.appid,
"secret": self.appsecret
}
) | [
"def",
"grant_token",
"(",
"self",
")",
":",
"return",
"self",
".",
"get",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/cgi-bin/token\"",
",",
"params",
"=",
"{",
"\"grant_type\"",
":",
"\"client_credential\"",
",",
"\"appid\"",
":",
"self",
".",
"appid",
",",
... | 获取 Access Token。
:return: 返回的 JSON 数据包 | [
"获取",
"Access",
"Token。"
] | python | train | 24.785714 |
mosdef-hub/mbuild | mbuild/utils/io.py | https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/utils/io.py#L81-L124 | def import_(module):
"""Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The module object
Examples
--------
>>> # the following two lines are equivalent. the difference is that the
>>> # second will check for an ImportError and print you a very nice
>>> # user-facing message about what's wrong (where you can install the
>>> # module from, etc) if the import fails
>>> import tables
>>> tables = import_('tables')
"""
try:
return importlib.import_module(module)
except ImportError as e:
try:
message = MESSAGES[module]
except KeyError:
message = 'The code at {filename}:{line_number} requires the ' + module + ' package'
e = ImportError('No module named %s' % module)
frame, filename, line_number, function_name, lines, index = \
inspect.getouterframes(inspect.currentframe())[1]
m = message.format(filename=os.path.basename(filename), line_number=line_number)
m = textwrap.dedent(m)
bar = '\033[91m' + '#' * max(len(line) for line in m.split(os.linesep)) + '\033[0m'
print('', file=sys.stderr)
print(bar, file=sys.stderr)
print(m, file=sys.stderr)
print(bar, file=sys.stderr)
raise DelayImportError(m) | [
"def",
"import_",
"(",
"module",
")",
":",
"try",
":",
"return",
"importlib",
".",
"import_module",
"(",
"module",
")",
"except",
"ImportError",
"as",
"e",
":",
"try",
":",
"message",
"=",
"MESSAGES",
"[",
"module",
"]",
"except",
"KeyError",
":",
"messa... | Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The module object
Examples
--------
>>> # the following two lines are equivalent. the difference is that the
>>> # second will check for an ImportError and print you a very nice
>>> # user-facing message about what's wrong (where you can install the
>>> # module from, etc) if the import fails
>>> import tables
>>> tables = import_('tables') | [
"Import",
"a",
"module",
"and",
"issue",
"a",
"nice",
"message",
"to",
"stderr",
"if",
"the",
"module",
"isn",
"t",
"installed",
"."
] | python | train | 33.090909 |
project-ncl/pnc-cli | pnc_cli/buildrecords.py | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildrecords.py#L91-L97 | def list_built_artifacts(id, page_size=200, page_index=0, sort="", q=""):
"""
List Artifacts associated with a BuildRecord
"""
data = list_built_artifacts_raw(id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | [
"def",
"list_built_artifacts",
"(",
"id",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"\"\"",
",",
"q",
"=",
"\"\"",
")",
":",
"data",
"=",
"list_built_artifacts_raw",
"(",
"id",
",",
"page_size",
",",
"page_index",
",",
... | List Artifacts associated with a BuildRecord | [
"List",
"Artifacts",
"associated",
"with",
"a",
"BuildRecord"
] | python | train | 37.285714 |
saltstack/salt | salt/utils/user.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L232-L257 | def chugid_and_umask(runas, umask, group=None):
'''
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
'''
set_runas = False
set_grp = False
current_user = getpass.getuser()
if runas and runas != current_user:
set_runas = True
runas_user = runas
else:
runas_user = current_user
current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name
if group and group != current_grp:
set_grp = True
runas_grp = group
else:
runas_grp = current_grp
if set_runas or set_grp:
chugid(runas_user, runas_grp)
if umask is not None:
os.umask(umask) | [
"def",
"chugid_and_umask",
"(",
"runas",
",",
"umask",
",",
"group",
"=",
"None",
")",
":",
"set_runas",
"=",
"False",
"set_grp",
"=",
"False",
"current_user",
"=",
"getpass",
".",
"getuser",
"(",
")",
"if",
"runas",
"and",
"runas",
"!=",
"current_user",
... | Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process. | [
"Helper",
"method",
"for",
"for",
"subprocess",
".",
"Popen",
"to",
"initialise",
"uid",
"/",
"gid",
"and",
"umask",
"for",
"the",
"new",
"process",
"."
] | python | train | 26.230769 |
saltstack/salt | salt/utils/gitfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L590-L631 | def clean_stale_refs(self):
'''
Remove stale refs so that they are no longer seen as fileserver envs
'''
cleaned = []
cmd_str = 'git remote prune origin'
# Attempt to force all output to plain ascii english, which is what some parsing code
# may expect.
# According to stackoverflow (http://goo.gl/l74GC8), we are setting LANGUAGE as well
# just to be sure.
env = os.environ.copy()
env[b"LANGUAGE"] = b"C"
env[b"LC_ALL"] = b"C"
cmd = subprocess.Popen(
shlex.split(cmd_str),
close_fds=not salt.utils.platform.is_windows(),
cwd=os.path.dirname(self.gitdir),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
output = cmd.communicate()[0]
if six.PY3:
output = output.decode(__salt_system_encoding__)
if cmd.returncode != 0:
log.warning(
'Failed to prune stale branches for %s remote \'%s\'. '
'Output from \'%s\' follows:\n%s',
self.role, self.id, cmd_str, output
)
else:
marker = ' * [pruned] '
for line in salt.utils.itertools.split(output, '\n'):
if line.startswith(marker):
cleaned.append(line[len(marker):].strip())
if cleaned:
log.debug(
'%s pruned the following stale refs: %s',
self.role, ', '.join(cleaned)
)
return cleaned | [
"def",
"clean_stale_refs",
"(",
"self",
")",
":",
"cleaned",
"=",
"[",
"]",
"cmd_str",
"=",
"'git remote prune origin'",
"# Attempt to force all output to plain ascii english, which is what some parsing code",
"# may expect.",
"# According to stackoverflow (http://goo.gl/l74GC8), we ar... | Remove stale refs so that they are no longer seen as fileserver envs | [
"Remove",
"stale",
"refs",
"so",
"that",
"they",
"are",
"no",
"longer",
"seen",
"as",
"fileserver",
"envs"
] | python | train | 36.738095 |
grycap/RADL | radl/radl.py | https://github.com/grycap/RADL/blob/03ccabb0313a48a5aa0e20c1f7983fddcb95e9cb/radl/radl.py#L1190-L1200 | def get(self, aspect):
"""Get a network, system or configure or contextualize with the same id as aspect passed."""
classification = [(network, self.networks), (system, self.systems),
(configure, self.configures)]
aspect_list = [l for t, l in classification if isinstance(aspect, t)]
assert len(aspect_list) == 1, "Unexpected aspect for RADL."
aspect_list = aspect_list[0]
old_aspect = [a for a in aspect_list if a.getId() == aspect.getId()]
return old_aspect[0] if old_aspect else None | [
"def",
"get",
"(",
"self",
",",
"aspect",
")",
":",
"classification",
"=",
"[",
"(",
"network",
",",
"self",
".",
"networks",
")",
",",
"(",
"system",
",",
"self",
".",
"systems",
")",
",",
"(",
"configure",
",",
"self",
".",
"configures",
")",
"]"... | Get a network, system or configure or contextualize with the same id as aspect passed. | [
"Get",
"a",
"network",
"system",
"or",
"configure",
"or",
"contextualize",
"with",
"the",
"same",
"id",
"as",
"aspect",
"passed",
"."
] | python | train | 50.909091 |
gem/oq-engine | openquake/calculators/reportwriter.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/reportwriter.py#L85-L117 | def make_report(self):
"""Build the report and return a restructed text string"""
oq, ds = self.oq, self.dstore
for name in ('params', 'inputs'):
self.add(name)
if 'csm_info' in ds:
self.add('csm_info')
if ds['csm_info'].source_models[0].name != 'scenario':
# required_params_per_trt makes no sense for GMFs from file
self.add('required_params_per_trt')
self.add('rlzs_assoc', ds['csm_info'].get_rlzs_assoc())
if 'csm_info' in ds:
self.add('ruptures_per_trt')
if 'rup_data' in ds:
self.add('ruptures_events')
if oq.calculation_mode in ('event_based_risk',):
self.add('avglosses_data_transfer')
if 'exposure' in oq.inputs:
self.add('exposure_info')
if 'source_info' in ds:
self.add('slow_sources')
self.add('times_by_source_class')
self.add('dupl_sources')
if 'task_info' in ds:
self.add('task_info')
tasks = set(ds['task_info'])
if 'classical' in tasks:
self.add('task_hazard:0')
self.add('task_hazard:-1')
self.add('job_info')
if 'performance_data' in ds:
self.add('performance')
return self.text | [
"def",
"make_report",
"(",
"self",
")",
":",
"oq",
",",
"ds",
"=",
"self",
".",
"oq",
",",
"self",
".",
"dstore",
"for",
"name",
"in",
"(",
"'params'",
",",
"'inputs'",
")",
":",
"self",
".",
"add",
"(",
"name",
")",
"if",
"'csm_info'",
"in",
"ds... | Build the report and return a restructed text string | [
"Build",
"the",
"report",
"and",
"return",
"a",
"restructed",
"text",
"string"
] | python | train | 39.909091 |
UCSBarchlab/PyRTL | pyrtl/transform.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L73-L78 | def all_wires(transform_func):
"""Decorator that wraps a wire transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
wire_transform(transform_func, **kwargs)
return t_res | [
"def",
"all_wires",
"(",
"transform_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"transform_func",
")",
"def",
"t_res",
"(",
"*",
"*",
"kwargs",
")",
":",
"wire_transform",
"(",
"transform_func",
",",
"*",
"*",
"kwargs",
")",
"return",
"t_res"
] | Decorator that wraps a wire transform function | [
"Decorator",
"that",
"wraps",
"a",
"wire",
"transform",
"function"
] | python | train | 35 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/vqa_utils.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/vqa_utils.py#L98-L140 | def _distort_color(image, color_ordering=0, scope=None):
"""Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
Args:
image: 3-D Tensor containing single image in [0, 1].
color_ordering: Python int, a type of distortion (valid values: 0-3).
scope: Optional scope for name_scope.
Returns:
3-D Tensor color-distorted image on range [0, 1]
Raises:
ValueError: if color_ordering not in [0, 3]
"""
with tf.name_scope(scope, "distort_color", [image]):
if color_ordering == 0:
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
elif color_ordering == 1:
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
elif color_ordering == 2:
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
elif color_ordering == 3:
image = tf.image.random_hue(image, max_delta=0.2)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.random_brightness(image, max_delta=32. / 255.)
else:
raise ValueError("color_ordering must be in [0, 3]")
# The random_* ops do not necessarily clamp.
return tf.clip_by_value(image, 0.0, 1.0) | [
"def",
"_distort_color",
"(",
"image",
",",
"color_ordering",
"=",
"0",
",",
"scope",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
",",
"\"distort_color\"",
",",
"[",
"image",
"]",
")",
":",
"if",
"color_ordering",
"==",
"0",
"... | Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
Args:
image: 3-D Tensor containing single image in [0, 1].
color_ordering: Python int, a type of distortion (valid values: 0-3).
scope: Optional scope for name_scope.
Returns:
3-D Tensor color-distorted image on range [0, 1]
Raises:
ValueError: if color_ordering not in [0, 3] | [
"Distort",
"the",
"color",
"of",
"a",
"Tensor",
"image",
"."
] | python | train | 47.418605 |
jbarlow83/OCRmyPDF | src/ocrmypdf/pdfinfo/__init__.py | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L364-L370 | def _find_inline_images(contentsinfo):
"Find inline images in the contentstream"
for n, inline in enumerate(contentsinfo.inline_images):
yield ImageInfo(
name='inline-%02d' % n, shorthand=inline.shorthand, inline=inline
) | [
"def",
"_find_inline_images",
"(",
"contentsinfo",
")",
":",
"for",
"n",
",",
"inline",
"in",
"enumerate",
"(",
"contentsinfo",
".",
"inline_images",
")",
":",
"yield",
"ImageInfo",
"(",
"name",
"=",
"'inline-%02d'",
"%",
"n",
",",
"shorthand",
"=",
"inline"... | Find inline images in the contentstream | [
"Find",
"inline",
"images",
"in",
"the",
"contentstream"
] | python | train | 36 |
MrYsLab/PyMata | PyMata/pymata.py | https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L718-L737 | def reset(self):
"""
This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value.
"""
# set all output pins to a value of 0
for pin in range(0, self._command_handler.total_pins_discovered):
if self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.PWM:
self.analog_write(pin, 0)
elif self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.SERVO:
self.analog_write(pin, 0)
elif self._command_handler.digital_response_table[self._command_handler.RESPONSE_TABLE_MODE] \
== self.TONE:
data = [self.TONE_NO_TONE, pin]
self._command_handler.send_sysex(self._command_handler.TONE_PLAY, data)
else:
self.digital_write(pin, 0)
self._command_handler.system_reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"# set all output pins to a value of 0",
"for",
"pin",
"in",
"range",
"(",
"0",
",",
"self",
".",
"_command_handler",
".",
"total_pins_discovered",
")",
":",
"if",
"self",
".",
"_command_handler",
".",
"digital_response_table... | This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value. | [
"This",
"command",
"sends",
"a",
"reset",
"message",
"to",
"the",
"Arduino",
".",
"The",
"response",
"tables",
"will",
"be",
"reinitialized",
":",
"return",
":",
"No",
"return",
"value",
"."
] | python | valid | 51.15 |
dchaplinsky/aiohttp_validate | aiohttp_validate/__init__.py | https://github.com/dchaplinsky/aiohttp_validate/blob/e581cf51df6fcc377c7704315a487b10c3dd6000/aiohttp_validate/__init__.py#L32-L74 | def _validate_data(data, schema, validator_cls):
"""
Validate the dict against given schema (using given validator class).
"""
validator = validator_cls(schema)
_errors = defaultdict(list)
for err in validator.iter_errors(data):
path = err.schema_path
# Code courtesy: Ruslan Karalkin
# Looking in error schema path for
# property that failed validation
# Schema example:
# {
# "type": "object",
# "properties": {
# "foo": {"type": "number"},
# "bar": {"type": "string"}
# }
# "required": ["foo", "bar"]
# }
#
# Related err.schema_path examples:
# ['required'],
# ['properties', 'foo', 'type']
if "properties" in path:
path.remove("properties")
key = path.popleft()
# If validation failed by missing property,
# then parse err.message to find property name
# as it always first word enclosed in quotes
if key == "required":
key = err.message.split("'")[1]
_errors[key].append(str(err))
if _errors:
_raise_exception(
web.HTTPBadRequest,
"Request is invalid; There are validation errors.",
_errors) | [
"def",
"_validate_data",
"(",
"data",
",",
"schema",
",",
"validator_cls",
")",
":",
"validator",
"=",
"validator_cls",
"(",
"schema",
")",
"_errors",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"err",
"in",
"validator",
".",
"iter_errors",
"(",
"data",
"... | Validate the dict against given schema (using given validator class). | [
"Validate",
"the",
"dict",
"against",
"given",
"schema",
"(",
"using",
"given",
"validator",
"class",
")",
"."
] | python | train | 29.627907 |
bolt-project/bolt | bolt/spark/array.py | https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/array.py#L62-L83 | def stack(self, size=None):
"""
Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
to restore the full bolt array.
Parameters
----------
size : int, optional, default=None
The maximum size for each stack (number of original records),
will aggregate groups of records per partition up to this size,
if None will aggregate all records on each partition.
Returns
-------
StackedArray
"""
stk = StackedArray(self._rdd, shape=self.shape, split=self.split)
return stk.stack(size) | [
"def",
"stack",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"stk",
"=",
"StackedArray",
"(",
"self",
".",
"_rdd",
",",
"shape",
"=",
"self",
".",
"shape",
",",
"split",
"=",
"self",
".",
"split",
")",
"return",
"stk",
".",
"stack",
"(",
"siz... | Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
to restore the full bolt array.
Parameters
----------
size : int, optional, default=None
The maximum size for each stack (number of original records),
will aggregate groups of records per partition up to this size,
if None will aggregate all records on each partition.
Returns
-------
StackedArray | [
"Aggregates",
"records",
"of",
"a",
"distributed",
"array",
"."
] | python | test | 36.454545 |
baruwa-enterprise/BaruwaAPI | BaruwaAPI/resource.py | https://github.com/baruwa-enterprise/BaruwaAPI/blob/53335b377ccfd388e42f4f240f181eed72f51180/BaruwaAPI/resource.py#L353-L357 | def get_radiussettings(self, domainid, serverid, settingsid):
"""Get RADIUS settings"""
return self.api_call(
ENDPOINTS['radiussettings']['get'],
dict(domainid=domainid, serverid=serverid, settingsid=settingsid)) | [
"def",
"get_radiussettings",
"(",
"self",
",",
"domainid",
",",
"serverid",
",",
"settingsid",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"ENDPOINTS",
"[",
"'radiussettings'",
"]",
"[",
"'get'",
"]",
",",
"dict",
"(",
"domainid",
"=",
"domainid",
",... | Get RADIUS settings | [
"Get",
"RADIUS",
"settings"
] | python | train | 49.6 |
liip/taxi | taxi/timesheet/parser.py | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/parser.py#L307-L334 | def parse_text(self, text):
"""
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised.
"""
text = text.strip()
lines = text.splitlines()
parsed_lines = []
encountered_date = False
for (lineno, line) in enumerate(lines, 1):
try:
parsed_line = self.parse_line(line)
if isinstance(parsed_line, DateLine):
encountered_date = True
elif isinstance(parsed_line, Entry) and not encountered_date:
raise ParseError("Entries must be defined inside a date section")
except ParseError as e:
# Update exception with some more information
e.line_number = lineno
e.line = line
raise
else:
parsed_lines.append(parsed_line)
return parsed_lines | [
"def",
"parse_text",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"lines",
"=",
"text",
".",
"splitlines",
"(",
")",
"parsed_lines",
"=",
"[",
"]",
"encountered_date",
"=",
"False",
"for",
"(",
"lineno",
",",
"line... | Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised. | [
"Parse",
"the",
"given",
"text",
"and",
"return",
"a",
"list",
"of",
":",
"class",
":",
"~taxi",
".",
"timesheet",
".",
"lines",
".",
"DateLine",
":",
"class",
":",
"~taxi",
".",
"timesheet",
".",
"lines",
".",
"Entry",
"and",
":",
"class",
":",
"~ta... | python | train | 39.285714 |
Projectplace/basepage | basepage/wait.py | https://github.com/Projectplace/basepage/blob/735476877eb100db0981590a6d12140e68652167/basepage/wait.py#L46-L69 | def until(self, func, message='', *args, **kwargs):
"""
Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:return: result of function or None
"""
value = None
end_time = time.time() + self._timeout
while True:
value = func(*args, **kwargs)
if self._debug:
print("Value from func within ActionWait: {}".format(value))
if value:
break
time.sleep(self._poll)
self._poll *= 1.25
if time.time() > end_time:
raise RuntimeError(message)
return value | [
"def",
"until",
"(",
"self",
",",
"func",
",",
"message",
"=",
"''",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"None",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"_timeout",
"while",
"True",
":",
... | Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:return: result of function or None | [
"Continues",
"to",
"execute",
"the",
"function",
"until",
"successful",
"or",
"time",
"runs",
"out",
"."
] | python | train | 33.125 |
seomoz/qless-py | qless/workers/forking.py | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/forking.py#L54-L63 | def spawn(self, **kwargs):
'''Return a new worker for a child process'''
copy = dict(self.kwargs)
copy.update(kwargs)
# Apparently there's an issue with importing gevent in the parent
# process and then using it int he child. This is meant to relieve that
# problem by allowing `klass` to be specified as a string.
if isinstance(self.klass, string_types):
self.klass = util.import_class(self.klass)
return self.klass(self.queues, self.client, **copy) | [
"def",
"spawn",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"copy",
"=",
"dict",
"(",
"self",
".",
"kwargs",
")",
"copy",
".",
"update",
"(",
"kwargs",
")",
"# Apparently there's an issue with importing gevent in the parent",
"# process and then using it int he ... | Return a new worker for a child process | [
"Return",
"a",
"new",
"worker",
"for",
"a",
"child",
"process"
] | python | train | 51.7 |
iotaledger/iota.lib.py | iota/transaction/validator.py | https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/transaction/validator.py#L41-L51 | def errors(self):
# type: () -> List[Text]
"""
Returns all errors found with the bundle.
"""
try:
self._errors.extend(self._validator) # type: List[Text]
except StopIteration:
pass
return self._errors | [
"def",
"errors",
"(",
"self",
")",
":",
"# type: () -> List[Text]",
"try",
":",
"self",
".",
"_errors",
".",
"extend",
"(",
"self",
".",
"_validator",
")",
"# type: List[Text]",
"except",
"StopIteration",
":",
"pass",
"return",
"self",
".",
"_errors"
] | Returns all errors found with the bundle. | [
"Returns",
"all",
"errors",
"found",
"with",
"the",
"bundle",
"."
] | python | test | 24.727273 |
DataBiosphere/toil | src/toil/__init__.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/__init__.py#L421-L667 | def _monkey_patch_boto():
"""
Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles.
"""
from boto import provider
from botocore.session import Session
from botocore.credentials import create_credential_resolver, RefreshableCredentials
# We cache the final credentials so that we don't send multiple processes to
# simultaneously bang on the EC2 metadata server or ask for MFA pins from the
# user.
cache_path = '~/.cache/aws/cached_temporary_credentials'
datetime_format = "%Y-%m-%dT%H:%M:%SZ" # incidentally the same as the format used by AWS
log = logging.getLogger(__name__)
def datetime_to_str(dt):
"""
Convert a naive (implicitly UTC) datetime object into a string, explicitly UTC.
>>> datetime_to_str(datetime(1970, 1, 1, 0, 0, 0))
'1970-01-01T00:00:00Z'
"""
return dt.strftime(datetime_format)
def str_to_datetime(s):
"""
Convert a string, explicitly UTC into a naive (implicitly UTC) datetime object.
>>> str_to_datetime( '1970-01-01T00:00:00Z' )
datetime.datetime(1970, 1, 1, 0, 0)
Just to show that the constructor args for seconds and microseconds are optional:
>>> datetime(1970, 1, 1, 0, 0, 0)
datetime.datetime(1970, 1, 1, 0, 0)
"""
return datetime.strptime(s, datetime_format)
class BotoCredentialAdapter(provider.Provider):
"""
Adapter to allow Boto 2 to use AWS credentials obtained via Boto 3's
credential finding logic. This allows for automatic role assumption
respecting the Boto 3 config files, even when parts of the app still use
Boto 2.
This class also handles cacheing credentials in multi-process environments
to avoid loads of processes swamping the EC2 metadata service.
"""
def __init__(self, name, access_key=None, secret_key=None,
security_token=None, profile_name=None, **kwargs):
"""
Create a new BotoCredentialAdapter.
"""
# TODO: We take kwargs because new boto2 versions have an 'anon'
# argument and we want to be future proof
if (name == 'aws' or name is None) and access_key is None and not kwargs.get('anon', False):
# We are on AWS and we don't have credentials passed along and we aren't anonymous.
# We will backend into a boto3 resolver for getting credentials.
self._boto3_resolver = create_credential_resolver(Session(profile=profile_name))
else:
# We will use the normal flow
self._boto3_resolver = None
# Pass along all the arguments
super(BotoCredentialAdapter, self).__init__(name, access_key=access_key,
secret_key=secret_key, security_token=security_token,
profile_name=profile_name, **kwargs)
def get_credentials(self, access_key=None, secret_key=None, security_token=None, profile_name=None):
"""
Make sure our credential fields are populated. Called by the base class
constructor.
"""
if self._boto3_resolver is not None:
# Go get the credentials from the cache, or from boto3 if not cached.
# We need to be eager here; having the default None
# _credential_expiry_time makes the accessors never try to refresh.
self._obtain_credentials_from_cache_or_boto3()
else:
# We're not on AWS, or they passed a key, or we're anonymous.
# Use the normal route; our credentials shouldn't expire.
super(BotoCredentialAdapter, self).get_credentials(access_key=access_key,
secret_key=secret_key, security_token=security_token, profile_name=profile_name)
def _populate_keys_from_metadata_server(self):
"""
This override is misnamed; it's actually the only hook we have to catch
_credential_expiry_time being too soon and refresh the credentials. We
actually just go back and poke the cache to see if it feels like
getting us new credentials.
Boto 2 hardcodes a refresh within 5 minutes of expiry:
https://github.com/boto/boto/blob/591911db1029f2fbb8ba1842bfcc514159b37b32/boto/provider.py#L247
Boto 3 wants to refresh 15 or 10 minutes before expiry:
https://github.com/boto/botocore/blob/8d3ea0e61473fba43774eb3c74e1b22995ee7370/botocore/credentials.py#L279
So if we ever want to refresh, Boto 3 wants to refresh too.
"""
# This should only happen if we have expiring credentials, which we should only get from boto3
assert(self._boto3_resolver is not None)
self._obtain_credentials_from_cache_or_boto3()
def _obtain_credentials_from_boto3(self):
"""
We know the current cached credentials are not good, and that we
need to get them from Boto 3. Fill in our credential fields
(_access_key, _secret_key, _security_token,
_credential_expiry_time) from Boto 3.
"""
# We get a Credentials object
# <https://github.com/boto/botocore/blob/8d3ea0e61473fba43774eb3c74e1b22995ee7370/botocore/credentials.py#L227>
# or a RefreshableCredentials, or None on failure.
creds = None
for attempt in retry(timeout=10, predicate=lambda _: True):
with attempt:
creds = self._boto3_resolver.load_credentials()
if creds is None:
try:
resolvers = str(self._boto3_resolver.providers)
except:
resolvers = "(Resolvers unavailable)"
raise RuntimeError("Could not obtain AWS credentials from Boto3. Resolvers tried: " + resolvers)
# Make sure the credentials actually has some credentials if it is lazy
creds.get_frozen_credentials()
# Get when the credentials will expire, if ever
if isinstance(creds, RefreshableCredentials):
# Credentials may expire.
# Get a naive UTC datetime like boto 2 uses from the boto 3 time.
self._credential_expiry_time = creds._expiry_time.astimezone(timezone('UTC')).replace(tzinfo=None)
else:
# Credentials never expire
self._credential_expiry_time = None
# Then, atomically get all the credentials bits. They may be newer than we think they are, but never older.
frozen = creds.get_frozen_credentials()
# Copy them into us
self._access_key = frozen.access_key
self._secret_key = frozen.secret_key
self._security_token = frozen.token
def _obtain_credentials_from_cache_or_boto3(self):
"""
Get the cached credentials, or retrieve them from Boto 3 and cache them
(or wait for another cooperating process to do so) if they are missing
or not fresh enough.
"""
path = os.path.expanduser(cache_path)
tmp_path = path + '.tmp'
while True:
log.debug('Attempting to read cached credentials from %s.', path)
try:
with open(path, 'r') as f:
content = f.read()
if content:
record = content.split('\n')
assert len(record) == 4
self._access_key = record[0]
self._secret_key = record[1]
self._security_token = record[2]
self._credential_expiry_time = str_to_datetime(record[3])
else:
log.debug('%s is empty. Credentials are not temporary.', path)
self._obtain_credentials_from_boto3()
return
except IOError as e:
if e.errno == errno.ENOENT:
log.debug('Cached credentials are missing.')
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
log.debug('Creating parent directory %s', dir_path)
# A race would be ok at this point
mkdir_p(dir_path)
else:
raise
else:
if self._credentials_need_refresh():
log.debug('Cached credentials are expired.')
else:
log.debug('Cached credentials exist and are still fresh.')
return
# We get here if credentials are missing or expired
log.debug('Racing to create %s.', tmp_path)
# Only one process, the winner, will succeed
try:
fd = os.open(tmp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
except OSError as e:
if e.errno == errno.EEXIST:
log.debug('Lost the race to create %s. Waiting on winner to remove it.', tmp_path)
while os.path.exists(tmp_path):
time.sleep(0.1)
log.debug('Winner removed %s. Trying from the top.', tmp_path)
else:
raise
else:
try:
log.debug('Won the race to create %s. Requesting credentials from backend.', tmp_path)
self._obtain_credentials_from_boto3()
except:
os.close(fd)
fd = None
log.debug('Failed to obtain credentials, removing %s.', tmp_path)
# This unblocks the loosers.
os.unlink(tmp_path)
# Bail out. It's too likely to happen repeatedly
raise
else:
if self._credential_expiry_time is None:
os.close(fd)
fd = None
log.debug('Credentials are not temporary. Leaving %s empty and renaming it to %s.', tmp_path, path)
# No need to actually cache permanent credentials,
# because we hnow we aren't getting them from the
# metadata server or by assuming a role. Those both
# give temporary credentials.
else:
log.debug('Writing credentials to %s.', tmp_path)
with os.fdopen(fd, 'w') as fh:
fd = None
fh.write('\n'.join([
self._access_key,
self._secret_key,
self._security_token,
datetime_to_str(self._credential_expiry_time)]))
log.debug('Wrote credentials to %s. Renaming to %s.', tmp_path, path)
os.rename(tmp_path, path)
return
finally:
if fd is not None:
os.close(fd)
# Now we have defined the adapter class. Patch the Boto module so it replaces the default Provider when Boto makes Providers.
provider.Provider = BotoCredentialAdapter | [
"def",
"_monkey_patch_boto",
"(",
")",
":",
"from",
"boto",
"import",
"provider",
"from",
"botocore",
".",
"session",
"import",
"Session",
"from",
"botocore",
".",
"credentials",
"import",
"create_credential_resolver",
",",
"RefreshableCredentials",
"# We cache the fina... | Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles. | [
"Boto",
"2",
"can",
"t",
"automatically",
"assume",
"roles",
".",
"We",
"want",
"to",
"replace",
"its",
"Provider",
"class",
"that",
"manages",
"credentials",
"with",
"one",
"that",
"uses",
"the",
"Boto",
"3",
"configuration",
"and",
"can",
"assume",
"roles"... | python | train | 49.016194 |
mikedh/trimesh | trimesh/util.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/util.py#L1428-L1454 | def jsonify(obj, **kwargs):
"""
A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj
"""
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
# will work for numpy.ndarrays
# as well as their int64/etc objects
if hasattr(obj, 'tolist'):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
# run the dumps using our encoder
dumped = json.dumps(obj, cls=NumpyEncoder, **kwargs)
return dumped | [
"def",
"jsonify",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"NumpyEncoder",
"(",
"json",
".",
"JSONEncoder",
")",
":",
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"# will work for numpy.ndarrays",
"# as well as their int64/etc objects",
... | A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj | [
"A",
"version",
"of",
"json",
".",
"dumps",
"that",
"can",
"handle",
"numpy",
"arrays",
"by",
"creating",
"a",
"custom",
"encoder",
"for",
"numpy",
"dtypes",
"."
] | python | train | 26.666667 |
python-diamond/Diamond | src/diamond/utils/signals.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/signals.py#L6-L18 | def signal_to_exception(signum, frame):
"""
Called by the timeout alarm during the collector run time
"""
if signum == signal.SIGALRM:
raise SIGALRMException()
if signum == signal.SIGHUP:
raise SIGHUPException()
if signum == signal.SIGUSR1:
raise SIGUSR1Exception()
if signum == signal.SIGUSR2:
raise SIGUSR2Exception()
raise SignalException(signum) | [
"def",
"signal_to_exception",
"(",
"signum",
",",
"frame",
")",
":",
"if",
"signum",
"==",
"signal",
".",
"SIGALRM",
":",
"raise",
"SIGALRMException",
"(",
")",
"if",
"signum",
"==",
"signal",
".",
"SIGHUP",
":",
"raise",
"SIGHUPException",
"(",
")",
"if",... | Called by the timeout alarm during the collector run time | [
"Called",
"by",
"the",
"timeout",
"alarm",
"during",
"the",
"collector",
"run",
"time"
] | python | train | 30.846154 |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L3568-L3628 | def vm_cputime(vm_=None, **kwargs):
'''
Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_cputime
'''
conn = __get_conn(**kwargs)
host_cpus = conn.getInfo()[2]
def _info(dom):
'''
Compute cputime info of a domain
'''
raw = dom.info()
vcpus = int(raw[3])
cputime = int(raw[4])
cputime_percent = 0
if cputime:
# Divide by vcpus to always return a number between 0 and 100
cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus
return {
'cputime': int(raw[4]),
'cputime_percent': int('{0:.0f}'.format(cputime_percent))
}
info = {}
if vm_:
info[vm_] = _info(_get_domain(conn, vm_))
else:
for domain in _get_domain(conn, iterable=True):
info[domain.name()] = _info(domain)
conn.close()
return info | [
"def",
"vm_cputime",
"(",
"vm_",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__get_conn",
"(",
"*",
"*",
"kwargs",
")",
"host_cpus",
"=",
"conn",
".",
"getInfo",
"(",
")",
"[",
"2",
"]",
"def",
"_info",
"(",
"dom",
")",
":",
"... | Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_cputime | [
"Return",
"cputime",
"used",
"by",
"the",
"vms",
"on",
"this",
"hyper",
"in",
"a",
"list",
"of",
"dicts",
":"
] | python | train | 26.114754 |
Alignak-monitoring/alignak | alignak/daterange.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L929-L986 | def get_start_and_end_time(self, ref=None):
"""Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int)
"""
now = time.localtime(ref)
# If no year, it's our year
if self.syear == 0:
self.syear = now.tm_year
month_start_id = now.tm_mon
day_start = find_day_by_weekday_offset(self.syear,
month_start_id, self.swday, self.swday_offset)
start_time = get_start_of_day(self.syear, month_start_id, day_start)
# Same for end year
if self.eyear == 0:
self.eyear = now.tm_year
month_end_id = now.tm_mon
day_end = find_day_by_weekday_offset(self.eyear, month_end_id, self.ewday,
self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
# Maybe end_time is before start. So look for the
# next month
if start_time > end_time:
month_end_id += 1
if month_end_id > 12:
month_end_id = 1
self.eyear += 1
day_end = find_day_by_weekday_offset(self.eyear,
month_end_id, self.ewday, self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
now_epoch = time.mktime(now)
# But maybe we look not enought far. We should add a month
if end_time < now_epoch:
month_end_id += 1
month_start_id += 1
if month_end_id > 12:
month_end_id = 1
self.eyear += 1
if month_start_id > 12:
month_start_id = 1
self.syear += 1
# First start
day_start = find_day_by_weekday_offset(self.syear,
month_start_id, self.swday, self.swday_offset)
start_time = get_start_of_day(self.syear, month_start_id, day_start)
# Then end
day_end = find_day_by_weekday_offset(self.eyear,
month_end_id, self.ewday, self.ewday_offset)
end_time = get_end_of_day(self.eyear, month_end_id, day_end)
return (start_time, end_time) | [
"def",
"get_start_and_end_time",
"(",
"self",
",",
"ref",
"=",
"None",
")",
":",
"now",
"=",
"time",
".",
"localtime",
"(",
"ref",
")",
"# If no year, it's our year",
"if",
"self",
".",
"syear",
"==",
"0",
":",
"self",
".",
"syear",
"=",
"now",
".",
"t... | Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int) | [
"Specific",
"function",
"to",
"get",
"start",
"time",
"and",
"end",
"time",
"for",
"WeekDayDaterange"
] | python | train | 41.310345 |
ga4gh/ga4gh-server | ga4gh/server/frontend.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/frontend.py#L459-L483 | def checkAuthentication():
"""
The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and we don't check.
If we're being redirected to the oidcCallback we don't check.
:returns None if all is ok (and the request handler continues as usual).
Otherwise if the key was in the session (therefore we're in a browser)
then startLogin() will redirect to the OIDC provider. If the key was in
the request arguments, we're using the command line and just raise an
exception.
"""
if app.oidcClient is None:
return
if flask.request.endpoint == 'oidcCallback':
return
key = flask.session.get('key') or flask.request.args.get('key')
if key is None or not app.cache.get(key):
if 'key' in flask.request.args:
raise exceptions.NotAuthenticatedException()
else:
return startLogin() | [
"def",
"checkAuthentication",
"(",
")",
":",
"if",
"app",
".",
"oidcClient",
"is",
"None",
":",
"return",
"if",
"flask",
".",
"request",
".",
"endpoint",
"==",
"'oidcCallback'",
":",
"return",
"key",
"=",
"flask",
".",
"session",
".",
"get",
"(",
"'key'"... | The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and we don't check.
If we're being redirected to the oidcCallback we don't check.
:returns None if all is ok (and the request handler continues as usual).
Otherwise if the key was in the session (therefore we're in a browser)
then startLogin() will redirect to the OIDC provider. If the key was in
the request arguments, we're using the command line and just raise an
exception. | [
"The",
"request",
"will",
"have",
"a",
"parameter",
"key",
"if",
"it",
"came",
"from",
"the",
"command",
"line",
"client",
"or",
"have",
"a",
"session",
"key",
"of",
"key",
"if",
"it",
"s",
"the",
"browser",
".",
"If",
"the",
"token",
"is",
"not",
"f... | python | train | 41.56 |
lemieuxl/pyGenClean | pyGenClean/run_data_clean_up.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/run_data_clean_up.py#L3117-L3159 | def count_markers_samples(prefix, file_type):
"""Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple).
"""
# The files that will need counting
sample_file = None
marker_file = None
if file_type == "bfile":
# Binary files (.bed, .bim and .fam)
sample_file = prefix + ".fam"
marker_file = prefix + ".bim"
elif file_type == "file":
# Pedfile (.ped and .map)
sample_file = prefix + ".ped"
marker_file = prefix + ".map"
elif file_type == "tfile":
# Transposed pedfile (.tped and .tfam)
sample_file = prefix + ".tfam"
marker_file = prefix + ".tped"
# Counting (this may take some time)
nb_samples = 0
with open(sample_file, "r") as f:
for line in f:
nb_samples += 1
nb_markers = 0
with open(marker_file, "r") as f:
for line in f:
nb_markers += 1
return nb_markers, nb_samples | [
"def",
"count_markers_samples",
"(",
"prefix",
",",
"file_type",
")",
":",
"# The files that will need counting",
"sample_file",
"=",
"None",
"marker_file",
"=",
"None",
"if",
"file_type",
"==",
"\"bfile\"",
":",
"# Binary files (.bed, .bim and .fam)",
"sample_file",
"=",... | Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple). | [
"Counts",
"the",
"number",
"of",
"markers",
"and",
"samples",
"in",
"plink",
"file",
"."
] | python | train | 25.511628 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsGenIncProcessModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsGenIncProcessModel.py#L1109-L1130 | def simBirth(self,which_agents):
'''
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------
which_agents : np.array(Bool)
Boolean array of size self.AgentCount indicating which agents should be "born".
Returns
-------
None
'''
# Get and store states for newly born agents
N = np.sum(which_agents) # Number of new consumers to make
aNrmNow_new = drawLognormal(N,mu=self.aNrmInitMean,sigma=self.aNrmInitStd,seed=self.RNG.randint(0,2**31-1))
self.pLvlNow[which_agents] = drawLognormal(N,mu=self.pLvlInitMean,sigma=self.pLvlInitStd,seed=self.RNG.randint(0,2**31-1))
self.aLvlNow[which_agents] = aNrmNow_new*self.pLvlNow[which_agents]
self.t_age[which_agents] = 0 # How many periods since each agent was born
self.t_cycle[which_agents] = 0 | [
"def",
"simBirth",
"(",
"self",
",",
"which_agents",
")",
":",
"# Get and store states for newly born agents",
"N",
"=",
"np",
".",
"sum",
"(",
"which_agents",
")",
"# Number of new consumers to make",
"aNrmNow_new",
"=",
"drawLognormal",
"(",
"N",
",",
"mu",
"=",
... | Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------
which_agents : np.array(Bool)
Boolean array of size self.AgentCount indicating which agents should be "born".
Returns
-------
None | [
"Makes",
"new",
"consumers",
"for",
"the",
"given",
"indices",
".",
"Initialized",
"variables",
"include",
"aNrm",
"and",
"pLvl",
"as",
"well",
"as",
"time",
"variables",
"t_age",
"and",
"t_cycle",
".",
"Normalized",
"assets",
"and",
"persistent",
"income",
"l... | python | train | 50.272727 |
sorgerlab/indra | indra/sources/biopax/processor.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L344-L433 | def get_conversions(self):
"""Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules. This pattern thereby extracts metabolic
conversions as well as signaling processes via small molecules
(e.g. lipid phosphorylation or cleavage).
"""
# NOTE: This pattern gets all reactions in which a protein is the
# controller and chemicals are converted. But with this pattern only
# a single chemical is extracted from each side. This can be misleading
# since we want to capture all inputs and all outputs of the
# conversion. So we need to step back to the conversion itself and
# enumerate all inputs/outputs, make sure they constitute the kind
# of conversion we can capture here and then extract as a Conversion
# Statement. Another issue here is that the same reaction will be
# extracted multiple times if there is more then one input or output.
# Therefore we need to cache the ID of the reactions that have already
# been handled.
p = _bpp('Pattern')(_bpimpl('PhysicalEntity')().getModelInterface(),
'controller PE')
# Getting the control itself
p.add(cb.peToControl(), "controller PE", "Control")
# Make sure the controller is a protein
# TODO: possibly allow Complex too
p.add(tp(_bpimpl('Protein')().getModelInterface()), "controller PE")
# Link the control to the conversion that it controls
p.add(cb.controlToConv(), "Control", "Conversion")
# Make sure this is a BiochemicalRection (as opposed to, for instance,
# ComplexAssembly)
p.add(tp(_bpimpl('BiochemicalReaction')().getModelInterface()),
"Conversion")
# The controller shouldn't be a participant of the conversion
p.add(_bpp('constraint.NOT')(cb.participant()),
"Conversion", "controller PE")
# Get the input participant of the conversion
p.add(pt(rt.INPUT, True), "Control", "Conversion", "input PE")
# Link to the other side of the conversion
p.add(cs(cst.OTHER_SIDE), "input PE", "Conversion", "output PE")
# Make sure the two sides are not the same
p.add(_bpp('constraint.Equality')(False), "input PE", "output PE")
# Make sure the input/output is a chemical
p.add(tp(_bpimpl('SmallMolecule')().getModelInterface()), "input PE")
p.add(tp(_bpimpl('SmallMolecule')().getModelInterface()), "output PE")
s = _bpp('Searcher')
res = s.searchPlain(self.model, p)
res_array = [_match_to_array(m) for m in res.toArray()]
stmts = []
reaction_extracted = set()
for r in res_array:
controller_pe = r[p.indexOf('controller PE')]
reaction = r[p.indexOf('Conversion')]
control = r[p.indexOf('Control')]
input_pe = r[p.indexOf('input PE')]
output_pe = r[p.indexOf('output PE')]
if control.getUri() in reaction_extracted:
continue
# Get controller
subj_list = self._get_agents_from_entity(controller_pe)
# Get inputs and outputs
left = reaction.getLeft().toArray()
right = reaction.getRight().toArray()
# Skip this if not all participants are chemicals
if any([not _is_small_molecule(e) for e in left]):
continue
if any([not _is_small_molecule(e) for e in right]):
continue
obj_left = []
obj_right = []
for participant in left:
agent = self._get_agents_from_entity(participant)
if isinstance(agent, list):
obj_left += agent
else:
obj_left.append(agent)
for participant in right:
agent = self._get_agents_from_entity(participant)
if isinstance(agent, list):
obj_right += agent
else:
obj_right.append(agent)
ev = self._get_evidence(control)
for subj in _listify(subj_list):
st = Conversion(subj, obj_left, obj_right, evidence=ev)
st_dec = decode_obj(st, encoding='utf-8')
self.statements.append(st_dec)
reaction_extracted.add(control.getUri()) | [
"def",
"get_conversions",
"(",
"self",
")",
":",
"# NOTE: This pattern gets all reactions in which a protein is the",
"# controller and chemicals are converted. But with this pattern only",
"# a single chemical is extracted from each side. This can be misleading",
"# since we want to capture all i... | Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules. This pattern thereby extracts metabolic
conversions as well as signaling processes via small molecules
(e.g. lipid phosphorylation or cleavage). | [
"Extract",
"Conversion",
"INDRA",
"Statements",
"from",
"the",
"BioPAX",
"model",
"."
] | python | train | 50.611111 |
chaoss/grimoirelab-elk | grimoire_elk/enriched/kitsune.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/kitsune.py#L86-L99 | def get_identities(self, item):
""" Return the identities from an item """
item = item['data']
for identity in ['creator']:
# Todo: questions has also involved and solved_by
if identity in item and item[identity]:
user = self.get_sh_identity(item[identity])
yield user
if 'answers_data' in item:
for answer in item['answers_data']:
user = self.get_sh_identity(answer[identity])
yield user | [
"def",
"get_identities",
"(",
"self",
",",
"item",
")",
":",
"item",
"=",
"item",
"[",
"'data'",
"]",
"for",
"identity",
"in",
"[",
"'creator'",
"]",
":",
"# Todo: questions has also involved and solved_by",
"if",
"identity",
"in",
"item",
"and",
"item",
"[",
... | Return the identities from an item | [
"Return",
"the",
"identities",
"from",
"an",
"item"
] | python | train | 37.5 |
respondcreate/django-versatileimagefield | versatileimagefield/utils.py | https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/utils.py#L107-L128 | def get_resized_path(path_to_image, width, height,
filename_key, storage):
"""
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
"""
containing_folder, filename = os.path.split(path_to_image)
resized_filename = get_resized_filename(
filename,
width,
height,
filename_key
)
joined_path = os.path.join(*[
VERSATILEIMAGEFIELD_SIZED_DIRNAME,
containing_folder,
resized_filename
]).replace(' ', '') # Removing spaces so this path is memcached friendly
return joined_path | [
"def",
"get_resized_path",
"(",
"path_to_image",
",",
"width",
",",
"height",
",",
"filename_key",
",",
"storage",
")",
":",
"containing_folder",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path_to_image",
")",
"resized_filename",
"=",
"get_re... | Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key` | [
"Return",
"a",
"path_to_image",
"location",
"on",
"storage",
"as",
"dictated",
"by",
"width",
"height",
"and",
"filename_key"
] | python | test | 27.909091 |
Kellel/ProxyMiddleware | ProxyMiddleware/ProxyMiddleware.py | https://github.com/Kellel/ProxyMiddleware/blob/cb3a8854cbcb0f2ddccf5a688feca3c2debec8a4/ProxyMiddleware/ProxyMiddleware.py#L62-L75 | def force_slash(fn):
"""
Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work
"""
@wraps(fn)
def wrapped(*args, **kwargs):
if request.environ['PATH_INFO'].endswith('/'):
return fn(*args, **kwargs)
else:
redirect(request.environ['SCRIPT_NAME'] + request.environ['PATH_INFO'] + '/')
return wrapped | [
"def",
"force_slash",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"environ",
"[",
"'PATH_INFO'",
"]",
".",
"endswith",
"(",
"'/'",
")",
":",
"retu... | Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work | [
"Force",
"Slash",
"-----------"
] | python | train | 34.571429 |
molmod/molmod | molmod/io/gamess.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/io/gamess.py#L55-L75 | def _read(self, filename):
"""Internal routine that reads all data from the punch file."""
data = {}
parsers = [
FirstDataParser(), CoordinateParser(), EnergyGradParser(),
SkipApproxHessian(), HessianParser(), MassParser(),
]
with open(filename) as f:
while True:
line = f.readline()
if line == "":
break
# at each line, a parsers checks if it has to process a piece of
# file. If that happens, the parser gets control over the file
# and reads as many lines as it needs to collect data for some
# attributes.
for parser in parsers:
if parser.test(line, data):
parser.read(line, f, data)
break
self.__dict__.update(data) | [
"def",
"_read",
"(",
"self",
",",
"filename",
")",
":",
"data",
"=",
"{",
"}",
"parsers",
"=",
"[",
"FirstDataParser",
"(",
")",
",",
"CoordinateParser",
"(",
")",
",",
"EnergyGradParser",
"(",
")",
",",
"SkipApproxHessian",
"(",
")",
",",
"HessianParser... | Internal routine that reads all data from the punch file. | [
"Internal",
"routine",
"that",
"reads",
"all",
"data",
"from",
"the",
"punch",
"file",
"."
] | python | train | 42.095238 |
TeamHG-Memex/eli5 | eli5/formatters/as_dataframe.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/as_dataframe.py#L93-L116 | def format_as_dataframe(explanation):
# type: (Explanation) -> Optional[pd.DataFrame]
""" Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exported, ``None`` is returned.
This function also accepts some components of the explanation as arguments:
feature importances, targets, transition features.
Note that :func:`eli5.explain_weights` limits number of features
by default. If you need all features, pass ``top=None`` to
:func:`eli5.explain_weights`, or use
:func:`explain_weights_df`.
"""
for attr in _EXPORTED_ATTRIBUTES:
value = getattr(explanation, attr)
if value:
other_attrs = [a for a in _EXPORTED_ATTRIBUTES
if getattr(explanation, a) and a != attr]
if other_attrs:
warnings.warn('Exporting {} to DataFrame, but also {} could be '
'exported. Consider using eli5.format_as_dataframes.'
.format(attr, ', '.join(other_attrs)))
return format_as_dataframe(value)
return None | [
"def",
"format_as_dataframe",
"(",
"explanation",
")",
":",
"# type: (Explanation) -> Optional[pd.DataFrame]",
"for",
"attr",
"in",
"_EXPORTED_ATTRIBUTES",
":",
"value",
"=",
"getattr",
"(",
"explanation",
",",
"attr",
")",
"if",
"value",
":",
"other_attrs",
"=",
"[... | Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exported, ``None`` is returned.
This function also accepts some components of the explanation as arguments:
feature importances, targets, transition features.
Note that :func:`eli5.explain_weights` limits number of features
by default. If you need all features, pass ``top=None`` to
:func:`eli5.explain_weights`, or use
:func:`explain_weights_df`. | [
"Export",
"an",
"explanation",
"to",
"a",
"single",
"pandas",
".",
"DataFrame",
".",
"In",
"case",
"several",
"dataframes",
"could",
"be",
"exported",
"by",
":",
"func",
":",
"eli5",
".",
"formatters",
".",
"as_dataframe",
".",
"format_as_dataframes",
"a",
"... | python | train | 51 |
gambogi/CSHLDAP | CSHLDAP.py | https://github.com/gambogi/CSHLDAP/blob/09cb754b1e72437834e0d8cb4c7ac1830cfa6829/CSHLDAP.py#L99-L103 | def drinkAdmins(self, objects=False):
""" Returns a list of drink admins uids
"""
admins = self.group('drink', objects=objects)
return admins | [
"def",
"drinkAdmins",
"(",
"self",
",",
"objects",
"=",
"False",
")",
":",
"admins",
"=",
"self",
".",
"group",
"(",
"'drink'",
",",
"objects",
"=",
"objects",
")",
"return",
"admins"
] | Returns a list of drink admins uids | [
"Returns",
"a",
"list",
"of",
"drink",
"admins",
"uids"
] | python | train | 33.8 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_fcoe_ext.py#L65-L79 | def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")
fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
fcoe_intf_port_type = ET.SubElement(fcoe_intf_list, "fcoe-intf-port-type")
fcoe_intf_port_type.text = kwargs.pop('fcoe_intf_port_type')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe_get_interface",
"=",
"ET",
".",
"Element",
"(",
"\"fcoe_get_interface\"",
")",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 52.466667 |
observermedia/django-wordpress-rest | wordpress/loading.py | https://github.com/observermedia/django-wordpress-rest/blob/f0d96891d8ac5a69c8ba90e044876e756fad1bfe/wordpress/loading.py#L864-L879 | def process_post_many_to_many_field(existing_post, field, related_objects):
"""
Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_objects: the list of objects for the field, that need to be sync'd to the Post
:return: None
"""
to_add = set(related_objects.get(existing_post.wp_id, set())) - set(getattr(existing_post, field).all())
to_remove = set(getattr(existing_post, field).all()) - set(related_objects.get(existing_post.wp_id, set()))
if to_add:
getattr(existing_post, field).add(*to_add)
if to_remove:
getattr(existing_post, field).remove(*to_remove) | [
"def",
"process_post_many_to_many_field",
"(",
"existing_post",
",",
"field",
",",
"related_objects",
")",
":",
"to_add",
"=",
"set",
"(",
"related_objects",
".",
"get",
"(",
"existing_post",
".",
"wp_id",
",",
"set",
"(",
")",
")",
")",
"-",
"set",
"(",
"... | Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_objects: the list of objects for the field, that need to be sync'd to the Post
:return: None | [
"Sync",
"data",
"for",
"a",
"many",
"-",
"to",
"-",
"many",
"field",
"related",
"to",
"a",
"post",
"using",
"set",
"differences",
"."
] | python | train | 50.0625 |
DLR-RM/RAFCON | source/rafcon/core/script.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/script.py#L107-L117 | def _load_script(self):
"""Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened
"""
script_text = filesystem.read_file(self.path, self.filename)
if not script_text:
raise IOError("Script file could not be opened or was empty: {0}"
"".format(os.path.join(self.path, self.filename)))
self.script = script_text | [
"def",
"_load_script",
"(",
"self",
")",
":",
"script_text",
"=",
"filesystem",
".",
"read_file",
"(",
"self",
".",
"path",
",",
"self",
".",
"filename",
")",
"if",
"not",
"script_text",
":",
"raise",
"IOError",
"(",
"\"Script file could not be opened or was emp... | Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened | [
"Loads",
"the",
"script",
"from",
"the",
"filesystem"
] | python | train | 39.636364 |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L903-L913 | def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._really_parse_tag()
except BadRoute:
self._head = reset
self._emit_text("<")
else:
self._emit_all(tag) | [
"def",
"_parse_tag",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"self",
".",
"_head",
"+=",
"1",
"try",
":",
"tag",
"=",
"self",
".",
"_really_parse_tag",
"(",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"self"... | Parse an HTML tag at the head of the wikicode string. | [
"Parse",
"an",
"HTML",
"tag",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
] | python | train | 29.181818 |
vpelletier/python-libaio | libaio/__init__.py | https://github.com/vpelletier/python-libaio/blob/5b5a2fed5418e2bd1ac9197fa46c69dae86c6fe3/libaio/__init__.py#L384-L393 | def close(self):
"""
Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context.
"""
if self._ctx is not None:
# Note: same as io_destroy
self._io_queue_release(self._ctx)
del self._ctx | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ctx",
"is",
"not",
"None",
":",
"# Note: same as io_destroy",
"self",
".",
"_io_queue_release",
"(",
"self",
".",
"_ctx",
")",
"del",
"self",
".",
"_ctx"
] | Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context. | [
"Cancels",
"all",
"pending",
"IO",
"blocks",
".",
"Waits",
"until",
"all",
"non",
"-",
"cancellable",
"IO",
"blocks",
"finish",
".",
"De",
"-",
"initialises",
"AIO",
"context",
"."
] | python | test | 30.9 |
HazyResearch/fonduer | src/fonduer/candidates/matchers.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/matchers.py#L472-L474 | def _is_subspan(self, m, span):
"""Tests if mention m does exist"""
return m.figure.document.id == span[0] and m.figure.position == span[1] | [
"def",
"_is_subspan",
"(",
"self",
",",
"m",
",",
"span",
")",
":",
"return",
"m",
".",
"figure",
".",
"document",
".",
"id",
"==",
"span",
"[",
"0",
"]",
"and",
"m",
".",
"figure",
".",
"position",
"==",
"span",
"[",
"1",
"]"
] | Tests if mention m does exist | [
"Tests",
"if",
"mention",
"m",
"does",
"exist"
] | python | train | 51 |
pytroll/satpy | satpy/writers/mitiff.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/writers/mitiff.py#L109-L154 | def save_datasets(self, datasets, filename=None, fill_value=None,
compute=True, **kwargs):
"""Save all datasets to one or more files.
"""
LOG.debug("Starting in mitiff save_datasets ... ")
def _delayed_create(create_opts, datasets):
LOG.debug("create_opts: %s", create_opts)
try:
if 'platform_name' not in kwargs:
kwargs['platform_name'] = datasets.attrs['platform_name']
if 'name' not in kwargs:
kwargs['name'] = datasets[0].attrs['name']
if 'start_time' not in kwargs:
kwargs['start_time'] = datasets[0].attrs['start_time']
if 'sensor' not in kwargs:
kwargs['sensor'] = datasets[0].attrs['sensor']
try:
self.mitiff_config[kwargs['sensor']] = datasets['metadata_requirements']['config']
self.translate_channel_name[kwargs['sensor']] = datasets['metadata_requirements']['translate']
self.channel_order[kwargs['sensor']] = datasets['metadata_requirements']['order']
self.file_pattern = datasets['metadata_requirements']['file_pattern']
except KeyError:
# For some mitiff products this info is needed, for others not.
# If needed you should know how to fix this
pass
image_description = self._make_image_description(datasets, **kwargs)
LOG.debug("File pattern %s", self.file_pattern)
if isinstance(datasets, list):
kwargs['start_time'] = datasets[0].attrs['start_time']
else:
kwargs['start_time'] = datasets.attrs['start_time']
gen_filename = filename or self.get_filename(**kwargs)
LOG.info("Saving mitiff to: %s ...", gen_filename)
self._save_datasets_as_mitiff(datasets, image_description, gen_filename, **kwargs)
except (KeyError, ValueError, RuntimeError):
raise
create_opts = ()
delayed = dask.delayed(_delayed_create)(create_opts, datasets)
LOG.debug("About to call delayed compute ...")
if compute:
return delayed.compute()
return delayed | [
"def",
"save_datasets",
"(",
"self",
",",
"datasets",
",",
"filename",
"=",
"None",
",",
"fill_value",
"=",
"None",
",",
"compute",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Starting in mitiff save_datasets ... \"",
")",
... | Save all datasets to one or more files. | [
"Save",
"all",
"datasets",
"to",
"one",
"or",
"more",
"files",
"."
] | python | train | 50.630435 |
janpipek/physt | physt/util.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/util.py#L9-L18 | def all_subclasses(cls: type) -> Tuple[type, ...]:
"""All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
"""
subclasses = []
for subclass in cls.__subclasses__():
subclasses.append(subclass)
subclasses.extend(all_subclasses(subclass))
return tuple(subclasses) | [
"def",
"all_subclasses",
"(",
"cls",
":",
"type",
")",
"->",
"Tuple",
"[",
"type",
",",
"...",
"]",
":",
"subclasses",
"=",
"[",
"]",
"for",
"subclass",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"subclasses",
".",
"append",
"(",
"subclass",
... | All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780 | [
"All",
"subclasses",
"of",
"a",
"class",
"."
] | python | train | 31.7 |
nats-io/python-nats | nats/io/client.py | https://github.com/nats-io/python-nats/blob/4a409319c409e7e55ce8377b64b406375c5f455b/nats/io/client.py#L465-L482 | def publish_request(self, subject, reply, payload):
"""
Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _INBOX.2007314fe0fcb2cdc2a2914c1 5
"""
payload_size = len(payload)
if payload_size > self._max_payload_size:
raise ErrMaxPayload
if self.is_closed:
raise ErrConnectionClosed
yield self._publish(subject, reply, payload, payload_size)
if self._flush_queue.empty():
yield self._flush_pending() | [
"def",
"publish_request",
"(",
"self",
",",
"subject",
",",
"reply",
",",
"payload",
")",
":",
"payload_size",
"=",
"len",
"(",
"payload",
")",
"if",
"payload_size",
">",
"self",
".",
"_max_payload_size",
":",
"raise",
"ErrMaxPayload",
"if",
"self",
".",
"... | Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _INBOX.2007314fe0fcb2cdc2a2914c1 5 | [
"Publishes",
"a",
"message",
"tagging",
"it",
"with",
"a",
"reply",
"subscription",
"which",
"can",
"be",
"used",
"by",
"those",
"receiving",
"the",
"message",
"to",
"respond",
":"
] | python | train | 37.611111 |
andrey-git/pysensibo | pysensibo/__init__.py | https://github.com/andrey-git/pysensibo/blob/c471c99ee64bbcc78f3a10aabc0e3b326a1f64f8/pysensibo/__init__.py#L38-L41 | def async_get_device(self, uid, fields='*'):
"""Get specific device by ID."""
return (yield from self._get('/pods/{}'.format(uid),
fields=fields)) | [
"def",
"async_get_device",
"(",
"self",
",",
"uid",
",",
"fields",
"=",
"'*'",
")",
":",
"return",
"(",
"yield",
"from",
"self",
".",
"_get",
"(",
"'/pods/{}'",
".",
"format",
"(",
"uid",
")",
",",
"fields",
"=",
"fields",
")",
")"
] | Get specific device by ID. | [
"Get",
"specific",
"device",
"by",
"ID",
"."
] | python | train | 49 |
zhmcclient/python-zhmcclient | zhmcclient/_partition.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_partition.py#L284-L328 | def feature_enabled(self, feature_name):
"""
Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section "Features" in the
:term:`HMC API`, or use the :meth:`feature_info` method.
Authorization requirements:
* Object-access permission to this partition.
Parameters:
feature_name (:term:`string`): The name of the feature.
Returns:
bool: `True` if the feature is enabled, or `False` if the feature is
disabled (but available).
Raises:
:exc:`ValueError`: Features are not supported on the HMC.
:exc:`ValueError`: The specified feature is not available for the
CPC.
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
:exc:`~zhmcclient.ConnectionError`
"""
feature_list = self.prop('available-features-list', None)
if feature_list is None:
raise ValueError("Firmware features are not supported on CPC %s" %
self.manager.cpc.name)
for feature in feature_list:
if feature['name'] == feature_name:
break
else:
raise ValueError("Firmware feature %s is not available on CPC %s" %
(feature_name, self.manager.cpc.name))
return feature['state'] | [
"def",
"feature_enabled",
"(",
"self",
",",
"feature_name",
")",
":",
"feature_list",
"=",
"self",
".",
"prop",
"(",
"'available-features-list'",
",",
"None",
")",
"if",
"feature_list",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Firmware features are not su... | Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section "Features" in the
:term:`HMC API`, or use the :meth:`feature_info` method.
Authorization requirements:
* Object-access permission to this partition.
Parameters:
feature_name (:term:`string`): The name of the feature.
Returns:
bool: `True` if the feature is enabled, or `False` if the feature is
disabled (but available).
Raises:
:exc:`ValueError`: Features are not supported on the HMC.
:exc:`ValueError`: The specified feature is not available for the
CPC.
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
:exc:`~zhmcclient.ConnectionError` | [
"Indicates",
"whether",
"the",
"specified",
"feature",
"is",
"enabled",
"for",
"the",
"CPC",
"of",
"this",
"partition",
"."
] | python | train | 34.622222 |
apple/turicreate | src/unity/python/turicreate/toolkits/distances/_util.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/distances/_util.py#L232-L301 | def build_address_distance(number=None, street=None, city=None, state=None,
zip_code=None):
"""
Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model. When the composite distance
is applied in a particular context, the feature types and individual
distance functions must be appropriate for the given model.
Parameters
----------
number, street, city, state, zip_code : string, optional
Name of the SFrame column for the feature corresponding to the address
component. Each feature name is mapped to an appropriate distance
function and scalar multiplier.
Returns
-------
dist : list
A composite distance function, mapping sets of feature names to distance
functions.
Examples
--------
>>> homes = turicreate.SFrame({'sqft': [1230, 875, 1745],
... 'street': ['phinney', 'fairview', 'cottage'],
... 'city': ['seattle', 'olympia', 'boston'],
... 'state': ['WA', 'WA', 'MA']})
...
>>> my_dist = turicreate.distances.build_address_distance(street='street',
... city='city',
... state='state')
>>> my_dist
[[['street'], 'jaccard', 5],
[['state'], 'jaccard', 5],
[['city'], 'levenshtein', 1]]
"""
## Validate inputs
for param in [number, street, city, state, zip_code]:
if param is not None and not isinstance(param, str):
raise TypeError("All inputs must be strings. Each parameter is " +
"intended to be the name of an SFrame column.")
## Figure out features for levenshtein distance.
string_features = []
if city:
string_features.append(city)
if zip_code:
string_features.append(zip_code)
## Compile the distance components.
dist = []
if number:
dist.append([[number], 'jaccard', 1])
if street:
dist.append([[street], 'jaccard', 5])
if state:
dist.append([[state], 'jaccard', 5])
if len(string_features) > 0:
dist.append([string_features, 'levenshtein', 1])
return dist | [
"def",
"build_address_distance",
"(",
"number",
"=",
"None",
",",
"street",
"=",
"None",
",",
"city",
"=",
"None",
",",
"state",
"=",
"None",
",",
"zip_code",
"=",
"None",
")",
":",
"## Validate inputs",
"for",
"param",
"in",
"[",
"number",
",",
"street"... | Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model. When the composite distance
is applied in a particular context, the feature types and individual
distance functions must be appropriate for the given model.
Parameters
----------
number, street, city, state, zip_code : string, optional
Name of the SFrame column for the feature corresponding to the address
component. Each feature name is mapped to an appropriate distance
function and scalar multiplier.
Returns
-------
dist : list
A composite distance function, mapping sets of feature names to distance
functions.
Examples
--------
>>> homes = turicreate.SFrame({'sqft': [1230, 875, 1745],
... 'street': ['phinney', 'fairview', 'cottage'],
... 'city': ['seattle', 'olympia', 'boston'],
... 'state': ['WA', 'WA', 'MA']})
...
>>> my_dist = turicreate.distances.build_address_distance(street='street',
... city='city',
... state='state')
>>> my_dist
[[['street'], 'jaccard', 5],
[['state'], 'jaccard', 5],
[['city'], 'levenshtein', 1]] | [
"Construct",
"a",
"composite",
"distance",
"appropriate",
"for",
"matching",
"address",
"data",
".",
"NOTE",
":",
"this",
"utility",
"function",
"does",
"not",
"guarantee",
"that",
"the",
"output",
"composite",
"distance",
"will",
"work",
"with",
"a",
"particula... | python | train | 33.7 |
ChrisCummins/labm8 | modules.py | https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/modules.py#L28-L68 | def import_foreign(name, custom_name=None):
"""
Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Example:
To import the standard module "math" as "std_math":
if labm8.is_python3():
import math as std_math
else:
std_math = modules.import_foreign("math", "std_math")
Arguments:
name (str): The name of the module to import.
custom_name (str, optional): The custom name to assign the module to.
Raises:
ImportError: If the module is not found.
"""
if lab.is_python3():
io.error(("Ignoring attempt to import foreign module '{mod}' "
"using python version {major}.{minor}"
.format(mod=name, major=sys.version_info[0],
minor=sys.version_info[1])))
return
custom_name = custom_name or name
f, pathname, desc = imp.find_module(name, sys.path[1:])
module = imp.load_module(custom_name, f, pathname, desc)
f.close()
return module | [
"def",
"import_foreign",
"(",
"name",
",",
"custom_name",
"=",
"None",
")",
":",
"if",
"lab",
".",
"is_python3",
"(",
")",
":",
"io",
".",
"error",
"(",
"(",
"\"Ignoring attempt to import foreign module '{mod}' \"",
"\"using python version {major}.{minor}\"",
".",
"... | Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Example:
To import the standard module "math" as "std_math":
if labm8.is_python3():
import math as std_math
else:
std_math = modules.import_foreign("math", "std_math")
Arguments:
name (str): The name of the module to import.
custom_name (str, optional): The custom name to assign the module to.
Raises:
ImportError: If the module is not found. | [
"Import",
"a",
"module",
"with",
"a",
"custom",
"name",
"."
] | python | train | 28.804878 |
awslabs/sockeye | sockeye/encoder.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/encoder.py#L124-L174 | def get_recurrent_encoder(config: RecurrentEncoderConfig, prefix: str) -> 'Encoder':
"""
Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance.
"""
# TODO give more control on encoder architecture
encoder_seq = EncoderSequence([], config.dtype)
if config.conv_config is not None:
encoder_seq.append(ConvolutionalEmbeddingEncoder, config=config.conv_config,
prefix=prefix + C.CHAR_SEQ_ENCODER_PREFIX)
if config.conv_config.add_positional_encoding:
# If specified, add positional encodings to segment embeddings
encoder_seq.append(AddSinCosPositionalEmbeddings,
num_embed=config.conv_config.num_embed,
scale_up_input=False,
scale_down_positions=False,
prefix="%s%sadd_positional_encodings" % (prefix, C.CHAR_SEQ_ENCODER_PREFIX))
encoder_seq.append(ConvertLayout, infer_hidden=True, target_layout=C.TIME_MAJOR)
else:
encoder_seq.append(ConvertLayout, target_layout=C.TIME_MAJOR, num_hidden=0)
if config.reverse_input:
encoder_seq.append(ReverseSequence, infer_hidden=True)
if config.rnn_config.residual:
utils.check_condition(config.rnn_config.first_residual_layer >= 2,
"Residual connections on the first encoder layer are not supported")
# One layer bi-directional RNN:
encoder_seq.append(BiDirectionalRNNEncoder,
rnn_config=config.rnn_config.copy(num_layers=1),
prefix=prefix + C.BIDIRECTIONALRNN_PREFIX,
layout=C.TIME_MAJOR)
if config.rnn_config.num_layers > 1:
# Stacked uni-directional RNN:
# Because we already have a one layer bi-rnn we reduce the num_layers as well as the first_residual_layer.
remaining_rnn_config = config.rnn_config.copy(num_layers=config.rnn_config.num_layers - 1,
first_residual_layer=config.rnn_config.first_residual_layer - 1)
encoder_seq.append(RecurrentEncoder,
rnn_config=remaining_rnn_config,
prefix=prefix + C.STACKEDRNN_PREFIX,
layout=C.TIME_MAJOR)
encoder_seq.append(ConvertLayout, infer_hidden=True, target_layout=C.BATCH_MAJOR)
return encoder_seq | [
"def",
"get_recurrent_encoder",
"(",
"config",
":",
"RecurrentEncoderConfig",
",",
"prefix",
":",
"str",
")",
"->",
"'Encoder'",
":",
"# TODO give more control on encoder architecture",
"encoder_seq",
"=",
"EncoderSequence",
"(",
"[",
"]",
",",
"config",
".",
"dtype",... | Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance. | [
"Returns",
"an",
"encoder",
"stack",
"with",
"a",
"bi",
"-",
"directional",
"RNN",
"and",
"a",
"variable",
"number",
"of",
"uni",
"-",
"directional",
"forward",
"RNNs",
"."
] | python | train | 50.45098 |
materialsproject/pymatgen-db | matgendb/builders/incr.py | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/builders/incr.py#L390-L395 | def _get(self, operation, field):
"""Get tracked position for a given operation and field."""
self._check_exists()
query = {Mark.FLD_OP: operation.name,
Mark.FLD_MARK + "." + field: {"$exists": True}}
return self._track.find_one(query) | [
"def",
"_get",
"(",
"self",
",",
"operation",
",",
"field",
")",
":",
"self",
".",
"_check_exists",
"(",
")",
"query",
"=",
"{",
"Mark",
".",
"FLD_OP",
":",
"operation",
".",
"name",
",",
"Mark",
".",
"FLD_MARK",
"+",
"\".\"",
"+",
"field",
":",
"{... | Get tracked position for a given operation and field. | [
"Get",
"tracked",
"position",
"for",
"a",
"given",
"operation",
"and",
"field",
"."
] | python | train | 46.5 |
changecoin/changetip-python | changetip/bots/base.py | https://github.com/changecoin/changetip-python/blob/daa6e2f41712eb58d16c537af34f9f0a1b74a14e/changetip/bots/base.py#L49-L70 | def send_tip(self, sender, receiver, message, context_uid, meta):
""" Send a request to the ChangeTip API, to be delivered immediately. """
assert self.channel is not None, "channel must be defined"
# Add extra data to meta
meta["mention_bot"] = self.mention_bot()
data = json.dumps({
"channel": self.channel,
"sender": sender,
"receiver": receiver,
"message": message,
"context_uid": context_uid,
"meta": meta,
})
response = requests.post(self.get_api_url("/tips/"), data=data, headers={'content-type': 'application/json'})
if response.headers.get("Content-Type", None) == "application/json":
out = response.json()
out["state"] = response.reason.lower()
return out
else:
return {"state": response.reason.lower(), "error": "%s error submitting tip" % response.status_code} | [
"def",
"send_tip",
"(",
"self",
",",
"sender",
",",
"receiver",
",",
"message",
",",
"context_uid",
",",
"meta",
")",
":",
"assert",
"self",
".",
"channel",
"is",
"not",
"None",
",",
"\"channel must be defined\"",
"# Add extra data to meta",
"meta",
"[",
"\"me... | Send a request to the ChangeTip API, to be delivered immediately. | [
"Send",
"a",
"request",
"to",
"the",
"ChangeTip",
"API",
"to",
"be",
"delivered",
"immediately",
"."
] | python | train | 42.954545 |
python-bugzilla/python-bugzilla | bugzilla/bug.py | https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L328-L344 | def get_flag_status(self, name):
"""
Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value information.
"""
f = self.get_flags(name)
if not f:
return None
# This method works only for simple flags that have only one
# value set.
assert len(f) <= 1
return f[0]['status'] | [
"def",
"get_flag_status",
"(",
"self",
",",
"name",
")",
":",
"f",
"=",
"self",
".",
"get_flags",
"(",
"name",
")",
"if",
"not",
"f",
":",
"return",
"None",
"# This method works only for simple flags that have only one",
"# value set.",
"assert",
"len",
"(",
"f"... | Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value information. | [
"Return",
"a",
"flag",
"status",
"field"
] | python | train | 31.058824 |
saltstack/salt | salt/modules/jenkinsmod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jenkinsmod.py#L254-L295 | def create_job(name=None,
config_xml=None,
saltenv='base'):
'''
Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.create_job jobname
salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml'
'''
if not name:
raise SaltInvocationError('Required parameter \'name\' is missing')
if job_exists(name):
raise CommandExecutionError('Job \'{0}\' already exists'.format(name))
if not config_xml:
config_xml = jenkins.EMPTY_CONFIG_XML
else:
config_xml_file = _retrieve_config_xml(config_xml, saltenv)
with salt.utils.files.fopen(config_xml_file) as _fp:
config_xml = salt.utils.stringutils.to_unicode(_fp.read())
server = _connect()
try:
server.create_job(name, config_xml)
except jenkins.JenkinsException as err:
raise CommandExecutionError(
'Encountered error creating job \'{0}\': {1}'.format(name, err)
)
return config_xml | [
"def",
"create_job",
"(",
"name",
"=",
"None",
",",
"config_xml",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"if",
"not",
"name",
":",
"raise",
"SaltInvocationError",
"(",
"'Required parameter \\'name\\' is missing'",
")",
"if",
"job_exists",
"(",
"... | Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: bash
salt '*' jenkins.create_job jobname
salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml' | [
"Return",
"the",
"configuration",
"file",
"."
] | python | train | 30.166667 |
vxgmichel/aiostream | aiostream/stream/select.py | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L62-L78 | async def skiplast(source, n):
"""Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated.
"""
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
if n <= 0:
yield item
continue
if len(queue) == n:
yield queue[0]
queue.append(item) | [
"async",
"def",
"skiplast",
"(",
"source",
",",
"n",
")",
":",
"queue",
"=",
"collections",
".",
"deque",
"(",
"maxlen",
"=",
"n",
"if",
"n",
">",
"0",
"else",
"0",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"... | Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated. | [
"Forward",
"an",
"asynchronous",
"sequence",
"skipping",
"the",
"last",
"n",
"elements",
"."
] | python | train | 33.823529 |
mitsei/dlkit | dlkit/services/authorization.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/authorization.py#L1145-L1153 | def use_comparative_authorization_view(self):
"""Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view"""
self._object_views['authorization'] = COMPARATIVE
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
try:
session.use_comparative_authorization_view()
except AttributeError:
pass | [
"def",
"use_comparative_authorization_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'authorization'",
"]",
"=",
"COMPARATIVE",
"# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",... | Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view | [
"Pass",
"through",
"to",
"provider",
"AuthorizationLookupSession",
".",
"use_comparative_authorization_view"
] | python | train | 54.555556 |
tanghaibao/jcvi | jcvi/apps/base.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L1305-L1353 | def pushnotify(subject, message, api="pushover", priority=0, timestamp=None):
"""
Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
-------------------
[pushover]
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
user: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
[nma]
apikey: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
[pushbullet]
apikey: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
iden: dddddddddddddddddddddddddddddddddddd
"""
import types
assert type(priority) is int and -1 <= priority <= 2, \
"Priority should be and int() between -1 and 2"
cfgfile = op.join(op.expanduser("~"), "pushnotify.ini")
Config = ConfigParser()
if op.exists(cfgfile):
Config.read(cfgfile)
else:
sys.exit("Push notification config file `{0}`".format(cfgfile) + \
" does not exist!")
if api == "pushover":
cfg = ConfigSectionMap(Config, api)
token, key = cfg["token"], cfg["user"]
pushover(message, token, key, title=subject, \
priority=priority, timestamp=timestamp)
elif api == "nma":
cfg = ConfigSectionMap(Config, api)
apikey = cfg["apikey"]
nma(message, apikey, event=subject, \
priority=priority)
elif api == "pushbullet":
cfg = ConfigSectionMap(Config, api)
apikey, iden = cfg["apikey"], cfg['iden']
pushbullet(message, apikey, iden, title=subject, \
type="note") | [
"def",
"pushnotify",
"(",
"subject",
",",
"message",
",",
"api",
"=",
"\"pushover\"",
",",
"priority",
"=",
"0",
",",
"timestamp",
"=",
"None",
")",
":",
"import",
"types",
"assert",
"type",
"(",
"priority",
")",
"is",
"int",
"and",
"-",
"1",
"<=",
"... | Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
-------------------
[pushover]
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
user: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
[nma]
apikey: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
[pushbullet]
apikey: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
iden: dddddddddddddddddddddddddddddddddddd | [
"Send",
"push",
"notifications",
"using",
"pre",
"-",
"existing",
"APIs"
] | python | train | 33.408163 |
intel-analytics/BigDL | pyspark/bigdl/nn/layer.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L329-L360 | def evaluate(self, *args):
"""
No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the input data
:param batch_size: batch size
:param val_methods: a list of validation methods. i.e: Top1Accuracy,Top5Accuracy and Loss.
:return: a list of the metrics result
"""
if len(args) == 0:
callBigDlFunc(self.bigdl_type,
"evaluate", self.value)
return self
elif len(args) == 3:
dataset, batch_size, val_methods = args
if (isinstance(dataset, ImageFrame)):
return callBigDlFunc(self.bigdl_type,
"modelEvaluateImageFrame",
self.value,
dataset, batch_size, val_methods)
else:
return callBigDlFunc(self.bigdl_type,
"modelEvaluate",
self.value,
dataset, batch_size, val_methods)
else:
raise Exception("Error when calling evaluate(): it takes no argument or exactly three arguments only") | [
"def",
"evaluate",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"evaluate\"",
",",
"self",
".",
"value",
")",
"return",
"self",
"elif",
"len",
"(",
"... | No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the input data
:param batch_size: batch size
:param val_methods: a list of validation methods. i.e: Top1Accuracy,Top5Accuracy and Loss.
:return: a list of the metrics result | [
"No",
"argument",
"passed",
"in",
":",
"Evaluate",
"the",
"model",
"to",
"set",
"train",
"=",
"false",
"useful",
"when",
"doing",
"test",
"/",
"forward",
":",
"return",
":",
"layer",
"itself"
] | python | test | 42.28125 |
vertexproject/synapse | synapse/lib/editatom.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/editatom.py#L85-L125 | async def commit(self, snap):
'''
Push the recorded changes to disk, notify all the listeners
'''
if not self.npvs: # nothing to do
return
for node, prop, _, valu in self.npvs:
node.props[prop.name] = valu
node.proplayr[prop.name] = snap.wlyr
splices = [snap.splice('node:add', ndef=node.ndef) for node in self.mybldgbuids.values()]
for node, prop, oldv, valu in self.npvs:
info = {'ndef': node.ndef, 'prop': prop.name, 'valu': valu}
if oldv is not None:
info['oldv'] = oldv
splices.append(snap.splice('prop:set', **info))
await snap.stor(self.sops, splices)
for node in self.mybldgbuids.values():
snap.core.pokeFormCount(node.form.name, 1)
snap.buidcache.append(node)
snap.livenodes[node.buid] = node
await self.rendevous()
for node in self.mybldgbuids.values():
await node.form.wasAdded(node)
# fire all his prop sets
for node, prop, oldv, valu in self.npvs:
await prop.wasSet(node, oldv)
if prop.univ:
univ = snap.model.prop(prop.univ)
await univ.wasSet(node, oldv)
# Finally, fire all the triggers
for node, prop, oldv, _ in self.npvs:
await snap.core.triggers.runPropSet(node, prop, oldv) | [
"async",
"def",
"commit",
"(",
"self",
",",
"snap",
")",
":",
"if",
"not",
"self",
".",
"npvs",
":",
"# nothing to do",
"return",
"for",
"node",
",",
"prop",
",",
"_",
",",
"valu",
"in",
"self",
".",
"npvs",
":",
"node",
".",
"props",
"[",
"prop",
... | Push the recorded changes to disk, notify all the listeners | [
"Push",
"the",
"recorded",
"changes",
"to",
"disk",
"notify",
"all",
"the",
"listeners"
] | python | train | 33.829268 |
NaturalHistoryMuseum/pyzbar | pyzbar/pyzbar.py | https://github.com/NaturalHistoryMuseum/pyzbar/blob/833b375c0e84077943b7100cc9dc22a7bd48754b/pyzbar/pyzbar.py#L90-L116 | def _decode_symbols(symbols):
"""Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
"""
for symbol in symbols:
data = string_at(zbar_symbol_get_data(symbol))
# The 'type' int in a value in the ZBarSymbol enumeration
symbol_type = ZBarSymbol(symbol.contents.type).name
polygon = convex_hull(
(
zbar_symbol_get_loc_x(symbol, index),
zbar_symbol_get_loc_y(symbol, index)
)
for index in _RANGEFN(zbar_symbol_get_loc_size(symbol))
)
yield Decoded(
data=data,
type=symbol_type,
rect=bounding_box(polygon),
polygon=polygon
) | [
"def",
"_decode_symbols",
"(",
"symbols",
")",
":",
"for",
"symbol",
"in",
"symbols",
":",
"data",
"=",
"string_at",
"(",
"zbar_symbol_get_data",
"(",
"symbol",
")",
")",
"# The 'type' int in a value in the ZBarSymbol enumeration",
"symbol_type",
"=",
"ZBarSymbol",
"(... | Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol | [
"Generator",
"of",
"decoded",
"symbol",
"information",
"."
] | python | train | 29.148148 |
bwhite/hadoopy | hadoopy/_hdfs.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L81-L91 | def isempty(path):
"""Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise.
"""
cmd = "hadoop fs -test -z %s"
p = _hadoop_fs_command(cmd % (path))
p.communicate()
rcode = p.returncode
return bool(int(rcode == 0)) | [
"def",
"isempty",
"(",
"path",
")",
":",
"cmd",
"=",
"\"hadoop fs -test -z %s\"",
"p",
"=",
"_hadoop_fs_command",
"(",
"cmd",
"%",
"(",
"path",
")",
")",
"p",
".",
"communicate",
"(",
")",
"rcode",
"=",
"p",
".",
"returncode",
"return",
"bool",
"(",
"i... | Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise. | [
"Check",
"if",
"a",
"path",
"has",
"zero",
"length",
"(",
"also",
"true",
"if",
"it",
"s",
"a",
"directory",
")"
] | python | train | 34.818182 |
has2k1/plotnine | plotnine/aes.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L343-L350 | def is_position_aes(vars_):
"""
Figure out if an aesthetic is a position aesthetic or not
"""
try:
return all([aes_to_scale(v) in {'x', 'y'} for v in vars_])
except TypeError:
return aes_to_scale(vars_) in {'x', 'y'} | [
"def",
"is_position_aes",
"(",
"vars_",
")",
":",
"try",
":",
"return",
"all",
"(",
"[",
"aes_to_scale",
"(",
"v",
")",
"in",
"{",
"'x'",
",",
"'y'",
"}",
"for",
"v",
"in",
"vars_",
"]",
")",
"except",
"TypeError",
":",
"return",
"aes_to_scale",
"(",... | Figure out if an aesthetic is a position aesthetic or not | [
"Figure",
"out",
"if",
"an",
"aesthetic",
"is",
"a",
"position",
"aesthetic",
"or",
"not"
] | python | train | 30.625 |
cosven/feeluown-core | fuocore/netease/api.py | https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/netease/api.py#L116-L129 | def search(self, s, stype=1, offset=0, total='true', limit=60):
"""get songs list from search keywords"""
action = uri + '/search/get'
data = {
's': s,
'type': stype,
'offset': offset,
'total': total,
'limit': 60
}
resp = self.request('POST', action, data)
if resp['code'] == 200:
return resp['result']['songs']
return [] | [
"def",
"search",
"(",
"self",
",",
"s",
",",
"stype",
"=",
"1",
",",
"offset",
"=",
"0",
",",
"total",
"=",
"'true'",
",",
"limit",
"=",
"60",
")",
":",
"action",
"=",
"uri",
"+",
"'/search/get'",
"data",
"=",
"{",
"'s'",
":",
"s",
",",
"'type'... | get songs list from search keywords | [
"get",
"songs",
"list",
"from",
"search",
"keywords"
] | python | train | 31.142857 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L85-L127 | def thesis_info(self, key, value):
"""Populate the ``thesis_info`` key."""
def _get_degree_type(value):
DEGREE_TYPES_MAP = {
'RAPPORT DE STAGE': 'other',
'INTERNSHIP REPORT': 'other',
'DIPLOMA': 'diploma',
'BACHELOR': 'bachelor',
'LAUREA': 'laurea',
'MASTER': 'master',
'THESIS': 'other',
'PHD': 'phd',
'PDF': 'phd',
'PH.D. THESIS': 'phd',
'HABILITATION': 'habilitation',
}
b_value = force_single_element(value.get('b', ''))
if b_value:
return DEGREE_TYPES_MAP.get(b_value.upper(), 'other')
def _get_institutions(value):
c_values = force_list(value.get('c'))
z_values = force_list(value.get('z'))
# XXX: we zip only when they have the same length, otherwise
# we might match a value with the wrong recid.
if len(c_values) != len(z_values):
return [{'name': c_value} for c_value in c_values]
else:
return [{
'curated_relation': True,
'name': c_value,
'record': get_record_ref(z_value, 'institutions'),
} for c_value, z_value in zip(c_values, z_values)]
thesis_info = self.get('thesis_info', {})
thesis_info['date'] = normalize_date(force_single_element(value.get('d')))
thesis_info['degree_type'] = _get_degree_type(value)
thesis_info['institutions'] = _get_institutions(value)
return thesis_info | [
"def",
"thesis_info",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"def",
"_get_degree_type",
"(",
"value",
")",
":",
"DEGREE_TYPES_MAP",
"=",
"{",
"'RAPPORT DE STAGE'",
":",
"'other'",
",",
"'INTERNSHIP REPORT'",
":",
"'other'",
",",
"'DIPLOMA'",
":",
"... | Populate the ``thesis_info`` key. | [
"Populate",
"the",
"thesis_info",
"key",
"."
] | python | train | 34.976744 |
tanghaibao/goatools | goatools/grouper/plotobj.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/plotobj.py#L44-L53 | def get_kws_plt(self):
"""Get keyword args for GoSubDagPlot from self unless they are None."""
kws_plt = {}
for key_plt in self.keys_plt:
key_val = getattr(self, key_plt, None)
if key_val is not None:
kws_plt[key_plt] = key_val
elif key_plt in self.kws:
kws_plt[key_plt] = self.kws[key_plt]
return kws_plt | [
"def",
"get_kws_plt",
"(",
"self",
")",
":",
"kws_plt",
"=",
"{",
"}",
"for",
"key_plt",
"in",
"self",
".",
"keys_plt",
":",
"key_val",
"=",
"getattr",
"(",
"self",
",",
"key_plt",
",",
"None",
")",
"if",
"key_val",
"is",
"not",
"None",
":",
"kws_plt... | Get keyword args for GoSubDagPlot from self unless they are None. | [
"Get",
"keyword",
"args",
"for",
"GoSubDagPlot",
"from",
"self",
"unless",
"they",
"are",
"None",
"."
] | python | train | 39.6 |
odrling/peony-twitter | examples/birthday.py | https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/examples/birthday.py#L23-L33 | async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() | [
"async",
"def",
"set_tz",
"(",
"self",
")",
":",
"settings",
"=",
"await",
"self",
".",
"api",
".",
"account",
".",
"settings",
".",
"get",
"(",
")",
"tz",
"=",
"settings",
".",
"time_zone",
".",
"tzinfo_name",
"os",
".",
"environ",
"[",
"'TZ'",
"]",... | set the environment timezone to the timezone
set in your twitter settings | [
"set",
"the",
"environment",
"timezone",
"to",
"the",
"timezone",
"set",
"in",
"your",
"twitter",
"settings"
] | python | valid | 26.272727 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L2225-L2229 | def macro_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#show-macro"
api_path = "/api/v2/macros/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"macro_show",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/macros/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
... | https://developer.zendesk.com/rest_api/docs/core/macros#show-macro | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"macros#show",
"-",
"macro"
] | python | train | 48.2 |
impact27/registrator | registrator/channel.py | https://github.com/impact27/registrator/blob/04c099d83e0466207dc5b2e40d9b03db020d4dad/registrator/channel.py#L146-L175 | def channel_angle(im, chanapproxangle=None, *, isshiftdftedge=False,
truesize=None):
"""Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
isshiftdftedge: boolean, default False
If The image has already been treated:
(edge, dft, fftshift), set to True
truesize: 2 numbers, required if isshiftdftedge is True
The true size of the image
Returns:
--------
angle: number
The channel angle
"""
im = np.asarray(im)
# Compute edge
if not isshiftdftedge:
im = edge(im)
return reg.orientation_angle(im, isshiftdft=isshiftdftedge,
approxangle=chanapproxangle,
truesize=truesize) | [
"def",
"channel_angle",
"(",
"im",
",",
"chanapproxangle",
"=",
"None",
",",
"*",
",",
"isshiftdftedge",
"=",
"False",
",",
"truesize",
"=",
"None",
")",
":",
"im",
"=",
"np",
".",
"asarray",
"(",
"im",
")",
"# Compute edge",
"if",
"not",
"isshiftdftedge... | Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
isshiftdftedge: boolean, default False
If The image has already been treated:
(edge, dft, fftshift), set to True
truesize: 2 numbers, required if isshiftdftedge is True
The true size of the image
Returns:
--------
angle: number
The channel angle | [
"Extract",
"the",
"channel",
"angle",
"from",
"the",
"rfft"
] | python | train | 28.833333 |
gem/oq-engine | openquake/hmtk/plotting/mapping.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L274-L296 | def _plot_simple_fault(self, source, border='k-', border_width=1.0):
"""
Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:
Line properties of border (see matplotlib documentation for detail)
:param float border_width:
Line width of border (see matplotlib documentation for detail)
"""
# Get the trace
trace_lons = np.array([pnt.longitude
for pnt in source.fault_trace.points])
trace_lats = np.array([pnt.latitude
for pnt in source.fault_trace.points])
surface_projection = _fault_polygon_from_mesh(source)
# Plot surface projection first
x, y = self.m(surface_projection[:, 0], surface_projection[:, 1])
self.m.plot(x, y, border, linewidth=border_width)
# Plot fault trace
x, y = self.m(trace_lons, trace_lats)
self.m.plot(x, y, border, linewidth=1.3 * border_width) | [
"def",
"_plot_simple_fault",
"(",
"self",
",",
"source",
",",
"border",
"=",
"'k-'",
",",
"border_width",
"=",
"1.0",
")",
":",
"# Get the trace",
"trace_lons",
"=",
"np",
".",
"array",
"(",
"[",
"pnt",
".",
"longitude",
"for",
"pnt",
"in",
"source",
"."... | Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:
Line properties of border (see matplotlib documentation for detail)
:param float border_width:
Line width of border (see matplotlib documentation for detail) | [
"Plots",
"the",
"simple",
"fault",
"source",
"as",
"a",
"composite",
"of",
"the",
"fault",
"trace",
"and",
"the",
"surface",
"projection",
"of",
"the",
"fault",
".",
":",
"param",
"source",
":",
"Fault",
"source",
"as",
"instance",
"of",
":",
"class",
":... | python | train | 48.869565 |
jaraco/jaraco.logging | jaraco/logging.py | https://github.com/jaraco/jaraco.logging/blob/202d0d3b7c16503f9b8de83b6054f1306ae61930/jaraco/logging.py#L14-L25 | def log_level(level_string):
"""
Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True
"""
if level_string.isdigit():
return int(level_string)
return getattr(logging, level_string.upper()) | [
"def",
"log_level",
"(",
"level_string",
")",
":",
"if",
"level_string",
".",
"isdigit",
"(",
")",
":",
"return",
"int",
"(",
"level_string",
")",
"return",
"getattr",
"(",
"logging",
",",
"level_string",
".",
"upper",
"(",
")",
")"
] | Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True | [
"Return",
"a",
"log",
"level",
"for",
"a",
"string",
">>>",
"log_level",
"(",
"DEBUG",
")",
"==",
"logging",
".",
"DEBUG",
"True",
">>>",
"log_level",
"(",
"30",
")",
"==",
"logging",
".",
"WARNING",
"True"
] | python | train | 22.25 |
PagerDuty/pagerduty-api-python-client | pypd/log.py | https://github.com/PagerDuty/pagerduty-api-python-client/blob/f420b34ca9b29689cc2ecc9adca6dc5d56ae7161/pypd/log.py#L28-L31 | def log(*args, **kwargs):
"""Log things with the global logger."""
level = kwargs.pop('level', logging.INFO)
logger.log(level, *args, **kwargs) | [
"def",
"log",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"level",
"=",
"kwargs",
".",
"pop",
"(",
"'level'",
",",
"logging",
".",
"INFO",
")",
"logger",
".",
"log",
"(",
"level",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Log things with the global logger. | [
"Log",
"things",
"with",
"the",
"global",
"logger",
"."
] | python | train | 38 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.