nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/contrib/crosstalkcaffe/adapter/bvlccaffe/caffeadapter.py | python | CaffeAdapter.adapt_solver | (self) | Adapt Caffe solver into CNTK format
Args:
None
Return:
None | Adapt Caffe solver into CNTK format
Args:
None
Return:
None | [
"Adapt",
"Caffe",
"solver",
"into",
"CNTK",
"format",
"Args",
":",
"None",
"Return",
":",
"None"
] | def adapt_solver(self):
'''
Adapt Caffe solver into CNTK format
Args:
None
Return:
None
'''
self._uni_model.solver = cntkmodel.CntkSolver()
solver = self._uni_model.solver
caffe_solver = self._raw_solver
# Get the casting between iterations and epochs
if 'iters_per_epoch' in self._source_solver.keys():
iter_per_epoch = self._source_solver['iters_per_epoch']
solver.adjust_interval = int(caffe_solver.stepsize / iter_per_epoch + 0.5)
solver.max_epoch = int(caffe_solver.max_iter / iter_per_epoch + 0.5)
solver.learning_rate = caffe_solver.base_lr
solver.decrease_factor = caffe_solver.gamma
solver.momentum = caffe_solver.momentum
solver.weight_decay = caffe_solver.weight_decay
solver.number_to_show_result = caffe_solver.display | [
"def",
"adapt_solver",
"(",
"self",
")",
":",
"self",
".",
"_uni_model",
".",
"solver",
"=",
"cntkmodel",
".",
"CntkSolver",
"(",
")",
"solver",
"=",
"self",
".",
"_uni_model",
".",
"solver",
"caffe_solver",
"=",
"self",
".",
"_raw_solver",
"# Get the casting between iterations and epochs",
"if",
"'iters_per_epoch'",
"in",
"self",
".",
"_source_solver",
".",
"keys",
"(",
")",
":",
"iter_per_epoch",
"=",
"self",
".",
"_source_solver",
"[",
"'iters_per_epoch'",
"]",
"solver",
".",
"adjust_interval",
"=",
"int",
"(",
"caffe_solver",
".",
"stepsize",
"/",
"iter_per_epoch",
"+",
"0.5",
")",
"solver",
".",
"max_epoch",
"=",
"int",
"(",
"caffe_solver",
".",
"max_iter",
"/",
"iter_per_epoch",
"+",
"0.5",
")",
"solver",
".",
"learning_rate",
"=",
"caffe_solver",
".",
"base_lr",
"solver",
".",
"decrease_factor",
"=",
"caffe_solver",
".",
"gamma",
"solver",
".",
"momentum",
"=",
"caffe_solver",
".",
"momentum",
"solver",
".",
"weight_decay",
"=",
"caffe_solver",
".",
"weight_decay",
"solver",
".",
"number_to_show_result",
"=",
"caffe_solver",
".",
"display"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/contrib/crosstalkcaffe/adapter/bvlccaffe/caffeadapter.py#L396-L420 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHandler.py | python | IdleConf.GetCoreKeys | (self, keySetName=None) | return keyBindings | returns the requested set of core keybindings, with fallbacks if
required.
Keybindings loaded from the config file(s) are loaded _over_ these
defaults, so if there is a problem getting any core binding there will
be an 'ultimate last resort fallback' to the CUA-ish bindings
defined here. | returns the requested set of core keybindings, with fallbacks if
required.
Keybindings loaded from the config file(s) are loaded _over_ these
defaults, so if there is a problem getting any core binding there will
be an 'ultimate last resort fallback' to the CUA-ish bindings
defined here. | [
"returns",
"the",
"requested",
"set",
"of",
"core",
"keybindings",
"with",
"fallbacks",
"if",
"required",
".",
"Keybindings",
"loaded",
"from",
"the",
"config",
"file",
"(",
"s",
")",
"are",
"loaded",
"_over_",
"these",
"defaults",
"so",
"if",
"there",
"is",
"a",
"problem",
"getting",
"any",
"core",
"binding",
"there",
"will",
"be",
"an",
"ultimate",
"last",
"resort",
"fallback",
"to",
"the",
"CUA",
"-",
"ish",
"bindings",
"defined",
"here",
"."
] | def GetCoreKeys(self, keySetName=None):
"""
returns the requested set of core keybindings, with fallbacks if
required.
Keybindings loaded from the config file(s) are loaded _over_ these
defaults, so if there is a problem getting any core binding there will
be an 'ultimate last resort fallback' to the CUA-ish bindings
defined here.
"""
keyBindings={
'<<copy>>': ['<Control-c>', '<Control-C>'],
'<<cut>>': ['<Control-x>', '<Control-X>'],
'<<paste>>': ['<Control-v>', '<Control-V>'],
'<<beginning-of-line>>': ['<Control-a>', '<Home>'],
'<<center-insert>>': ['<Control-l>'],
'<<close-all-windows>>': ['<Control-q>'],
'<<close-window>>': ['<Alt-F4>'],
'<<do-nothing>>': ['<Control-x>'],
'<<end-of-file>>': ['<Control-d>'],
'<<python-docs>>': ['<F1>'],
'<<python-context-help>>': ['<Shift-F1>'],
'<<history-next>>': ['<Alt-n>'],
'<<history-previous>>': ['<Alt-p>'],
'<<interrupt-execution>>': ['<Control-c>'],
'<<view-restart>>': ['<F6>'],
'<<restart-shell>>': ['<Control-F6>'],
'<<open-class-browser>>': ['<Alt-c>'],
'<<open-module>>': ['<Alt-m>'],
'<<open-new-window>>': ['<Control-n>'],
'<<open-window-from-file>>': ['<Control-o>'],
'<<plain-newline-and-indent>>': ['<Control-j>'],
'<<print-window>>': ['<Control-p>'],
'<<redo>>': ['<Control-y>'],
'<<remove-selection>>': ['<Escape>'],
'<<save-copy-of-window-as-file>>': ['<Alt-Shift-S>'],
'<<save-window-as-file>>': ['<Alt-s>'],
'<<save-window>>': ['<Control-s>'],
'<<select-all>>': ['<Alt-a>'],
'<<toggle-auto-coloring>>': ['<Control-slash>'],
'<<undo>>': ['<Control-z>'],
'<<find-again>>': ['<Control-g>', '<F3>'],
'<<find-in-files>>': ['<Alt-F3>'],
'<<find-selection>>': ['<Control-F3>'],
'<<find>>': ['<Control-f>'],
'<<replace>>': ['<Control-h>'],
'<<goto-line>>': ['<Alt-g>'],
'<<smart-backspace>>': ['<Key-BackSpace>'],
'<<newline-and-indent>>': ['<Key-Return>', '<Key-KP_Enter>'],
'<<smart-indent>>': ['<Key-Tab>'],
'<<indent-region>>': ['<Control-Key-bracketright>'],
'<<dedent-region>>': ['<Control-Key-bracketleft>'],
'<<comment-region>>': ['<Alt-Key-3>'],
'<<uncomment-region>>': ['<Alt-Key-4>'],
'<<tabify-region>>': ['<Alt-Key-5>'],
'<<untabify-region>>': ['<Alt-Key-6>'],
'<<toggle-tabs>>': ['<Alt-Key-t>'],
'<<change-indentwidth>>': ['<Alt-Key-u>'],
'<<del-word-left>>': ['<Control-Key-BackSpace>'],
'<<del-word-right>>': ['<Control-Key-Delete>']
}
if keySetName:
for event in keyBindings.keys():
binding=self.GetKeyBinding(keySetName,event)
if binding:
keyBindings[event]=binding
else: #we are going to return a default, print warning
warning=('\n Warning: configHandler.py - IdleConf.GetCoreKeys'
' -\n problem retrieving key binding for event %r'
'\n from key set %r.\n'
' returning default value: %r\n' %
(event, keySetName, keyBindings[event]))
try:
sys.stderr.write(warning)
except IOError:
pass
return keyBindings | [
"def",
"GetCoreKeys",
"(",
"self",
",",
"keySetName",
"=",
"None",
")",
":",
"keyBindings",
"=",
"{",
"'<<copy>>'",
":",
"[",
"'<Control-c>'",
",",
"'<Control-C>'",
"]",
",",
"'<<cut>>'",
":",
"[",
"'<Control-x>'",
",",
"'<Control-X>'",
"]",
",",
"'<<paste>>'",
":",
"[",
"'<Control-v>'",
",",
"'<Control-V>'",
"]",
",",
"'<<beginning-of-line>>'",
":",
"[",
"'<Control-a>'",
",",
"'<Home>'",
"]",
",",
"'<<center-insert>>'",
":",
"[",
"'<Control-l>'",
"]",
",",
"'<<close-all-windows>>'",
":",
"[",
"'<Control-q>'",
"]",
",",
"'<<close-window>>'",
":",
"[",
"'<Alt-F4>'",
"]",
",",
"'<<do-nothing>>'",
":",
"[",
"'<Control-x>'",
"]",
",",
"'<<end-of-file>>'",
":",
"[",
"'<Control-d>'",
"]",
",",
"'<<python-docs>>'",
":",
"[",
"'<F1>'",
"]",
",",
"'<<python-context-help>>'",
":",
"[",
"'<Shift-F1>'",
"]",
",",
"'<<history-next>>'",
":",
"[",
"'<Alt-n>'",
"]",
",",
"'<<history-previous>>'",
":",
"[",
"'<Alt-p>'",
"]",
",",
"'<<interrupt-execution>>'",
":",
"[",
"'<Control-c>'",
"]",
",",
"'<<view-restart>>'",
":",
"[",
"'<F6>'",
"]",
",",
"'<<restart-shell>>'",
":",
"[",
"'<Control-F6>'",
"]",
",",
"'<<open-class-browser>>'",
":",
"[",
"'<Alt-c>'",
"]",
",",
"'<<open-module>>'",
":",
"[",
"'<Alt-m>'",
"]",
",",
"'<<open-new-window>>'",
":",
"[",
"'<Control-n>'",
"]",
",",
"'<<open-window-from-file>>'",
":",
"[",
"'<Control-o>'",
"]",
",",
"'<<plain-newline-and-indent>>'",
":",
"[",
"'<Control-j>'",
"]",
",",
"'<<print-window>>'",
":",
"[",
"'<Control-p>'",
"]",
",",
"'<<redo>>'",
":",
"[",
"'<Control-y>'",
"]",
",",
"'<<remove-selection>>'",
":",
"[",
"'<Escape>'",
"]",
",",
"'<<save-copy-of-window-as-file>>'",
":",
"[",
"'<Alt-Shift-S>'",
"]",
",",
"'<<save-window-as-file>>'",
":",
"[",
"'<Alt-s>'",
"]",
",",
"'<<save-window>>'",
":",
"[",
"'<Control-s>'",
"]",
",",
"'<<select-all>>'",
":",
"[",
"'<Alt-a>'",
"]",
",",
"'<<toggle-auto-coloring>>'",
":",
"[",
"'<Control-slash>'",
"]",
",",
"'<<undo>>'",
":",
"[",
"'<Control-z>'",
"]",
",",
"'<<find-again>>'",
":",
"[",
"'<Control-g>'",
",",
"'<F3>'",
"]",
",",
"'<<find-in-files>>'",
":",
"[",
"'<Alt-F3>'",
"]",
",",
"'<<find-selection>>'",
":",
"[",
"'<Control-F3>'",
"]",
",",
"'<<find>>'",
":",
"[",
"'<Control-f>'",
"]",
",",
"'<<replace>>'",
":",
"[",
"'<Control-h>'",
"]",
",",
"'<<goto-line>>'",
":",
"[",
"'<Alt-g>'",
"]",
",",
"'<<smart-backspace>>'",
":",
"[",
"'<Key-BackSpace>'",
"]",
",",
"'<<newline-and-indent>>'",
":",
"[",
"'<Key-Return>'",
",",
"'<Key-KP_Enter>'",
"]",
",",
"'<<smart-indent>>'",
":",
"[",
"'<Key-Tab>'",
"]",
",",
"'<<indent-region>>'",
":",
"[",
"'<Control-Key-bracketright>'",
"]",
",",
"'<<dedent-region>>'",
":",
"[",
"'<Control-Key-bracketleft>'",
"]",
",",
"'<<comment-region>>'",
":",
"[",
"'<Alt-Key-3>'",
"]",
",",
"'<<uncomment-region>>'",
":",
"[",
"'<Alt-Key-4>'",
"]",
",",
"'<<tabify-region>>'",
":",
"[",
"'<Alt-Key-5>'",
"]",
",",
"'<<untabify-region>>'",
":",
"[",
"'<Alt-Key-6>'",
"]",
",",
"'<<toggle-tabs>>'",
":",
"[",
"'<Alt-Key-t>'",
"]",
",",
"'<<change-indentwidth>>'",
":",
"[",
"'<Alt-Key-u>'",
"]",
",",
"'<<del-word-left>>'",
":",
"[",
"'<Control-Key-BackSpace>'",
"]",
",",
"'<<del-word-right>>'",
":",
"[",
"'<Control-Key-Delete>'",
"]",
"}",
"if",
"keySetName",
":",
"for",
"event",
"in",
"keyBindings",
".",
"keys",
"(",
")",
":",
"binding",
"=",
"self",
".",
"GetKeyBinding",
"(",
"keySetName",
",",
"event",
")",
"if",
"binding",
":",
"keyBindings",
"[",
"event",
"]",
"=",
"binding",
"else",
":",
"#we are going to return a default, print warning",
"warning",
"=",
"(",
"'\\n Warning: configHandler.py - IdleConf.GetCoreKeys'",
"' -\\n problem retrieving key binding for event %r'",
"'\\n from key set %r.\\n'",
"' returning default value: %r\\n'",
"%",
"(",
"event",
",",
"keySetName",
",",
"keyBindings",
"[",
"event",
"]",
")",
")",
"try",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"warning",
")",
"except",
"IOError",
":",
"pass",
"return",
"keyBindings"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHandler.py#L566-L641 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/python2/httplib2/__init__.py | python | Http._auth_from_challenge | (self, host, request_uri, headers, response, content) | A generator that creates Authorization objects
that can be applied to requests. | A generator that creates Authorization objects
that can be applied to requests. | [
"A",
"generator",
"that",
"creates",
"Authorization",
"objects",
"that",
"can",
"be",
"applied",
"to",
"requests",
"."
] | def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, 'www-authenticate')
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if challenges.has_key(scheme):
yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self) | [
"def",
"_auth_from_challenge",
"(",
"self",
",",
"host",
",",
"request_uri",
",",
"headers",
",",
"response",
",",
"content",
")",
":",
"challenges",
"=",
"_parse_www_authenticate",
"(",
"response",
",",
"'www-authenticate'",
")",
"for",
"cred",
"in",
"self",
".",
"credentials",
".",
"iter",
"(",
"host",
")",
":",
"for",
"scheme",
"in",
"AUTH_SCHEME_ORDER",
":",
"if",
"challenges",
".",
"has_key",
"(",
"scheme",
")",
":",
"yield",
"AUTH_SCHEME_CLASSES",
"[",
"scheme",
"]",
"(",
"cred",
",",
"host",
",",
"request_uri",
",",
"headers",
",",
"response",
",",
"content",
",",
"self",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/python2/httplib2/__init__.py#L1222-L1230 | ||
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | python_packaging/src/gmxapi/version.py | python | api_is_at_least | (major_version, minor_version=0, patch_version=0) | Allow client to check whether installed module supports the requested API level.
Arguments:
major_version (int): gmxapi major version number.
minor_version (int): optional gmxapi minor version number (default: 0).
patch_version (int): optional gmxapi patch level number (default: 0).
Returns:
True if installed gmx package is greater than or equal to the input level
Note that if gmxapi.version.release is False, the package is not guaranteed to correctly or
fully support the reported API level. | Allow client to check whether installed module supports the requested API level. | [
"Allow",
"client",
"to",
"check",
"whether",
"installed",
"module",
"supports",
"the",
"requested",
"API",
"level",
"."
] | def api_is_at_least(major_version, minor_version=0, patch_version=0):
"""Allow client to check whether installed module supports the requested API level.
Arguments:
major_version (int): gmxapi major version number.
minor_version (int): optional gmxapi minor version number (default: 0).
patch_version (int): optional gmxapi patch level number (default: 0).
Returns:
True if installed gmx package is greater than or equal to the input level
Note that if gmxapi.version.release is False, the package is not guaranteed to correctly or
fully support the reported API level.
"""
if not isinstance(major_version, int) or not isinstance(minor_version, int) or not isinstance(
patch_version,
int):
raise TypeError('Version levels must be provided as integers.')
if _major > major_version:
return True
elif _major == major_version and _minor >= minor_version:
return True
elif _major == major_version and _minor == minor_version and _micro >= patch_version:
return True
else:
return False | [
"def",
"api_is_at_least",
"(",
"major_version",
",",
"minor_version",
"=",
"0",
",",
"patch_version",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"major_version",
",",
"int",
")",
"or",
"not",
"isinstance",
"(",
"minor_version",
",",
"int",
")",
"or",
"not",
"isinstance",
"(",
"patch_version",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'Version levels must be provided as integers.'",
")",
"if",
"_major",
">",
"major_version",
":",
"return",
"True",
"elif",
"_major",
"==",
"major_version",
"and",
"_minor",
">=",
"minor_version",
":",
"return",
"True",
"elif",
"_major",
"==",
"major_version",
"and",
"_minor",
"==",
"minor_version",
"and",
"_micro",
">=",
"patch_version",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/version.py#L132-L157 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | TextDropTarget._setCallbackInfo | (*args, **kwargs) | return _misc_.TextDropTarget__setCallbackInfo(*args, **kwargs) | _setCallbackInfo(self, PyObject self, PyObject _class) | _setCallbackInfo(self, PyObject self, PyObject _class) | [
"_setCallbackInfo",
"(",
"self",
"PyObject",
"self",
"PyObject",
"_class",
")"
] | def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _misc_.TextDropTarget__setCallbackInfo(*args, **kwargs) | [
"def",
"_setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"TextDropTarget__setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L5637-L5639 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/protorpc/ez_setup.py | python | download_setuptools | (
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
) | return os.path.realpath(saveto) | Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt. | Download setuptools from a specified location and return its filename | [
"Download",
"setuptools",
"from",
"a",
"specified",
"location",
"and",
"return",
"its",
"filename"
] | def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto) | [
"def",
"download_setuptools",
"(",
"version",
"=",
"DEFAULT_VERSION",
",",
"download_base",
"=",
"DEFAULT_URL",
",",
"to_dir",
"=",
"os",
".",
"curdir",
",",
"delay",
"=",
"15",
")",
":",
"import",
"urllib2",
",",
"shutil",
"egg_name",
"=",
"\"setuptools-%s-py%s.egg\"",
"%",
"(",
"version",
",",
"sys",
".",
"version",
"[",
":",
"3",
"]",
")",
"url",
"=",
"download_base",
"+",
"egg_name",
"saveto",
"=",
"os",
".",
"path",
".",
"join",
"(",
"to_dir",
",",
"egg_name",
")",
"src",
"=",
"dst",
"=",
"None",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"saveto",
")",
":",
"# Avoid repeated downloads",
"try",
":",
"from",
"distutils",
"import",
"log",
"if",
"delay",
":",
"log",
".",
"warn",
"(",
"\"\"\"\n---------------------------------------------------------------------------\nThis script requires setuptools version %s to run (even to display\nhelp). I will attempt to download it for you (from\n%s), but\nyou may need to enable firewall access for this script first.\nI will start the download in %d seconds.\n\n(Note: if this machine does not have network access, please obtain the file\n\n %s\n\nand place it in this directory before rerunning this script.)\n---------------------------------------------------------------------------\"\"\"",
",",
"version",
",",
"download_base",
",",
"delay",
",",
"url",
")",
"from",
"time",
"import",
"sleep",
"sleep",
"(",
"delay",
")",
"log",
".",
"warn",
"(",
"\"Downloading %s\"",
",",
"url",
")",
"src",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"# Read/write all in one block, so we don't create a corrupt file",
"# if the download is interrupted.",
"data",
"=",
"_validate_md5",
"(",
"egg_name",
",",
"src",
".",
"read",
"(",
")",
")",
"dst",
"=",
"open",
"(",
"saveto",
",",
"\"wb\"",
")",
"dst",
".",
"write",
"(",
"data",
")",
"finally",
":",
"if",
"src",
":",
"src",
".",
"close",
"(",
")",
"if",
"dst",
":",
"dst",
".",
"close",
"(",
")",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"saveto",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/ez_setup.py#L94-L139 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/linalg/_sketches.py | python | cwt_matrix | (n_rows, n_columns, seed=None) | return S | r""""
Generate a matrix S for the Clarkson-Woodruff sketch.
Given the desired size of matrix, the method returns a matrix S of size
(n_rows, n_columns) where each column has all the entries set to 0 less one
position which has been randomly set to +1 or -1 with equal probability.
Parameters
----------
n_rows: int
Number of rows of S
n_columns: int
Number of columns of S
seed : None or int or `numpy.random.RandomState` instance, optional
This parameter defines the ``RandomState`` object to use for drawing
random variates.
If None (or ``np.random``), the global ``np.random`` state is used.
If integer, it is used to seed the local ``RandomState`` instance.
Default is None.
Returns
-------
S : (n_rows, n_columns) array_like
Notes
-----
Given a matrix A, with probability at least 9/10,
.. math:: ||SA|| == (1 \pm \epsilon)||A||
Where epsilon is related to the size of S | r""""
Generate a matrix S for the Clarkson-Woodruff sketch. | [
"r",
"Generate",
"a",
"matrix",
"S",
"for",
"the",
"Clarkson",
"-",
"Woodruff",
"sketch",
"."
] | def cwt_matrix(n_rows, n_columns, seed=None):
r""""
Generate a matrix S for the Clarkson-Woodruff sketch.
Given the desired size of matrix, the method returns a matrix S of size
(n_rows, n_columns) where each column has all the entries set to 0 less one
position which has been randomly set to +1 or -1 with equal probability.
Parameters
----------
n_rows: int
Number of rows of S
n_columns: int
Number of columns of S
seed : None or int or `numpy.random.RandomState` instance, optional
This parameter defines the ``RandomState`` object to use for drawing
random variates.
If None (or ``np.random``), the global ``np.random`` state is used.
If integer, it is used to seed the local ``RandomState`` instance.
Default is None.
Returns
-------
S : (n_rows, n_columns) array_like
Notes
-----
Given a matrix A, with probability at least 9/10,
.. math:: ||SA|| == (1 \pm \epsilon)||A||
Where epsilon is related to the size of S
"""
S = np.zeros((n_rows, n_columns))
nz_positions = np.random.randint(0, n_rows, n_columns)
rng = check_random_state(seed)
values = rng.choice([1, -1], n_columns)
for i in range(n_columns):
S[nz_positions[i]][i] = values[i]
return S | [
"def",
"cwt_matrix",
"(",
"n_rows",
",",
"n_columns",
",",
"seed",
"=",
"None",
")",
":",
"S",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_rows",
",",
"n_columns",
")",
")",
"nz_positions",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"n_rows",
",",
"n_columns",
")",
"rng",
"=",
"check_random_state",
"(",
"seed",
")",
"values",
"=",
"rng",
".",
"choice",
"(",
"[",
"1",
",",
"-",
"1",
"]",
",",
"n_columns",
")",
"for",
"i",
"in",
"range",
"(",
"n_columns",
")",
":",
"S",
"[",
"nz_positions",
"[",
"i",
"]",
"]",
"[",
"i",
"]",
"=",
"values",
"[",
"i",
"]",
"return",
"S"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/linalg/_sketches.py#L15-L53 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/compiler.py | python | CodeGenerator.newline | (self, node=None, extra=0) | Add one or more newlines before the next write. | Add one or more newlines before the next write. | [
"Add",
"one",
"or",
"more",
"newlines",
"before",
"the",
"next",
"write",
"."
] | def newline(self, node=None, extra=0):
"""Add one or more newlines before the next write."""
self._new_lines = max(self._new_lines, 1 + extra)
if node is not None and node.lineno != self._last_line:
self._write_debug_info = node.lineno
self._last_line = node.lineno | [
"def",
"newline",
"(",
"self",
",",
"node",
"=",
"None",
",",
"extra",
"=",
"0",
")",
":",
"self",
".",
"_new_lines",
"=",
"max",
"(",
"self",
".",
"_new_lines",
",",
"1",
"+",
"extra",
")",
"if",
"node",
"is",
"not",
"None",
"and",
"node",
".",
"lineno",
"!=",
"self",
".",
"_last_line",
":",
"self",
".",
"_write_debug_info",
"=",
"node",
".",
"lineno",
"self",
".",
"_last_line",
"=",
"node",
".",
"lineno"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/compiler.py#L516-L521 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | schemaCleanupTypes | () | Cleanup the default XML Schemas type library | Cleanup the default XML Schemas type library | [
"Cleanup",
"the",
"default",
"XML",
"Schemas",
"type",
"library"
] | def schemaCleanupTypes():
"""Cleanup the default XML Schemas type library """
libxml2mod.xmlSchemaCleanupTypes() | [
"def",
"schemaCleanupTypes",
"(",
")",
":",
"libxml2mod",
".",
"xmlSchemaCleanupTypes",
"(",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1226-L1228 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/httpsession.py | python | ProxyConfiguration.proxy_url_for | (self, url) | return proxy | Retrirves the corresponding proxy url for a given url. | Retrirves the corresponding proxy url for a given url. | [
"Retrirves",
"the",
"corresponding",
"proxy",
"url",
"for",
"a",
"given",
"url",
"."
] | def proxy_url_for(self, url):
"""Retrirves the corresponding proxy url for a given url. """
parsed_url = urlparse(url)
proxy = self._proxies.get(parsed_url.scheme)
if proxy:
proxy = self._fix_proxy_url(proxy)
return proxy | [
"def",
"proxy_url_for",
"(",
"self",
",",
"url",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"proxy",
"=",
"self",
".",
"_proxies",
".",
"get",
"(",
"parsed_url",
".",
"scheme",
")",
"if",
"proxy",
":",
"proxy",
"=",
"self",
".",
"_fix_proxy_url",
"(",
"proxy",
")",
"return",
"proxy"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/httpsession.py#L99-L105 | |
0ad/0ad | f58db82e0e925016d83f4e3fa7ca599e3866e2af | source/tools/i18n/extractors/extractors.py | python | Extractor.extractFromFile | (self, filepath) | Extracts messages from a specific file.
:return: An iterator over ``(message, plural, context, breadcrumb, position, comments)`` tuples.
:rtype: ``iterator`` | Extracts messages from a specific file. | [
"Extracts",
"messages",
"from",
"a",
"specific",
"file",
"."
] | def extractFromFile(self, filepath):
""" Extracts messages from a specific file.
:return: An iterator over ``(message, plural, context, breadcrumb, position, comments)`` tuples.
:rtype: ``iterator``
"""
pass | [
"def",
"extractFromFile",
"(",
"self",
",",
"filepath",
")",
":",
"pass"
] | https://github.com/0ad/0ad/blob/f58db82e0e925016d83f4e3fa7ca599e3866e2af/source/tools/i18n/extractors/extractors.py#L94-L100 | ||
v8mips/v8mips | f0c9cc0bbfd461c7f516799d9a58e9a7395f737e | tools/grokdump.py | python | InspectionPadawan.FindObjectOrSmi | (self, tagged_address) | When used as a mixin in place of V8Heap. | When used as a mixin in place of V8Heap. | [
"When",
"used",
"as",
"a",
"mixin",
"in",
"place",
"of",
"V8Heap",
"."
] | def FindObjectOrSmi(self, tagged_address):
"""When used as a mixin in place of V8Heap."""
found_obj = self.SenseObject(tagged_address)
if found_obj: return found_obj
if (tagged_address & 1) == 0:
return "Smi(%d)" % (tagged_address / 2)
else:
return "Unknown(%s)" % self.reader.FormatIntPtr(tagged_address) | [
"def",
"FindObjectOrSmi",
"(",
"self",
",",
"tagged_address",
")",
":",
"found_obj",
"=",
"self",
".",
"SenseObject",
"(",
"tagged_address",
")",
"if",
"found_obj",
":",
"return",
"found_obj",
"if",
"(",
"tagged_address",
"&",
"1",
")",
"==",
"0",
":",
"return",
"\"Smi(%d)\"",
"%",
"(",
"tagged_address",
"/",
"2",
")",
"else",
":",
"return",
"\"Unknown(%s)\"",
"%",
"self",
".",
"reader",
".",
"FormatIntPtr",
"(",
"tagged_address",
")"
] | https://github.com/v8mips/v8mips/blob/f0c9cc0bbfd461c7f516799d9a58e9a7395f737e/tools/grokdump.py#L1731-L1738 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | _ProxyFile.__enter__ | (self) | return self | Context management protocol support. | Context management protocol support. | [
"Context",
"management",
"protocol",
"support",
"."
] | def __enter__(self):
"""Context management protocol support."""
return self | [
"def",
"__enter__",
"(",
"self",
")",
":",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L1994-L1996 | |
xapian/xapian | 2b803ea5e3904a6e0cd7d111b2ff38a704c21041 | xapian-bindings/python3/doxy2swig.py | python | Doxy2SWIG.clean_pieces | (self, pieces) | return ret | Cleans the list of strings given as `pieces`. It replaces
multiple newlines by a maximum of 2 and returns a new list.
It also wraps the paragraphs nicely. | Cleans the list of strings given as `pieces`. It replaces
multiple newlines by a maximum of 2 and returns a new list.
It also wraps the paragraphs nicely. | [
"Cleans",
"the",
"list",
"of",
"strings",
"given",
"as",
"pieces",
".",
"It",
"replaces",
"multiple",
"newlines",
"by",
"a",
"maximum",
"of",
"2",
"and",
"returns",
"a",
"new",
"list",
".",
"It",
"also",
"wraps",
"the",
"paragraphs",
"nicely",
"."
] | def clean_pieces(self, pieces):
"""Cleans the list of strings given as `pieces`. It replaces
multiple newlines by a maximum of 2 and returns a new list.
It also wraps the paragraphs nicely.
"""
ret = []
count = 0
for i in pieces:
if i == '\n':
count = count + 1
else:
if i == '";':
if count:
ret.append('\n')
elif count > 2:
ret.append('\n\n')
elif count:
ret.append('\n'*count)
count = 0
ret.append(i)
_data = "".join(ret)
ret = []
for i in _data.split('\n\n'):
if i == 'Parameters:':
ret.extend(['Parameters:\n-----------', '\n\n'])
elif i.find('// File:') > -1: # leave comments alone.
ret.extend([i, '\n'])
else:
_tmp = textwrap.fill(i.strip(), break_long_words=False)
_tmp = self.lead_spc.sub(r'\1"\2', _tmp)
ret.extend([_tmp, '\n\n'])
return ret | [
"def",
"clean_pieces",
"(",
"self",
",",
"pieces",
")",
":",
"ret",
"=",
"[",
"]",
"count",
"=",
"0",
"for",
"i",
"in",
"pieces",
":",
"if",
"i",
"==",
"'\\n'",
":",
"count",
"=",
"count",
"+",
"1",
"else",
":",
"if",
"i",
"==",
"'\";'",
":",
"if",
"count",
":",
"ret",
".",
"append",
"(",
"'\\n'",
")",
"elif",
"count",
">",
"2",
":",
"ret",
".",
"append",
"(",
"'\\n\\n'",
")",
"elif",
"count",
":",
"ret",
".",
"append",
"(",
"'\\n'",
"*",
"count",
")",
"count",
"=",
"0",
"ret",
".",
"append",
"(",
"i",
")",
"_data",
"=",
"\"\"",
".",
"join",
"(",
"ret",
")",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"_data",
".",
"split",
"(",
"'\\n\\n'",
")",
":",
"if",
"i",
"==",
"'Parameters:'",
":",
"ret",
".",
"extend",
"(",
"[",
"'Parameters:\\n-----------'",
",",
"'\\n\\n'",
"]",
")",
"elif",
"i",
".",
"find",
"(",
"'// File:'",
")",
">",
"-",
"1",
":",
"# leave comments alone.",
"ret",
".",
"extend",
"(",
"[",
"i",
",",
"'\\n'",
"]",
")",
"else",
":",
"_tmp",
"=",
"textwrap",
".",
"fill",
"(",
"i",
".",
"strip",
"(",
")",
",",
"break_long_words",
"=",
"False",
")",
"_tmp",
"=",
"self",
".",
"lead_spc",
".",
"sub",
"(",
"r'\\1\"\\2'",
",",
"_tmp",
")",
"ret",
".",
"extend",
"(",
"[",
"_tmp",
",",
"'\\n\\n'",
"]",
")",
"return",
"ret"
] | https://github.com/xapian/xapian/blob/2b803ea5e3904a6e0cd7d111b2ff38a704c21041/xapian-bindings/python3/doxy2swig.py#L338-L371 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/web.py | python | RequestHandler.check_xsrf_cookie | (self) | Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
reject the form submission as a potential forgery.
The ``_xsrf`` value may be set as either a form field named ``_xsrf``
or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
(the latter is accepted for compatibility with Django).
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
.. versionchanged:: 3.2.2
Added support for cookie version 2. Both versions 1 and 2 are
supported. | Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument. | [
"Verifies",
"that",
"the",
"_xsrf",
"cookie",
"matches",
"the",
"_xsrf",
"argument",
"."
] | def check_xsrf_cookie(self) -> None:
"""Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
reject the form submission as a potential forgery.
The ``_xsrf`` value may be set as either a form field named ``_xsrf``
or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
(the latter is accepted for compatibility with Django).
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
.. versionchanged:: 3.2.2
Added support for cookie version 2. Both versions 1 and 2 are
supported.
"""
# Prior to release 1.1.1, this check was ignored if the HTTP header
# ``X-Requested-With: XMLHTTPRequest`` was present. This exception
# has been shown to be insecure and has been removed. For more
# information please see
# http://www.djangoproject.com/weblog/2011/feb/08/security/
# http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
token = (
self.get_argument("_xsrf", None)
or self.request.headers.get("X-Xsrftoken")
or self.request.headers.get("X-Csrftoken")
)
if not token:
raise HTTPError(403, "'_xsrf' argument missing from POST")
_, token, _ = self._decode_xsrf_token(token)
_, expected_token, _ = self._get_raw_xsrf_token()
if not token:
raise HTTPError(403, "'_xsrf' argument has invalid format")
if not hmac.compare_digest(utf8(token), utf8(expected_token)):
raise HTTPError(403, "XSRF cookie does not match POST argument") | [
"def",
"check_xsrf_cookie",
"(",
"self",
")",
"->",
"None",
":",
"# Prior to release 1.1.1, this check was ignored if the HTTP header",
"# ``X-Requested-With: XMLHTTPRequest`` was present. This exception",
"# has been shown to be insecure and has been removed. For more",
"# information please see",
"# http://www.djangoproject.com/weblog/2011/feb/08/security/",
"# http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails",
"token",
"=",
"(",
"self",
".",
"get_argument",
"(",
"\"_xsrf\"",
",",
"None",
")",
"or",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"\"X-Xsrftoken\"",
")",
"or",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"\"X-Csrftoken\"",
")",
")",
"if",
"not",
"token",
":",
"raise",
"HTTPError",
"(",
"403",
",",
"\"'_xsrf' argument missing from POST\"",
")",
"_",
",",
"token",
",",
"_",
"=",
"self",
".",
"_decode_xsrf_token",
"(",
"token",
")",
"_",
",",
"expected_token",
",",
"_",
"=",
"self",
".",
"_get_raw_xsrf_token",
"(",
")",
"if",
"not",
"token",
":",
"raise",
"HTTPError",
"(",
"403",
",",
"\"'_xsrf' argument has invalid format\"",
")",
"if",
"not",
"hmac",
".",
"compare_digest",
"(",
"utf8",
"(",
"token",
")",
",",
"utf8",
"(",
"expected_token",
")",
")",
":",
"raise",
"HTTPError",
"(",
"403",
",",
"\"XSRF cookie does not match POST argument\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/web.py#L1489-L1525 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py | python | init | () | Explicitly initializes the Python Imaging Library. This function
loads all available file format drivers. | Explicitly initializes the Python Imaging Library. This function
loads all available file format drivers. | [
"Explicitly",
"initializes",
"the",
"Python",
"Imaging",
"Library",
".",
"This",
"function",
"loads",
"all",
"available",
"file",
"format",
"drivers",
"."
] | def init():
"""
Explicitly initializes the Python Imaging Library. This function
loads all available file format drivers.
"""
global _initialized
if _initialized >= 2:
return 0
for plugin in _plugins:
try:
logger.debug("Importing %s", plugin)
__import__("PIL.%s" % plugin, globals(), locals(), [])
except ImportError as e:
logger.debug("Image: failed to import %s: %s", plugin, e)
if OPEN or SAVE:
_initialized = 2
return 1 | [
"def",
"init",
"(",
")",
":",
"global",
"_initialized",
"if",
"_initialized",
">=",
"2",
":",
"return",
"0",
"for",
"plugin",
"in",
"_plugins",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"\"Importing %s\"",
",",
"plugin",
")",
"__import__",
"(",
"\"PIL.%s\"",
"%",
"plugin",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
",",
"[",
"]",
")",
"except",
"ImportError",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"\"Image: failed to import %s: %s\"",
",",
"plugin",
",",
"e",
")",
"if",
"OPEN",
"or",
"SAVE",
":",
"_initialized",
"=",
"2",
"return",
"1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py#L392-L411 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Image.GetOption | (*args, **kwargs) | return _core_.Image_GetOption(*args, **kwargs) | GetOption(self, String name) -> String
Gets the value of an image handler option. | GetOption(self, String name) -> String | [
"GetOption",
"(",
"self",
"String",
"name",
")",
"-",
">",
"String"
] | def GetOption(*args, **kwargs):
"""
GetOption(self, String name) -> String
Gets the value of an image handler option.
"""
return _core_.Image_GetOption(*args, **kwargs) | [
"def",
"GetOption",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_GetOption",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L3580-L3586 | |
KhronosGroup/SPIRV-Tools | 940127a77d3ad795a4a1422fbeaad50c9f19f2ea | utils/generate_vim_syntax.py | python | EmitAsStatement | (name) | Emits the given name as a statement token | Emits the given name as a statement token | [
"Emits",
"the",
"given",
"name",
"as",
"a",
"statement",
"token"
] | def EmitAsStatement(name):
"""Emits the given name as a statement token"""
print('syn keyword spvasmStatement', name) | [
"def",
"EmitAsStatement",
"(",
"name",
")",
":",
"print",
"(",
"'syn keyword spvasmStatement'",
",",
"name",
")"
] | https://github.com/KhronosGroup/SPIRV-Tools/blob/940127a77d3ad795a4a1422fbeaad50c9f19f2ea/utils/generate_vim_syntax.py#L124-L126 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Text.mark_names | (self) | return self.tk.splitlist(self.tk.call(
self._w, 'mark', 'names')) | Return all mark names. | Return all mark names. | [
"Return",
"all",
"mark",
"names",
"."
] | def mark_names(self):
"""Return all mark names."""
return self.tk.splitlist(self.tk.call(
self._w, 'mark', 'names')) | [
"def",
"mark_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"splitlist",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'mark'",
",",
"'names'",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3054-L3057 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/core.py | python | expand_paths_if_needed | (paths, mode, num, fs, name_function) | return expanded_paths | Expand paths if they have a ``*`` in them.
:param paths: list of paths
mode: str
Mode in which to open files.
num: int
If opening in writing mode, number of files we expect to create.
fs: filesystem object
name_function: callable
If opening in writing mode, this callable is used to generate path
names. Names are generated for each partition by
``urlpath.replace('*', name_function(partition_index))``.
:return: list of paths | Expand paths if they have a ``*`` in them. | [
"Expand",
"paths",
"if",
"they",
"have",
"a",
"*",
"in",
"them",
"."
] | def expand_paths_if_needed(paths, mode, num, fs, name_function):
"""Expand paths if they have a ``*`` in them.
:param paths: list of paths
mode: str
Mode in which to open files.
num: int
If opening in writing mode, number of files we expect to create.
fs: filesystem object
name_function: callable
If opening in writing mode, this callable is used to generate path
names. Names are generated for each partition by
``urlpath.replace('*', name_function(partition_index))``.
:return: list of paths
"""
expanded_paths = []
paths = list(paths)
if "w" in mode and sum([1 for p in paths if "*" in p]) > 1:
raise ValueError("When writing data, only one filename mask can be specified.")
elif "w" in mode:
num = max(num, len(paths))
for curr_path in paths:
if "*" in curr_path:
if "w" in mode:
# expand using name_function
expanded_paths.extend(_expand_paths(curr_path, name_function, num))
else:
# expand using glob
expanded_paths.extend(fs.glob(curr_path))
else:
expanded_paths.append(curr_path)
# if we generated more paths that asked for, trim the list
if "w" in mode and len(expanded_paths) > num:
expanded_paths = expanded_paths[:num]
return expanded_paths | [
"def",
"expand_paths_if_needed",
"(",
"paths",
",",
"mode",
",",
"num",
",",
"fs",
",",
"name_function",
")",
":",
"expanded_paths",
"=",
"[",
"]",
"paths",
"=",
"list",
"(",
"paths",
")",
"if",
"\"w\"",
"in",
"mode",
"and",
"sum",
"(",
"[",
"1",
"for",
"p",
"in",
"paths",
"if",
"\"*\"",
"in",
"p",
"]",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"When writing data, only one filename mask can be specified.\"",
")",
"elif",
"\"w\"",
"in",
"mode",
":",
"num",
"=",
"max",
"(",
"num",
",",
"len",
"(",
"paths",
")",
")",
"for",
"curr_path",
"in",
"paths",
":",
"if",
"\"*\"",
"in",
"curr_path",
":",
"if",
"\"w\"",
"in",
"mode",
":",
"# expand using name_function",
"expanded_paths",
".",
"extend",
"(",
"_expand_paths",
"(",
"curr_path",
",",
"name_function",
",",
"num",
")",
")",
"else",
":",
"# expand using glob",
"expanded_paths",
".",
"extend",
"(",
"fs",
".",
"glob",
"(",
"curr_path",
")",
")",
"else",
":",
"expanded_paths",
".",
"append",
"(",
"curr_path",
")",
"# if we generated more paths that asked for, trim the list",
"if",
"\"w\"",
"in",
"mode",
"and",
"len",
"(",
"expanded_paths",
")",
">",
"num",
":",
"expanded_paths",
"=",
"expanded_paths",
"[",
":",
"num",
"]",
"return",
"expanded_paths"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/core.py#L381-L415 | |
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/jormungandr/jormungandr/scenarios/ridesharing/klaxit.py | python | Klaxit._request_journeys | (self, from_coord, to_coord, period_extremity, instance, limit=None) | return [] | :param from_coord: lat,lon ex: '48.109377,-1.682103'
:param to_coord: lat,lon ex: '48.020335,-1.743929'
:param period_extremity: a tuple of [timestamp(utc), clockwise]
:param limit: optional
:return: | [] | def _request_journeys(self, from_coord, to_coord, period_extremity, instance, limit=None):
"""
:param from_coord: lat,lon ex: '48.109377,-1.682103'
:param to_coord: lat,lon ex: '48.020335,-1.743929'
:param period_extremity: a tuple of [timestamp(utc), clockwise]
:param limit: optional
:return:
"""
dep_lat, dep_lon = from_coord.split(',')
arr_lat, arr_lon = to_coord.split(',')
# Parameters documenation : https://dev.klaxit.com/swagger-ui?url=https://via.klaxit.com/v1/swagger.json
# #/carpoolJourneys/get_carpoolJourneys
params = {
'apiKey': self.api_key,
'departureLat': dep_lat,
'departureLng': dep_lon,
'arrivalLat': arr_lat,
'arrivalLng': arr_lon,
'date': period_extremity.datetime,
'timeDelta': self.timedelta,
'departureRadius': 2,
'arrivalRadius': 2,
}
resp = self._call_service(params=params)
if not resp or resp.status_code != 200:
logging.getLogger(__name__).error(
'Klaxit VIA API service unavailable, impossible to query : %s',
resp.url,
extra={'ridesharing_service_id': self._get_rs_id(), 'status_code': resp.status_code},
)
raise RidesharingServiceError('non 200 response', resp.status_code, resp.reason, resp.text)
if resp:
r = self._make_response(resp.json())
self.record_additional_info('Received ridesharing offers', nb_ridesharing_offers=len(r))
logging.getLogger('stat.ridesharing.klaxit').info(
'Received ridesharing offers : %s',
len(r),
extra={'ridesharing_service_id': self._get_rs_id(), 'nb_ridesharing_offers': len(r)},
)
return r
self.record_additional_info('Received ridesharing offers', nb_ridesharing_offers=0)
logging.getLogger('stat.ridesharing.klaxit').info(
'Received ridesharing offers : 0',
extra={'ridesharing_service_id': self._get_rs_id(), 'nb_ridesharing_offers': 0},
)
return [] | [
"def",
"_request_journeys",
"(",
"self",
",",
"from_coord",
",",
"to_coord",
",",
"period_extremity",
",",
"instance",
",",
"limit",
"=",
"None",
")",
":",
"dep_lat",
",",
"dep_lon",
"=",
"from_coord",
".",
"split",
"(",
"','",
")",
"arr_lat",
",",
"arr_lon",
"=",
"to_coord",
".",
"split",
"(",
"','",
")",
"# Parameters documenation : https://dev.klaxit.com/swagger-ui?url=https://via.klaxit.com/v1/swagger.json",
"# #/carpoolJourneys/get_carpoolJourneys",
"params",
"=",
"{",
"'apiKey'",
":",
"self",
".",
"api_key",
",",
"'departureLat'",
":",
"dep_lat",
",",
"'departureLng'",
":",
"dep_lon",
",",
"'arrivalLat'",
":",
"arr_lat",
",",
"'arrivalLng'",
":",
"arr_lon",
",",
"'date'",
":",
"period_extremity",
".",
"datetime",
",",
"'timeDelta'",
":",
"self",
".",
"timedelta",
",",
"'departureRadius'",
":",
"2",
",",
"'arrivalRadius'",
":",
"2",
",",
"}",
"resp",
"=",
"self",
".",
"_call_service",
"(",
"params",
"=",
"params",
")",
"if",
"not",
"resp",
"or",
"resp",
".",
"status_code",
"!=",
"200",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"error",
"(",
"'Klaxit VIA API service unavailable, impossible to query : %s'",
",",
"resp",
".",
"url",
",",
"extra",
"=",
"{",
"'ridesharing_service_id'",
":",
"self",
".",
"_get_rs_id",
"(",
")",
",",
"'status_code'",
":",
"resp",
".",
"status_code",
"}",
",",
")",
"raise",
"RidesharingServiceError",
"(",
"'non 200 response'",
",",
"resp",
".",
"status_code",
",",
"resp",
".",
"reason",
",",
"resp",
".",
"text",
")",
"if",
"resp",
":",
"r",
"=",
"self",
".",
"_make_response",
"(",
"resp",
".",
"json",
"(",
")",
")",
"self",
".",
"record_additional_info",
"(",
"'Received ridesharing offers'",
",",
"nb_ridesharing_offers",
"=",
"len",
"(",
"r",
")",
")",
"logging",
".",
"getLogger",
"(",
"'stat.ridesharing.klaxit'",
")",
".",
"info",
"(",
"'Received ridesharing offers : %s'",
",",
"len",
"(",
"r",
")",
",",
"extra",
"=",
"{",
"'ridesharing_service_id'",
":",
"self",
".",
"_get_rs_id",
"(",
")",
",",
"'nb_ridesharing_offers'",
":",
"len",
"(",
"r",
")",
"}",
",",
")",
"return",
"r",
"self",
".",
"record_additional_info",
"(",
"'Received ridesharing offers'",
",",
"nb_ridesharing_offers",
"=",
"0",
")",
"logging",
".",
"getLogger",
"(",
"'stat.ridesharing.klaxit'",
")",
".",
"info",
"(",
"'Received ridesharing offers : 0'",
",",
"extra",
"=",
"{",
"'ridesharing_service_id'",
":",
"self",
".",
"_get_rs_id",
"(",
")",
",",
"'nb_ridesharing_offers'",
":",
"0",
"}",
",",
")",
"return",
"[",
"]"
] | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/scenarios/ridesharing/klaxit.py#L163-L213 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pytz/tzinfo.py | python | StaticTzInfo.dst | (self, dt, is_dst=None) | return _notime | See datetime.tzinfo.dst
is_dst is ignored for StaticTzInfo, and exists only to
retain compatibility with DstTzInfo. | See datetime.tzinfo.dst | [
"See",
"datetime",
".",
"tzinfo",
".",
"dst"
] | def dst(self, dt, is_dst=None):
'''See datetime.tzinfo.dst
is_dst is ignored for StaticTzInfo, and exists only to
retain compatibility with DstTzInfo.
'''
return _notime | [
"def",
"dst",
"(",
"self",
",",
"dt",
",",
"is_dst",
"=",
"None",
")",
":",
"return",
"_notime"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pytz/tzinfo.py#L96-L102 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hypertreelist.py | python | TreeListMainWindow.SetItemWindowEnabled | (self, item, enable=True, column=None) | Sets whether the window associated with an item is enabled or not.
:param `item`: an instance of :class:`TreeListItem`;
:param `enable`: ``True`` to enable the associated window, ``False`` to disable it;
:param `column`: if not ``None``, an integer specifying the column index.
If it is ``None``, the main column index is used. | Sets whether the window associated with an item is enabled or not. | [
"Sets",
"whether",
"the",
"window",
"associated",
"with",
"an",
"item",
"is",
"enabled",
"or",
"not",
"."
] | def SetItemWindowEnabled(self, item, enable=True, column=None):
"""
Sets whether the window associated with an item is enabled or not.
:param `item`: an instance of :class:`TreeListItem`;
:param `enable`: ``True`` to enable the associated window, ``False`` to disable it;
:param `column`: if not ``None``, an integer specifying the column index.
If it is ``None``, the main column index is used.
"""
item.SetWindowEnabled(enable, column) | [
"def",
"SetItemWindowEnabled",
"(",
"self",
",",
"item",
",",
"enable",
"=",
"True",
",",
"column",
"=",
"None",
")",
":",
"item",
".",
"SetWindowEnabled",
"(",
"enable",
",",
"column",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L2231-L2241 | ||
plumonito/dtslam | 5994bb9cf7a11981b830370db206bceb654c085d | 3rdparty/opencv-git/3rdparty/jinja2/environment.py | python | Environment.lex | (self, source, name=None, filename=None) | Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method. | Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates. | [
"Lex",
"the",
"given",
"sourcecode",
"and",
"return",
"a",
"generator",
"that",
"yields",
"tokens",
"as",
"tuples",
"in",
"the",
"form",
"(",
"lineno",
"token_type",
"value",
")",
".",
"This",
"can",
"be",
"useful",
"for",
":",
"ref",
":",
"extension",
"development",
"<writing",
"-",
"extensions",
">",
"and",
"debugging",
"templates",
"."
] | def lex(self, source, name=None, filename=None):
"""Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method.
"""
source = text_type(source)
try:
return self.lexer.tokeniter(source, name, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source) | [
"def",
"lex",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"source",
"=",
"text_type",
"(",
"source",
")",
"try",
":",
"return",
"self",
".",
"lexer",
".",
"tokeniter",
"(",
"source",
",",
"name",
",",
"filename",
")",
"except",
"TemplateSyntaxError",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"self",
".",
"handle_exception",
"(",
"exc_info",
",",
"source_hint",
"=",
"source",
")"
] | https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/environment.py#L461-L476 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/gradients.py | python | _maybe_colocate_with | (op, colocate_gradients_with_ops) | Context to colocate with `op` if `colocate_gradients_with_ops`. | Context to colocate with `op` if `colocate_gradients_with_ops`. | [
"Context",
"to",
"colocate",
"with",
"op",
"if",
"colocate_gradients_with_ops",
"."
] | def _maybe_colocate_with(op, colocate_gradients_with_ops):
"""Context to colocate with `op` if `colocate_gradients_with_ops`."""
if colocate_gradients_with_ops:
with ops.colocate_with(op):
yield
else:
yield | [
"def",
"_maybe_colocate_with",
"(",
"op",
",",
"colocate_gradients_with_ops",
")",
":",
"if",
"colocate_gradients_with_ops",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"op",
")",
":",
"yield",
"else",
":",
"yield"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/gradients.py#L297-L303 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/config.py | python | IdleConf.GetThemeDict | (self, type, themeName) | return theme | Return {option:value} dict for elements in themeName.
type - string, 'default' or 'user' theme type
themeName - string, theme name
Values are loaded over ultimate fallback defaults to guarantee
that all theme elements are present in a newly created theme. | Return {option:value} dict for elements in themeName. | [
"Return",
"{",
"option",
":",
"value",
"}",
"dict",
"for",
"elements",
"in",
"themeName",
"."
] | def GetThemeDict(self, type, themeName):
"""Return {option:value} dict for elements in themeName.
type - string, 'default' or 'user' theme type
themeName - string, theme name
Values are loaded over ultimate fallback defaults to guarantee
that all theme elements are present in a newly created theme.
"""
if type == 'user':
cfgParser = self.userCfg['highlight']
elif type == 'default':
cfgParser = self.defaultCfg['highlight']
else:
raise InvalidTheme('Invalid theme type specified')
# Provide foreground and background colors for each theme
# element (other than cursor) even though some values are not
# yet used by idle, to allow for their use in the future.
# Default values are generally black and white.
# TODO copy theme from a class attribute.
theme ={'normal-foreground':'#000000',
'normal-background':'#ffffff',
'keyword-foreground':'#000000',
'keyword-background':'#ffffff',
'builtin-foreground':'#000000',
'builtin-background':'#ffffff',
'comment-foreground':'#000000',
'comment-background':'#ffffff',
'string-foreground':'#000000',
'string-background':'#ffffff',
'definition-foreground':'#000000',
'definition-background':'#ffffff',
'hilite-foreground':'#000000',
'hilite-background':'gray',
'break-foreground':'#ffffff',
'break-background':'#000000',
'hit-foreground':'#ffffff',
'hit-background':'#000000',
'error-foreground':'#ffffff',
'error-background':'#000000',
'context-foreground':'#000000',
'context-background':'#ffffff',
'linenumber-foreground':'#000000',
'linenumber-background':'#ffffff',
#cursor (only foreground can be set)
'cursor-foreground':'#000000',
#shell window
'stdout-foreground':'#000000',
'stdout-background':'#ffffff',
'stderr-foreground':'#000000',
'stderr-background':'#ffffff',
'console-foreground':'#000000',
'console-background':'#ffffff',
}
for element in theme:
if not (cfgParser.has_option(themeName, element) or
# Skip warning for new elements.
element.startswith(('context-', 'linenumber-'))):
# Print warning that will return a default color
warning = ('\n Warning: config.IdleConf.GetThemeDict'
' -\n problem retrieving theme element %r'
'\n from theme %r.\n'
' returning default color: %r' %
(element, themeName, theme[element]))
_warn(warning, 'highlight', themeName, element)
theme[element] = cfgParser.Get(
themeName, element, default=theme[element])
return theme | [
"def",
"GetThemeDict",
"(",
"self",
",",
"type",
",",
"themeName",
")",
":",
"if",
"type",
"==",
"'user'",
":",
"cfgParser",
"=",
"self",
".",
"userCfg",
"[",
"'highlight'",
"]",
"elif",
"type",
"==",
"'default'",
":",
"cfgParser",
"=",
"self",
".",
"defaultCfg",
"[",
"'highlight'",
"]",
"else",
":",
"raise",
"InvalidTheme",
"(",
"'Invalid theme type specified'",
")",
"# Provide foreground and background colors for each theme",
"# element (other than cursor) even though some values are not",
"# yet used by idle, to allow for their use in the future.",
"# Default values are generally black and white.",
"# TODO copy theme from a class attribute.",
"theme",
"=",
"{",
"'normal-foreground'",
":",
"'#000000'",
",",
"'normal-background'",
":",
"'#ffffff'",
",",
"'keyword-foreground'",
":",
"'#000000'",
",",
"'keyword-background'",
":",
"'#ffffff'",
",",
"'builtin-foreground'",
":",
"'#000000'",
",",
"'builtin-background'",
":",
"'#ffffff'",
",",
"'comment-foreground'",
":",
"'#000000'",
",",
"'comment-background'",
":",
"'#ffffff'",
",",
"'string-foreground'",
":",
"'#000000'",
",",
"'string-background'",
":",
"'#ffffff'",
",",
"'definition-foreground'",
":",
"'#000000'",
",",
"'definition-background'",
":",
"'#ffffff'",
",",
"'hilite-foreground'",
":",
"'#000000'",
",",
"'hilite-background'",
":",
"'gray'",
",",
"'break-foreground'",
":",
"'#ffffff'",
",",
"'break-background'",
":",
"'#000000'",
",",
"'hit-foreground'",
":",
"'#ffffff'",
",",
"'hit-background'",
":",
"'#000000'",
",",
"'error-foreground'",
":",
"'#ffffff'",
",",
"'error-background'",
":",
"'#000000'",
",",
"'context-foreground'",
":",
"'#000000'",
",",
"'context-background'",
":",
"'#ffffff'",
",",
"'linenumber-foreground'",
":",
"'#000000'",
",",
"'linenumber-background'",
":",
"'#ffffff'",
",",
"#cursor (only foreground can be set)",
"'cursor-foreground'",
":",
"'#000000'",
",",
"#shell window",
"'stdout-foreground'",
":",
"'#000000'",
",",
"'stdout-background'",
":",
"'#ffffff'",
",",
"'stderr-foreground'",
":",
"'#000000'",
",",
"'stderr-background'",
":",
"'#ffffff'",
",",
"'console-foreground'",
":",
"'#000000'",
",",
"'console-background'",
":",
"'#ffffff'",
",",
"}",
"for",
"element",
"in",
"theme",
":",
"if",
"not",
"(",
"cfgParser",
".",
"has_option",
"(",
"themeName",
",",
"element",
")",
"or",
"# Skip warning for new elements.",
"element",
".",
"startswith",
"(",
"(",
"'context-'",
",",
"'linenumber-'",
")",
")",
")",
":",
"# Print warning that will return a default color",
"warning",
"=",
"(",
"'\\n Warning: config.IdleConf.GetThemeDict'",
"' -\\n problem retrieving theme element %r'",
"'\\n from theme %r.\\n'",
"' returning default color: %r'",
"%",
"(",
"element",
",",
"themeName",
",",
"theme",
"[",
"element",
"]",
")",
")",
"_warn",
"(",
"warning",
",",
"'highlight'",
",",
"themeName",
",",
"element",
")",
"theme",
"[",
"element",
"]",
"=",
"cfgParser",
".",
"Get",
"(",
"themeName",
",",
"element",
",",
"default",
"=",
"theme",
"[",
"element",
"]",
")",
"return",
"theme"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/config.py#L289-L355 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/lib/caching.py | python | get | (invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs) | return request.cached | Try to obtain cached output. If fresh enough, raise HTTPError(304).
If POST, PUT, or DELETE:
* invalidates (deletes) any cached response for this resource
* sets request.cached = False
* sets request.cacheable = False
else if a cached copy exists:
* sets request.cached = True
* sets request.cacheable = False
* sets response.headers to the cached values
* checks the cached Last-Modified response header against the
current If-(Un)Modified-Since request headers; raises 304
if necessary.
* sets response.status and response.body to the cached values
* returns True
otherwise:
* sets request.cached = False
* sets request.cacheable = True
* returns False | Try to obtain cached output. If fresh enough, raise HTTPError(304).
If POST, PUT, or DELETE:
* invalidates (deletes) any cached response for this resource
* sets request.cached = False
* sets request.cacheable = False
else if a cached copy exists:
* sets request.cached = True
* sets request.cacheable = False
* sets response.headers to the cached values
* checks the cached Last-Modified response header against the
current If-(Un)Modified-Since request headers; raises 304
if necessary.
* sets response.status and response.body to the cached values
* returns True
otherwise:
* sets request.cached = False
* sets request.cacheable = True
* returns False | [
"Try",
"to",
"obtain",
"cached",
"output",
".",
"If",
"fresh",
"enough",
"raise",
"HTTPError",
"(",
"304",
")",
".",
"If",
"POST",
"PUT",
"or",
"DELETE",
":",
"*",
"invalidates",
"(",
"deletes",
")",
"any",
"cached",
"response",
"for",
"this",
"resource",
"*",
"sets",
"request",
".",
"cached",
"=",
"False",
"*",
"sets",
"request",
".",
"cacheable",
"=",
"False",
"else",
"if",
"a",
"cached",
"copy",
"exists",
":",
"*",
"sets",
"request",
".",
"cached",
"=",
"True",
"*",
"sets",
"request",
".",
"cacheable",
"=",
"False",
"*",
"sets",
"response",
".",
"headers",
"to",
"the",
"cached",
"values",
"*",
"checks",
"the",
"cached",
"Last",
"-",
"Modified",
"response",
"header",
"against",
"the",
"current",
"If",
"-",
"(",
"Un",
")",
"Modified",
"-",
"Since",
"request",
"headers",
";",
"raises",
"304",
"if",
"necessary",
".",
"*",
"sets",
"response",
".",
"status",
"and",
"response",
".",
"body",
"to",
"the",
"cached",
"values",
"*",
"returns",
"True",
"otherwise",
":",
"*",
"sets",
"request",
".",
"cached",
"=",
"False",
"*",
"sets",
"request",
".",
"cacheable",
"=",
"True",
"*",
"returns",
"False"
] | def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs):
"""Try to obtain cached output. If fresh enough, raise HTTPError(304).
If POST, PUT, or DELETE:
* invalidates (deletes) any cached response for this resource
* sets request.cached = False
* sets request.cacheable = False
else if a cached copy exists:
* sets request.cached = True
* sets request.cacheable = False
* sets response.headers to the cached values
* checks the cached Last-Modified response header against the
current If-(Un)Modified-Since request headers; raises 304
if necessary.
* sets response.status and response.body to the cached values
* returns True
otherwise:
* sets request.cached = False
* sets request.cacheable = True
* returns False
"""
request = cherrypy.serving.request
response = cherrypy.serving.response
if not hasattr(cherrypy, "_cache"):
# Make a process-wide Cache object.
cherrypy._cache = kwargs.pop("cache_class", MemoryCache)()
# Take all remaining kwargs and set them on the Cache object.
for k, v in kwargs.items():
setattr(cherrypy._cache, k, v)
cherrypy._cache.debug = debug
# POST, PUT, DELETE should invalidate (delete) the cached copy.
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10.
if request.method in invalid_methods:
if debug:
cherrypy.log('request.method %r in invalid_methods %r' %
(request.method, invalid_methods), 'TOOLS.CACHING')
cherrypy._cache.delete()
request.cached = False
request.cacheable = False
return False
if 'no-cache' in [e.value for e in request.headers.elements('Pragma')]:
request.cached = False
request.cacheable = True
return False
cache_data = cherrypy._cache.get()
request.cached = bool(cache_data)
request.cacheable = not request.cached
if request.cached:
# Serve the cached copy.
max_age = cherrypy._cache.delay
for v in [e.value for e in request.headers.elements('Cache-Control')]:
atoms = v.split('=', 1)
directive = atoms.pop(0)
if directive == 'max-age':
if len(atoms) != 1 or not atoms[0].isdigit():
raise cherrypy.HTTPError(400, "Invalid Cache-Control header")
max_age = int(atoms[0])
break
elif directive == 'no-cache':
if debug:
cherrypy.log('Ignoring cache due to Cache-Control: no-cache',
'TOOLS.CACHING')
request.cached = False
request.cacheable = True
return False
if debug:
cherrypy.log('Reading response from cache', 'TOOLS.CACHING')
s, h, b, create_time = cache_data
age = int(response.time - create_time)
if (age > max_age):
if debug:
cherrypy.log('Ignoring cache due to age > %d' % max_age,
'TOOLS.CACHING')
request.cached = False
request.cacheable = True
return False
# Copy the response headers. See http://www.cherrypy.org/ticket/721.
response.headers = rh = httputil.HeaderMap()
for k in h:
dict.__setitem__(rh, k, dict.__getitem__(h, k))
# Add the required Age header
response.headers["Age"] = str(age)
try:
# Note that validate_since depends on a Last-Modified header;
# this was put into the cached copy, and should have been
# resurrected just above (response.headers = cache_data[1]).
cptools.validate_since()
except cherrypy.HTTPRedirect:
x = sys.exc_info()[1]
if x.status == 304:
cherrypy._cache.tot_non_modified += 1
raise
# serve it & get out from the request
response.status = s
response.body = b
else:
if debug:
cherrypy.log('request is not cached', 'TOOLS.CACHING')
return request.cached | [
"def",
"get",
"(",
"invalid_methods",
"=",
"(",
"\"POST\"",
",",
"\"PUT\"",
",",
"\"DELETE\"",
")",
",",
"debug",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"cherrypy",
".",
"serving",
".",
"request",
"response",
"=",
"cherrypy",
".",
"serving",
".",
"response",
"if",
"not",
"hasattr",
"(",
"cherrypy",
",",
"\"_cache\"",
")",
":",
"# Make a process-wide Cache object.",
"cherrypy",
".",
"_cache",
"=",
"kwargs",
".",
"pop",
"(",
"\"cache_class\"",
",",
"MemoryCache",
")",
"(",
")",
"# Take all remaining kwargs and set them on the Cache object.",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"cherrypy",
".",
"_cache",
",",
"k",
",",
"v",
")",
"cherrypy",
".",
"_cache",
".",
"debug",
"=",
"debug",
"# POST, PUT, DELETE should invalidate (delete) the cached copy.",
"# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10.",
"if",
"request",
".",
"method",
"in",
"invalid_methods",
":",
"if",
"debug",
":",
"cherrypy",
".",
"log",
"(",
"'request.method %r in invalid_methods %r'",
"%",
"(",
"request",
".",
"method",
",",
"invalid_methods",
")",
",",
"'TOOLS.CACHING'",
")",
"cherrypy",
".",
"_cache",
".",
"delete",
"(",
")",
"request",
".",
"cached",
"=",
"False",
"request",
".",
"cacheable",
"=",
"False",
"return",
"False",
"if",
"'no-cache'",
"in",
"[",
"e",
".",
"value",
"for",
"e",
"in",
"request",
".",
"headers",
".",
"elements",
"(",
"'Pragma'",
")",
"]",
":",
"request",
".",
"cached",
"=",
"False",
"request",
".",
"cacheable",
"=",
"True",
"return",
"False",
"cache_data",
"=",
"cherrypy",
".",
"_cache",
".",
"get",
"(",
")",
"request",
".",
"cached",
"=",
"bool",
"(",
"cache_data",
")",
"request",
".",
"cacheable",
"=",
"not",
"request",
".",
"cached",
"if",
"request",
".",
"cached",
":",
"# Serve the cached copy.",
"max_age",
"=",
"cherrypy",
".",
"_cache",
".",
"delay",
"for",
"v",
"in",
"[",
"e",
".",
"value",
"for",
"e",
"in",
"request",
".",
"headers",
".",
"elements",
"(",
"'Cache-Control'",
")",
"]",
":",
"atoms",
"=",
"v",
".",
"split",
"(",
"'='",
",",
"1",
")",
"directive",
"=",
"atoms",
".",
"pop",
"(",
"0",
")",
"if",
"directive",
"==",
"'max-age'",
":",
"if",
"len",
"(",
"atoms",
")",
"!=",
"1",
"or",
"not",
"atoms",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"raise",
"cherrypy",
".",
"HTTPError",
"(",
"400",
",",
"\"Invalid Cache-Control header\"",
")",
"max_age",
"=",
"int",
"(",
"atoms",
"[",
"0",
"]",
")",
"break",
"elif",
"directive",
"==",
"'no-cache'",
":",
"if",
"debug",
":",
"cherrypy",
".",
"log",
"(",
"'Ignoring cache due to Cache-Control: no-cache'",
",",
"'TOOLS.CACHING'",
")",
"request",
".",
"cached",
"=",
"False",
"request",
".",
"cacheable",
"=",
"True",
"return",
"False",
"if",
"debug",
":",
"cherrypy",
".",
"log",
"(",
"'Reading response from cache'",
",",
"'TOOLS.CACHING'",
")",
"s",
",",
"h",
",",
"b",
",",
"create_time",
"=",
"cache_data",
"age",
"=",
"int",
"(",
"response",
".",
"time",
"-",
"create_time",
")",
"if",
"(",
"age",
">",
"max_age",
")",
":",
"if",
"debug",
":",
"cherrypy",
".",
"log",
"(",
"'Ignoring cache due to age > %d'",
"%",
"max_age",
",",
"'TOOLS.CACHING'",
")",
"request",
".",
"cached",
"=",
"False",
"request",
".",
"cacheable",
"=",
"True",
"return",
"False",
"# Copy the response headers. See http://www.cherrypy.org/ticket/721.",
"response",
".",
"headers",
"=",
"rh",
"=",
"httputil",
".",
"HeaderMap",
"(",
")",
"for",
"k",
"in",
"h",
":",
"dict",
".",
"__setitem__",
"(",
"rh",
",",
"k",
",",
"dict",
".",
"__getitem__",
"(",
"h",
",",
"k",
")",
")",
"# Add the required Age header",
"response",
".",
"headers",
"[",
"\"Age\"",
"]",
"=",
"str",
"(",
"age",
")",
"try",
":",
"# Note that validate_since depends on a Last-Modified header;",
"# this was put into the cached copy, and should have been",
"# resurrected just above (response.headers = cache_data[1]).",
"cptools",
".",
"validate_since",
"(",
")",
"except",
"cherrypy",
".",
"HTTPRedirect",
":",
"x",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"x",
".",
"status",
"==",
"304",
":",
"cherrypy",
".",
"_cache",
".",
"tot_non_modified",
"+=",
"1",
"raise",
"# serve it & get out from the request",
"response",
".",
"status",
"=",
"s",
"response",
".",
"body",
"=",
"b",
"else",
":",
"if",
"debug",
":",
"cherrypy",
".",
"log",
"(",
"'request is not cached'",
",",
"'TOOLS.CACHING'",
")",
"return",
"request",
".",
"cached"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/caching.py#L266-L376 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/appController.py | python | AppController._changePrimViewDepth | (self, action) | Signal handler for view-depth menu items | Signal handler for view-depth menu items | [
"Signal",
"handler",
"for",
"view",
"-",
"depth",
"menu",
"items"
] | def _changePrimViewDepth(self, action):
"""Signal handler for view-depth menu items
"""
actionTxt = str(action.text())
# recover the depth factor from the action's name
depth = int(actionTxt[actionTxt.find(" ")+1])
self._expandToDepth(depth) | [
"def",
"_changePrimViewDepth",
"(",
"self",
",",
"action",
")",
":",
"actionTxt",
"=",
"str",
"(",
"action",
".",
"text",
"(",
")",
")",
"# recover the depth factor from the action's name",
"depth",
"=",
"int",
"(",
"actionTxt",
"[",
"actionTxt",
".",
"find",
"(",
"\" \"",
")",
"+",
"1",
"]",
")",
"self",
".",
"_expandToDepth",
"(",
"depth",
")"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L2931-L2937 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/isolate/merge_isolate.py | python | Configs.flatten | (self) | return dict(
(k, v.flatten()) for k, v in self.per_os.iteritems() if k is not None) | Returns a flat dictionary representation of the configuration.
Skips None pseudo-OS. | Returns a flat dictionary representation of the configuration. | [
"Returns",
"a",
"flat",
"dictionary",
"representation",
"of",
"the",
"configuration",
"."
] | def flatten(self):
"""Returns a flat dictionary representation of the configuration.
Skips None pseudo-OS.
"""
return dict(
(k, v.flatten()) for k, v in self.per_os.iteritems() if k is not None) | [
"def",
"flatten",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"v",
".",
"flatten",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"per_os",
".",
"iteritems",
"(",
")",
"if",
"k",
"is",
"not",
"None",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/isolate/merge_isolate.py#L165-L171 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/ConfigParser.py | python | RawConfigParser.remove_option | (self, section, option) | return existed | Remove an option. | Remove an option. | [
"Remove",
"an",
"option",
"."
] | def remove_option(self, section, option):
"""Remove an option."""
if not section or section == DEFAULTSECT:
sectdict = self._defaults
else:
try:
sectdict = self._sections[section]
except KeyError:
raise NoSectionError(section)
option = self.optionxform(option)
existed = option in sectdict
if existed:
del sectdict[option]
return existed | [
"def",
"remove_option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"not",
"section",
"or",
"section",
"==",
"DEFAULTSECT",
":",
"sectdict",
"=",
"self",
".",
"_defaults",
"else",
":",
"try",
":",
"sectdict",
"=",
"self",
".",
"_sections",
"[",
"section",
"]",
"except",
"KeyError",
":",
"raise",
"NoSectionError",
"(",
"section",
")",
"option",
"=",
"self",
".",
"optionxform",
"(",
"option",
")",
"existed",
"=",
"option",
"in",
"sectdict",
"if",
"existed",
":",
"del",
"sectdict",
"[",
"option",
"]",
"return",
"existed"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/ConfigParser.py#L416-L429 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py | python | IMAP4.namespace | (self) | return self._untagged_response(typ, dat, name) | Returns IMAP namespaces ala rfc2342
(typ, [data, ...]) = <instance>.namespace() | Returns IMAP namespaces ala rfc2342 | [
"Returns",
"IMAP",
"namespaces",
"ala",
"rfc2342"
] | def namespace(self):
""" Returns IMAP namespaces ala rfc2342
(typ, [data, ...]) = <instance>.namespace()
"""
name = 'NAMESPACE'
typ, dat = self._simple_command(name)
return self._untagged_response(typ, dat, name) | [
"def",
"namespace",
"(",
"self",
")",
":",
"name",
"=",
"'NAMESPACE'",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"name",
")",
"return",
"self",
".",
"_untagged_response",
"(",
"typ",
",",
"dat",
",",
"name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py#L655-L662 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/signaltools.py | python | sosfilt | (sos, x, axis=-1, zi=None) | return out | Filter data along one dimension using cascaded second-order sections.
Filter a data sequence, `x`, using a digital IIR filter defined by
`sos`. This is implemented by performing `lfilter` for each
second-order section. See `lfilter` for details.
Parameters
----------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. Each row corresponds to a second-order
section, with the first three columns providing the numerator
coefficients and the last three providing the denominator
coefficients.
x : array_like
An N-dimensional input array.
axis : int, optional
The axis of the input data array along which to apply the
linear filter. The filter is applied to each subarray along
this axis. Default is -1.
zi : array_like, optional
Initial conditions for the cascaded filter delays. It is a (at
least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where
``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]``
replaced by 2. If `zi` is None or is not given then initial rest
(i.e. all zeros) is assumed.
Note that these initial conditions are *not* the same as the initial
conditions given by `lfiltic` or `lfilter_zi`.
Returns
-------
y : ndarray
The output of the digital filter.
zf : ndarray, optional
If `zi` is None, this is not returned, otherwise, `zf` holds the
final filter delay values.
See Also
--------
zpk2sos, sos2zpk, sosfilt_zi, sosfiltfilt, sosfreqz
Notes
-----
The filter function is implemented as a series of second-order filters
with direct-form II transposed structure. It is designed to minimize
numerical precision errors for high-order filters.
.. versionadded:: 0.16.0
Examples
--------
Plot a 13th-order filter's impulse response using both `lfilter` and
`sosfilt`, showing the instability that results from trying to do a
13th-order filter in a single stage (the numerical error pushes some poles
outside of the unit circle):
>>> import matplotlib.pyplot as plt
>>> from scipy import signal
>>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba')
>>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos')
>>> x = signal.unit_impulse(700)
>>> y_tf = signal.lfilter(b, a, x)
>>> y_sos = signal.sosfilt(sos, x)
>>> plt.plot(y_tf, 'r', label='TF')
>>> plt.plot(y_sos, 'k', label='SOS')
>>> plt.legend(loc='best')
>>> plt.show() | Filter data along one dimension using cascaded second-order sections. | [
"Filter",
"data",
"along",
"one",
"dimension",
"using",
"cascaded",
"second",
"-",
"order",
"sections",
"."
] | def sosfilt(sos, x, axis=-1, zi=None):
"""
Filter data along one dimension using cascaded second-order sections.
Filter a data sequence, `x`, using a digital IIR filter defined by
`sos`. This is implemented by performing `lfilter` for each
second-order section. See `lfilter` for details.
Parameters
----------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. Each row corresponds to a second-order
section, with the first three columns providing the numerator
coefficients and the last three providing the denominator
coefficients.
x : array_like
An N-dimensional input array.
axis : int, optional
The axis of the input data array along which to apply the
linear filter. The filter is applied to each subarray along
this axis. Default is -1.
zi : array_like, optional
Initial conditions for the cascaded filter delays. It is a (at
least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where
``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]``
replaced by 2. If `zi` is None or is not given then initial rest
(i.e. all zeros) is assumed.
Note that these initial conditions are *not* the same as the initial
conditions given by `lfiltic` or `lfilter_zi`.
Returns
-------
y : ndarray
The output of the digital filter.
zf : ndarray, optional
If `zi` is None, this is not returned, otherwise, `zf` holds the
final filter delay values.
See Also
--------
zpk2sos, sos2zpk, sosfilt_zi, sosfiltfilt, sosfreqz
Notes
-----
The filter function is implemented as a series of second-order filters
with direct-form II transposed structure. It is designed to minimize
numerical precision errors for high-order filters.
.. versionadded:: 0.16.0
Examples
--------
Plot a 13th-order filter's impulse response using both `lfilter` and
`sosfilt`, showing the instability that results from trying to do a
13th-order filter in a single stage (the numerical error pushes some poles
outside of the unit circle):
>>> import matplotlib.pyplot as plt
>>> from scipy import signal
>>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba')
>>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos')
>>> x = signal.unit_impulse(700)
>>> y_tf = signal.lfilter(b, a, x)
>>> y_sos = signal.sosfilt(sos, x)
>>> plt.plot(y_tf, 'r', label='TF')
>>> plt.plot(y_sos, 'k', label='SOS')
>>> plt.legend(loc='best')
>>> plt.show()
"""
x = np.asarray(x)
sos, n_sections = _validate_sos(sos)
use_zi = zi is not None
if use_zi:
zi = np.asarray(zi)
x_zi_shape = list(x.shape)
x_zi_shape[axis] = 2
x_zi_shape = tuple([n_sections] + x_zi_shape)
if zi.shape != x_zi_shape:
raise ValueError('Invalid zi shape. With axis=%r, an input with '
'shape %r, and an sos array with %d sections, zi '
'must have shape %r, got %r.' %
(axis, x.shape, n_sections, x_zi_shape, zi.shape))
zf = zeros_like(zi)
for section in range(n_sections):
if use_zi:
x, zf[section] = lfilter(sos[section, :3], sos[section, 3:],
x, axis, zi=zi[section])
else:
x = lfilter(sos[section, :3], sos[section, 3:], x, axis)
out = (x, zf) if use_zi else x
return out | [
"def",
"sosfilt",
"(",
"sos",
",",
"x",
",",
"axis",
"=",
"-",
"1",
",",
"zi",
"=",
"None",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"sos",
",",
"n_sections",
"=",
"_validate_sos",
"(",
"sos",
")",
"use_zi",
"=",
"zi",
"is",
"not",
"None",
"if",
"use_zi",
":",
"zi",
"=",
"np",
".",
"asarray",
"(",
"zi",
")",
"x_zi_shape",
"=",
"list",
"(",
"x",
".",
"shape",
")",
"x_zi_shape",
"[",
"axis",
"]",
"=",
"2",
"x_zi_shape",
"=",
"tuple",
"(",
"[",
"n_sections",
"]",
"+",
"x_zi_shape",
")",
"if",
"zi",
".",
"shape",
"!=",
"x_zi_shape",
":",
"raise",
"ValueError",
"(",
"'Invalid zi shape. With axis=%r, an input with '",
"'shape %r, and an sos array with %d sections, zi '",
"'must have shape %r, got %r.'",
"%",
"(",
"axis",
",",
"x",
".",
"shape",
",",
"n_sections",
",",
"x_zi_shape",
",",
"zi",
".",
"shape",
")",
")",
"zf",
"=",
"zeros_like",
"(",
"zi",
")",
"for",
"section",
"in",
"range",
"(",
"n_sections",
")",
":",
"if",
"use_zi",
":",
"x",
",",
"zf",
"[",
"section",
"]",
"=",
"lfilter",
"(",
"sos",
"[",
"section",
",",
":",
"3",
"]",
",",
"sos",
"[",
"section",
",",
"3",
":",
"]",
",",
"x",
",",
"axis",
",",
"zi",
"=",
"zi",
"[",
"section",
"]",
")",
"else",
":",
"x",
"=",
"lfilter",
"(",
"sos",
"[",
"section",
",",
":",
"3",
"]",
",",
"sos",
"[",
"section",
",",
"3",
":",
"]",
",",
"x",
",",
"axis",
")",
"out",
"=",
"(",
"x",
",",
"zf",
")",
"if",
"use_zi",
"else",
"x",
"return",
"out"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/signaltools.py#L3203-L3296 | |
ARM-software/armnn | 5e9965cae1cc6162649910f423ebd86001fc1931 | python/pyarmnn/examples/image_classification/example_utils.py | python | preprocess_default | (img: Image, width: int, height: int, data_type, scale: float, mean: list,
stddev: list) | return img | Default preprocessing image function.
Args:
img (PIL.Image): PIL.Image object instance.
width (int): Width to resize to.
height (int): Height to resize to.
data_type: Data Type to cast the image to.
scale (float): Scaling value.
mean (list): RGB mean offset.
stddev (list): RGB standard deviation.
Returns:
np.array: Resized and preprocessed image. | Default preprocessing image function. | [
"Default",
"preprocessing",
"image",
"function",
"."
] | def preprocess_default(img: Image, width: int, height: int, data_type, scale: float, mean: list,
stddev: list):
"""Default preprocessing image function.
Args:
img (PIL.Image): PIL.Image object instance.
width (int): Width to resize to.
height (int): Height to resize to.
data_type: Data Type to cast the image to.
scale (float): Scaling value.
mean (list): RGB mean offset.
stddev (list): RGB standard deviation.
Returns:
np.array: Resized and preprocessed image.
"""
img = img.resize((width, height), Image.BILINEAR)
img = img.convert('RGB')
img = np.array(img)
img = np.reshape(img, (-1, 3)) # reshape to [RGB][RGB]...
img = ((img / scale) - mean) / stddev
img = img.flatten().astype(data_type)
return img | [
"def",
"preprocess_default",
"(",
"img",
":",
"Image",
",",
"width",
":",
"int",
",",
"height",
":",
"int",
",",
"data_type",
",",
"scale",
":",
"float",
",",
"mean",
":",
"list",
",",
"stddev",
":",
"list",
")",
":",
"img",
"=",
"img",
".",
"resize",
"(",
"(",
"width",
",",
"height",
")",
",",
"Image",
".",
"BILINEAR",
")",
"img",
"=",
"img",
".",
"convert",
"(",
"'RGB'",
")",
"img",
"=",
"np",
".",
"array",
"(",
"img",
")",
"img",
"=",
"np",
".",
"reshape",
"(",
"img",
",",
"(",
"-",
"1",
",",
"3",
")",
")",
"# reshape to [RGB][RGB]...",
"img",
"=",
"(",
"(",
"img",
"/",
"scale",
")",
"-",
"mean",
")",
"/",
"stddev",
"img",
"=",
"img",
".",
"flatten",
"(",
")",
".",
"astype",
"(",
"data_type",
")",
"return",
"img"
] | https://github.com/ARM-software/armnn/blob/5e9965cae1cc6162649910f423ebd86001fc1931/python/pyarmnn/examples/image_classification/example_utils.py#L159-L181 | |
CoolProp/CoolProp | 381c8535e5dec3eec27ad430ebbfff8bc9dfc008 | dev/incompressible_liquids/CPIncomp/__init__.py | python | getIgnoreNames | () | return ignList | Returns a list of names of classes that should
not be treated like the normal fluids. | Returns a list of names of classes that should
not be treated like the normal fluids. | [
"Returns",
"a",
"list",
"of",
"names",
"of",
"classes",
"that",
"should",
"not",
"be",
"treated",
"like",
"the",
"normal",
"fluids",
"."
] | def getIgnoreNames():
"""
Returns a list of names of classes that should
not be treated like the normal fluids.
"""
ignList = []
ignList += getBaseClassNames()
ignList += getExampleNames()
return ignList | [
"def",
"getIgnoreNames",
"(",
")",
":",
"ignList",
"=",
"[",
"]",
"ignList",
"+=",
"getBaseClassNames",
"(",
")",
"ignList",
"+=",
"getExampleNames",
"(",
")",
"return",
"ignList"
] | https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/dev/incompressible_liquids/CPIncomp/__init__.py#L46-L54 | |
JoseExposito/touchegg | 1f3fda214358d071c05da4bf17c070c33d67b5eb | cmake/cpplint.py | python | FindNextMultiLineCommentStart | (lines, lineix) | return len(lines) | Find the beginning marker for a multiline comment. | Find the beginning marker for a multiline comment. | [
"Find",
"the",
"beginning",
"marker",
"for",
"a",
"multiline",
"comment",
"."
] | def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return lineix
lineix += 1
return len(lines) | [
"def",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
":",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'/*'",
")",
":",
"# Only return this marker if the comment goes beyond this line",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"find",
"(",
"'*/'",
",",
"2",
")",
"<",
"0",
":",
"return",
"lineix",
"lineix",
"+=",
"1",
"return",
"len",
"(",
"lines",
")"
] | https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L1364-L1372 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/preprocessing/categorical_vocabulary.py | python | CategoricalVocabulary.add | (self, category, count=1) | Adds count of the category to the frequency table.
Args:
category: string or integer, category to add frequency to.
count: optional integer, how many to add. | Adds count of the category to the frequency table. | [
"Adds",
"count",
"of",
"the",
"category",
"to",
"the",
"frequency",
"table",
"."
] | def add(self, category, count=1):
"""Adds count of the category to the frequency table.
Args:
category: string or integer, category to add frequency to.
count: optional integer, how many to add.
"""
category_id = self.get(category)
if category_id <= 0:
return
self._freq[category] += count | [
"def",
"add",
"(",
"self",
",",
"category",
",",
"count",
"=",
"1",
")",
":",
"category_id",
"=",
"self",
".",
"get",
"(",
"category",
")",
"if",
"category_id",
"<=",
"0",
":",
"return",
"self",
".",
"_freq",
"[",
"category",
"]",
"+=",
"count"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/preprocessing/categorical_vocabulary.py#L87-L97 | ||
SeisSol/SeisSol | 955fbeb8c5d40d3363a2da0edc611259aebe1653 | postprocessing/science/corner_frequency.py | python | linear_interpolate | (amplitude_trace, old_time_comp, start_frequency, end_frequency, frequency_steps) | return new_amplitude_trace, new_time_comp | Usually spectra do not have equal frequency steps, but this is needed for further functions of this script.
With this function a spectrum gets linear interpolated and the time compiler (frequency steps)
transformed to equal density. | Usually spectra do not have equal frequency steps, but this is needed for further functions of this script.
With this function a spectrum gets linear interpolated and the time compiler (frequency steps)
transformed to equal density. | [
"Usually",
"spectra",
"do",
"not",
"have",
"equal",
"frequency",
"steps",
"but",
"this",
"is",
"needed",
"for",
"further",
"functions",
"of",
"this",
"script",
".",
"With",
"this",
"function",
"a",
"spectrum",
"gets",
"linear",
"interpolated",
"and",
"the",
"time",
"compiler",
"(",
"frequency",
"steps",
")",
"transformed",
"to",
"equal",
"density",
"."
] | def linear_interpolate(amplitude_trace, old_time_comp, start_frequency, end_frequency, frequency_steps):
"""Usually spectra do not have equal frequency steps, but this is needed for further functions of this script.
With this function a spectrum gets linear interpolated and the time compiler (frequency steps)
transformed to equal density."""
interpolate_range=np.arange(start_frequency, end_frequency+frequency_steps, frequency_steps)
new_amplitude_trace=np.zeros(len(interpolate_range))
for q in range(0,len(interpolate_range)):
for d in range(0,len(old_time_comp)):
if old_time_comp[d] > interpolate_range[q]:
new_amplitude_trace[q]=abs(amplitude_trace[d-1])+(interpolate_range[q]-old_time_comp[d-1])*(
abs(amplitude_trace[d])-abs(amplitude_trace[d-1]))/(
old_time_comp[d]-old_time_comp[d-1])
break
new_time_comp = interpolate_range
return new_amplitude_trace, new_time_comp | [
"def",
"linear_interpolate",
"(",
"amplitude_trace",
",",
"old_time_comp",
",",
"start_frequency",
",",
"end_frequency",
",",
"frequency_steps",
")",
":",
"interpolate_range",
"=",
"np",
".",
"arange",
"(",
"start_frequency",
",",
"end_frequency",
"+",
"frequency_steps",
",",
"frequency_steps",
")",
"new_amplitude_trace",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"interpolate_range",
")",
")",
"for",
"q",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"interpolate_range",
")",
")",
":",
"for",
"d",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"old_time_comp",
")",
")",
":",
"if",
"old_time_comp",
"[",
"d",
"]",
">",
"interpolate_range",
"[",
"q",
"]",
":",
"new_amplitude_trace",
"[",
"q",
"]",
"=",
"abs",
"(",
"amplitude_trace",
"[",
"d",
"-",
"1",
"]",
")",
"+",
"(",
"interpolate_range",
"[",
"q",
"]",
"-",
"old_time_comp",
"[",
"d",
"-",
"1",
"]",
")",
"*",
"(",
"abs",
"(",
"amplitude_trace",
"[",
"d",
"]",
")",
"-",
"abs",
"(",
"amplitude_trace",
"[",
"d",
"-",
"1",
"]",
")",
")",
"/",
"(",
"old_time_comp",
"[",
"d",
"]",
"-",
"old_time_comp",
"[",
"d",
"-",
"1",
"]",
")",
"break",
"new_time_comp",
"=",
"interpolate_range",
"return",
"new_amplitude_trace",
",",
"new_time_comp"
] | https://github.com/SeisSol/SeisSol/blob/955fbeb8c5d40d3363a2da0edc611259aebe1653/postprocessing/science/corner_frequency.py#L13-L31 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py | python | Target.PreActionInput | (self, flavor) | return self.FinalOutput() or self.preaction_stamp | Return the path, if any, that should be used as a dependency of
any dependent action step. | Return the path, if any, that should be used as a dependency of
any dependent action step. | [
"Return",
"the",
"path",
"if",
"any",
"that",
"should",
"be",
"used",
"as",
"a",
"dependency",
"of",
"any",
"dependent",
"action",
"step",
"."
] | def PreActionInput(self, flavor):
"""Return the path, if any, that should be used as a dependency of
any dependent action step."""
if self.UsesToc(flavor):
return self.FinalOutput() + '.TOC'
return self.FinalOutput() or self.preaction_stamp | [
"def",
"PreActionInput",
"(",
"self",
",",
"flavor",
")",
":",
"if",
"self",
".",
"UsesToc",
"(",
"flavor",
")",
":",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"+",
"'.TOC'",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"or",
"self",
".",
"preaction_stamp"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py#L177-L182 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/utils.py | python | check_iterable | (obj) | return True | Check whether the object is Iterable. | Check whether the object is Iterable. | [
"Check",
"whether",
"the",
"object",
"is",
"Iterable",
"."
] | def check_iterable(obj):
"""Check whether the object is Iterable."""
try:
obj_iterator = iter(obj)
except TypeError as te:
print(obj.__str__(), "is not iterable")
return False
return True | [
"def",
"check_iterable",
"(",
"obj",
")",
":",
"try",
":",
"obj_iterator",
"=",
"iter",
"(",
"obj",
")",
"except",
"TypeError",
"as",
"te",
":",
"print",
"(",
"obj",
".",
"__str__",
"(",
")",
",",
"\"is not iterable\"",
")",
"return",
"False",
"return",
"True"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/utils.py#L453-L460 | |
alibaba/MNN | c4d9566171d589c3ded23aa18ffb197016995a12 | pymnn/pip_package/MNN/expr/__init__.py | python | reciprocal | (x) | return _F.reciprocal(x) | reciprocal(x)
Return the ``1/x``, element-wise.
Parameters
----------
x : var_like, input value, available range is [!=0].
Returns
-------
y : Var. The ``1/x`` of `x`.
Example:
-------
>>> expr.reciprocal([9., 0.5])
var([0.11111111, 2.]) | reciprocal(x)
Return the ``1/x``, element-wise. | [
"reciprocal",
"(",
"x",
")",
"Return",
"the",
"1",
"/",
"x",
"element",
"-",
"wise",
"."
] | def reciprocal(x):
'''
reciprocal(x)
Return the ``1/x``, element-wise.
Parameters
----------
x : var_like, input value, available range is [!=0].
Returns
-------
y : Var. The ``1/x`` of `x`.
Example:
-------
>>> expr.reciprocal([9., 0.5])
var([0.11111111, 2.])
'''
x = _to_var(x)
return _F.reciprocal(x) | [
"def",
"reciprocal",
"(",
"x",
")",
":",
"x",
"=",
"_to_var",
"(",
"x",
")",
"return",
"_F",
".",
"reciprocal",
"(",
"x",
")"
] | https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L597-L616 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/tool/build.py | python | RcBuilder.CheckAssertedOutputFiles | (self, assert_output_files) | return True | Checks that the asserted output files are specified in the given list.
Returns true if the asserted files are present. If they are not, returns
False and prints the failure. | Checks that the asserted output files are specified in the given list. | [
"Checks",
"that",
"the",
"asserted",
"output",
"files",
"are",
"specified",
"in",
"the",
"given",
"list",
"."
] | def CheckAssertedOutputFiles(self, assert_output_files):
'''Checks that the asserted output files are specified in the given list.
Returns true if the asserted files are present. If they are not, returns
False and prints the failure.
'''
# Compare the absolute path names, sorted.
asserted = sorted([os.path.abspath(i) for i in assert_output_files])
actual = sorted([
os.path.abspath(os.path.join(self.output_directory, i.GetFilename()))
for i in self.res.GetOutputFiles()])
if asserted != actual:
missing = list(set(actual) - set(asserted))
extra = list(set(asserted) - set(actual))
error = '''Asserted file list does not match.
Expected output files:
%s
Actual output files:
%s
Missing output files:
%s
Extra output files:
%s
'''
print error % ('\n'.join(asserted), '\n'.join(actual), '\n'.join(missing),
'\n'.join(extra))
return False
return True | [
"def",
"CheckAssertedOutputFiles",
"(",
"self",
",",
"assert_output_files",
")",
":",
"# Compare the absolute path names, sorted.",
"asserted",
"=",
"sorted",
"(",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"i",
")",
"for",
"i",
"in",
"assert_output_files",
"]",
")",
"actual",
"=",
"sorted",
"(",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output_directory",
",",
"i",
".",
"GetFilename",
"(",
")",
")",
")",
"for",
"i",
"in",
"self",
".",
"res",
".",
"GetOutputFiles",
"(",
")",
"]",
")",
"if",
"asserted",
"!=",
"actual",
":",
"missing",
"=",
"list",
"(",
"set",
"(",
"actual",
")",
"-",
"set",
"(",
"asserted",
")",
")",
"extra",
"=",
"list",
"(",
"set",
"(",
"asserted",
")",
"-",
"set",
"(",
"actual",
")",
")",
"error",
"=",
"'''Asserted file list does not match.\n\nExpected output files:\n%s\nActual output files:\n%s\nMissing output files:\n%s\nExtra output files:\n%s\n'''",
"print",
"error",
"%",
"(",
"'\\n'",
".",
"join",
"(",
"asserted",
")",
",",
"'\\n'",
".",
"join",
"(",
"actual",
")",
",",
"'\\n'",
".",
"join",
"(",
"missing",
")",
",",
"'\\n'",
".",
"join",
"(",
"extra",
")",
")",
"return",
"False",
"return",
"True"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/tool/build.py#L430-L459 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | FWCore/ParameterSet/python/Types.py | python | InputTag.value | (self) | return self.configValue() | Return the string rep | Return the string rep | [
"Return",
"the",
"string",
"rep"
] | def value(self):
"Return the string rep"
return self.configValue() | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
".",
"configValue",
"(",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/ParameterSet/python/Types.py#L682-L684 | |
immunant/selfrando | fe47bc08cf420edfdad44a967b601f29ebfed4d9 | src/RandoLib/posix/bionic/gensyscalls.py | python | count_arm_param_registers | (params) | return count | This function is used to count the number of register used
to pass parameters when invoking an ARM system call.
This is because the ARM EABI mandates that 64-bit quantities
must be passed in an even+odd register pair. So, for example,
something like:
foo(int fd, off64_t pos)
would actually need 4 registers:
r0 -> int
r1 -> unused
r2-r3 -> pos | This function is used to count the number of register used
to pass parameters when invoking an ARM system call.
This is because the ARM EABI mandates that 64-bit quantities
must be passed in an even+odd register pair. So, for example,
something like: | [
"This",
"function",
"is",
"used",
"to",
"count",
"the",
"number",
"of",
"register",
"used",
"to",
"pass",
"parameters",
"when",
"invoking",
"an",
"ARM",
"system",
"call",
".",
"This",
"is",
"because",
"the",
"ARM",
"EABI",
"mandates",
"that",
"64",
"-",
"bit",
"quantities",
"must",
"be",
"passed",
"in",
"an",
"even",
"+",
"odd",
"register",
"pair",
".",
"So",
"for",
"example",
"something",
"like",
":"
] | def count_arm_param_registers(params):
"""This function is used to count the number of register used
to pass parameters when invoking an ARM system call.
This is because the ARM EABI mandates that 64-bit quantities
must be passed in an even+odd register pair. So, for example,
something like:
foo(int fd, off64_t pos)
would actually need 4 registers:
r0 -> int
r1 -> unused
r2-r3 -> pos
"""
count = 0
for param in params:
if param_uses_64bits(param):
if (count & 1) != 0:
count += 1
count += 2
else:
count += 1
return count | [
"def",
"count_arm_param_registers",
"(",
"params",
")",
":",
"count",
"=",
"0",
"for",
"param",
"in",
"params",
":",
"if",
"param_uses_64bits",
"(",
"param",
")",
":",
"if",
"(",
"count",
"&",
"1",
")",
"!=",
"0",
":",
"count",
"+=",
"1",
"count",
"+=",
"2",
"else",
":",
"count",
"+=",
"1",
"return",
"count"
] | https://github.com/immunant/selfrando/blob/fe47bc08cf420edfdad44a967b601f29ebfed4d9/src/RandoLib/posix/bionic/gensyscalls.py#L181-L203 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/command/easy_install.py | python | easy_install.create_home_path | (self) | Create directories under ~. | Create directories under ~. | [
"Create",
"directories",
"under",
"~",
"."
] | def create_home_path(self):
"""Create directories under ~."""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for name, path in self.config_vars.items():
if path.startswith(home) and not os.path.isdir(path):
self.debug_print("os.makedirs('%s', 0o700)" % path)
os.makedirs(path, 0o700) | [
"def",
"create_home_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"user",
":",
"return",
"home",
"=",
"convert_path",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
")",
"for",
"name",
",",
"path",
"in",
"self",
".",
"config_vars",
".",
"items",
"(",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"home",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"self",
".",
"debug_print",
"(",
"\"os.makedirs('%s', 0o700)\"",
"%",
"path",
")",
"os",
".",
"makedirs",
"(",
"path",
",",
"0o700",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/command/easy_install.py#L1321-L1329 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-zeromq/examples/python/gui.py | python | parse_args | () | return args | Options parser. | Options parser. | [
"Options",
"parser",
"."
] | def parse_args():
"""Options parser."""
parser = ArgumentParser()
parser.add_argument("-s", "--servername", default="localhost",
help="Server hostname")
parser.add_argument("-c", "--clientname", default="localhost",
help="Server hostname")
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"-s\"",
",",
"\"--servername\"",
",",
"default",
"=",
"\"localhost\"",
",",
"help",
"=",
"\"Server hostname\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-c\"",
",",
"\"--clientname\"",
",",
"default",
"=",
"\"localhost\"",
",",
"help",
"=",
"\"Server hostname\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"return",
"args"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-zeromq/examples/python/gui.py#L148-L156 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/xml/dom/expatbuilder.py | python | ExpatBuilder._setup_subset | (self, buffer) | Load the internal subset if there might be one. | Load the internal subset if there might be one. | [
"Load",
"the",
"internal",
"subset",
"if",
"there",
"might",
"be",
"one",
"."
] | def _setup_subset(self, buffer):
"""Load the internal subset if there might be one."""
if self.document.doctype:
extractor = InternalSubsetExtractor()
extractor.parseString(buffer)
subset = extractor.getSubset()
self.document.doctype.internalSubset = subset | [
"def",
"_setup_subset",
"(",
"self",
",",
"buffer",
")",
":",
"if",
"self",
".",
"document",
".",
"doctype",
":",
"extractor",
"=",
"InternalSubsetExtractor",
"(",
")",
"extractor",
".",
"parseString",
"(",
"buffer",
")",
"subset",
"=",
"extractor",
".",
"getSubset",
"(",
")",
"self",
".",
"document",
".",
"doctype",
".",
"internalSubset",
"=",
"subset"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/dom/expatbuilder.py#L232-L238 | ||
ideawu/ssdb | f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4 | deps/cpy/antlr3/tree.py | python | CommonTreeAdaptor.getToken | (self, t) | return None | What is the Token associated with this node? If
you are not using CommonTree, then you must
override this in your own adaptor. | What is the Token associated with this node? If
you are not using CommonTree, then you must
override this in your own adaptor. | [
"What",
"is",
"the",
"Token",
"associated",
"with",
"this",
"node?",
"If",
"you",
"are",
"not",
"using",
"CommonTree",
"then",
"you",
"must",
"override",
"this",
"in",
"your",
"own",
"adaptor",
"."
] | def getToken(self, t):
"""
What is the Token associated with this node? If
you are not using CommonTree, then you must
override this in your own adaptor.
"""
if isinstance(t, CommonTree):
return t.getToken()
return None | [
"def",
"getToken",
"(",
"self",
",",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"CommonTree",
")",
":",
"return",
"t",
".",
"getToken",
"(",
")",
"return",
"None"
] | https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/tree.py#L1486-L1496 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/msvs.py | python | _NormalizedSource | (source) | return source | Normalize the path.
But not if that gets rid of a variable, as this may expand to something
larger than one directory.
Arguments:
source: The path to be normalize.d
Returns:
The normalized path. | Normalize the path. | [
"Normalize",
"the",
"path",
"."
] | def _NormalizedSource(source):
"""Normalize the path.
But not if that gets rid of a variable, as this may expand to something
larger than one directory.
Arguments:
source: The path to be normalize.d
Returns:
The normalized path.
"""
normalized = os.path.normpath(source)
if source.count('$') == normalized.count('$'):
source = normalized
return source | [
"def",
"_NormalizedSource",
"(",
"source",
")",
":",
"normalized",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"source",
")",
"if",
"source",
".",
"count",
"(",
"'$'",
")",
"==",
"normalized",
".",
"count",
"(",
"'$'",
")",
":",
"source",
"=",
"normalized",
"return",
"source"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/msvs.py#L139-L154 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/protobuf/python/google/protobuf/internal/decoder.py | python | _SkipLengthDelimited | (buffer, pos, end) | return pos | Skip a length-delimited value. Returns the new position. | Skip a length-delimited value. Returns the new position. | [
"Skip",
"a",
"length",
"-",
"delimited",
"value",
".",
"Returns",
"the",
"new",
"position",
"."
] | def _SkipLengthDelimited(buffer, pos, end):
"""Skip a length-delimited value. Returns the new position."""
(size, pos) = _DecodeVarint(buffer, pos)
pos += size
if pos > end:
raise _DecodeError('Truncated message.')
return pos | [
"def",
"_SkipLengthDelimited",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"(",
"size",
",",
"pos",
")",
"=",
"_DecodeVarint",
"(",
"buffer",
",",
"pos",
")",
"pos",
"+=",
"size",
"if",
"pos",
">",
"end",
":",
"raise",
"_DecodeError",
"(",
"'Truncated message.'",
")",
"return",
"pos"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/google/protobuf/internal/decoder.py#L644-L651 | |
Kinovarobotics/kinova-ros | 93f66822ec073827eac5de59ebc2a3c5f06bf17f | kinova_demo/nodes/kinova_demo/joints_action_client.py | python | argumentParser | (argument) | return args_ | Argument parser | Argument parser | [
"Argument",
"parser"
] | def argumentParser(argument):
""" Argument parser """
parser = argparse.ArgumentParser(description='Drive robot joint to command position')
parser.add_argument('kinova_robotType', metavar='kinova_robotType', type=str, default='j2n6a300',
help='kinova_RobotType is in format of: [{j|m|r|c}{1|2}{s|n}{4|6|7}{s|a}{2|3}{0}{0}]. eg: j2n6a300 refers to jaco v2 6DOF assistive 3fingers. Please be noted that not all options are valided for different robot types.')
parser.add_argument('unit', metavar='unit', type=str, nargs='?', default='degree',
choices={'degree', 'radian'},
help='Unit of joiint motion command, in degree, radian')
parser.add_argument('joint_value', nargs='*', type=float, help='joint values, length equals to number of joints.')
parser.add_argument('-r', '--relative', action='store_true',
help='the input values are relative values to current position.')
parser.add_argument('-v', '--verbose', action='store_true',
help='display joint values in alternative convention(degree or radian)')
# parser.add_argument('-f', action='store_true', help='assign finger values from a file')
args_ = parser.parse_args(argument)
return args_ | [
"def",
"argumentParser",
"(",
"argument",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Drive robot joint to command position'",
")",
"parser",
".",
"add_argument",
"(",
"'kinova_robotType'",
",",
"metavar",
"=",
"'kinova_robotType'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'j2n6a300'",
",",
"help",
"=",
"'kinova_RobotType is in format of: [{j|m|r|c}{1|2}{s|n}{4|6|7}{s|a}{2|3}{0}{0}]. eg: j2n6a300 refers to jaco v2 6DOF assistive 3fingers. Please be noted that not all options are valided for different robot types.'",
")",
"parser",
".",
"add_argument",
"(",
"'unit'",
",",
"metavar",
"=",
"'unit'",
",",
"type",
"=",
"str",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"'degree'",
",",
"choices",
"=",
"{",
"'degree'",
",",
"'radian'",
"}",
",",
"help",
"=",
"'Unit of joiint motion command, in degree, radian'",
")",
"parser",
".",
"add_argument",
"(",
"'joint_value'",
",",
"nargs",
"=",
"'*'",
",",
"type",
"=",
"float",
",",
"help",
"=",
"'joint values, length equals to number of joints.'",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--relative'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'the input values are relative values to current position.'",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'display joint values in alternative convention(degree or radian)'",
")",
"# parser.add_argument('-f', action='store_true', help='assign finger values from a file')",
"args_",
"=",
"parser",
".",
"parse_args",
"(",
"argument",
")",
"return",
"args_"
] | https://github.com/Kinovarobotics/kinova-ros/blob/93f66822ec073827eac5de59ebc2a3c5f06bf17f/kinova_demo/nodes/kinova_demo/joints_action_client.py#L71-L87 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/apiclient/googleapiclient/channel.py | python | Channel.__init__ | (self, type, id, token, address, expiration=None,
params=None, resource_id="", resource_uri="") | Create a new Channel.
In user code, this Channel constructor will not typically be called
manually since there are functions for creating channels for each specific
type with a more customized set of arguments to pass.
Args:
type: str, The type of delivery mechanism used by this channel. For
example, 'web_hook'.
id: str, A UUID for the channel.
token: str, An arbitrary string associated with the channel that
is delivered to the target address with each event delivered
over this channel.
address: str, The address of the receiving entity where events are
delivered. Specific to the channel type.
expiration: int, The time, in milliseconds from the epoch, when this
channel will expire.
params: dict, A dictionary of string to string, with additional parameters
controlling delivery channel behavior.
resource_id: str, An opaque id that identifies the resource that is
being watched. Stable across different API versions.
resource_uri: str, The canonicalized ID of the watched resource. | Create a new Channel. | [
"Create",
"a",
"new",
"Channel",
"."
] | def __init__(self, type, id, token, address, expiration=None,
params=None, resource_id="", resource_uri=""):
"""Create a new Channel.
In user code, this Channel constructor will not typically be called
manually since there are functions for creating channels for each specific
type with a more customized set of arguments to pass.
Args:
type: str, The type of delivery mechanism used by this channel. For
example, 'web_hook'.
id: str, A UUID for the channel.
token: str, An arbitrary string associated with the channel that
is delivered to the target address with each event delivered
over this channel.
address: str, The address of the receiving entity where events are
delivered. Specific to the channel type.
expiration: int, The time, in milliseconds from the epoch, when this
channel will expire.
params: dict, A dictionary of string to string, with additional parameters
controlling delivery channel behavior.
resource_id: str, An opaque id that identifies the resource that is
being watched. Stable across different API versions.
resource_uri: str, The canonicalized ID of the watched resource.
"""
self.type = type
self.id = id
self.token = token
self.address = address
self.expiration = expiration
self.params = params
self.resource_id = resource_id
self.resource_uri = resource_uri | [
"def",
"__init__",
"(",
"self",
",",
"type",
",",
"id",
",",
"token",
",",
"address",
",",
"expiration",
"=",
"None",
",",
"params",
"=",
"None",
",",
"resource_id",
"=",
"\"\"",
",",
"resource_uri",
"=",
"\"\"",
")",
":",
"self",
".",
"type",
"=",
"type",
"self",
".",
"id",
"=",
"id",
"self",
".",
"token",
"=",
"token",
"self",
".",
"address",
"=",
"address",
"self",
".",
"expiration",
"=",
"expiration",
"self",
".",
"params",
"=",
"params",
"self",
".",
"resource_id",
"=",
"resource_id",
"self",
".",
"resource_uri",
"=",
"resource_uri"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/apiclient/googleapiclient/channel.py#L153-L185 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/dtypes.py | python | DType.max | (self) | Returns the maximum representable value in this data type.
Raises:
TypeError: if this is a non-numeric, unordered, or quantized type. | Returns the maximum representable value in this data type. | [
"Returns",
"the",
"maximum",
"representable",
"value",
"in",
"this",
"data",
"type",
"."
] | def max(self):
"""Returns the maximum representable value in this data type.
Raises:
TypeError: if this is a non-numeric, unordered, or quantized type.
"""
if (self.is_quantized or self.base_dtype in
(bool, string, complex64, complex128)):
raise TypeError("Cannot find maximum value of %s." % self)
# there is no simple way to get the max value of a dtype, we have to check
# float and int types separately
try:
return np.finfo(self.as_numpy_dtype()).max
except: # bare except as possible raises by finfo not documented
try:
return np.iinfo(self.as_numpy_dtype()).max
except:
raise TypeError("Cannot find maximum value of %s." % self) | [
"def",
"max",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"is_quantized",
"or",
"self",
".",
"base_dtype",
"in",
"(",
"bool",
",",
"string",
",",
"complex64",
",",
"complex128",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Cannot find maximum value of %s.\"",
"%",
"self",
")",
"# there is no simple way to get the max value of a dtype, we have to check",
"# float and int types separately",
"try",
":",
"return",
"np",
".",
"finfo",
"(",
"self",
".",
"as_numpy_dtype",
"(",
")",
")",
".",
"max",
"except",
":",
"# bare except as possible raises by finfo not documented",
"try",
":",
"return",
"np",
".",
"iinfo",
"(",
"self",
".",
"as_numpy_dtype",
"(",
")",
")",
".",
"max",
"except",
":",
"raise",
"TypeError",
"(",
"\"Cannot find maximum value of %s.\"",
"%",
"self",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/dtypes.py#L200-L219 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/ops/dataset_ops.py | python | _VariantTracker.__init__ | (self, variant_tensor, resource_creator) | Record that `variant_tensor` is associated with `resource_creator`.
Args:
variant_tensor: The variant-dtype Tensor associated with the Dataset. This
Tensor will be a captured input to functions which use the Dataset, and
is used by saving code to identify the corresponding _VariantTracker.
resource_creator: A zero-argument function which creates a new
variant-dtype Tensor. This function will be included in SavedModels and
run to re-create the Dataset's variant Tensor on restore. | Record that `variant_tensor` is associated with `resource_creator`. | [
"Record",
"that",
"variant_tensor",
"is",
"associated",
"with",
"resource_creator",
"."
] | def __init__(self, variant_tensor, resource_creator):
"""Record that `variant_tensor` is associated with `resource_creator`.
Args:
variant_tensor: The variant-dtype Tensor associated with the Dataset. This
Tensor will be a captured input to functions which use the Dataset, and
is used by saving code to identify the corresponding _VariantTracker.
resource_creator: A zero-argument function which creates a new
variant-dtype Tensor. This function will be included in SavedModels and
run to re-create the Dataset's variant Tensor on restore.
"""
super(_VariantTracker, self).__init__(device="CPU")
self._resource_handle = variant_tensor
self._create_resource = resource_creator | [
"def",
"__init__",
"(",
"self",
",",
"variant_tensor",
",",
"resource_creator",
")",
":",
"super",
"(",
"_VariantTracker",
",",
"self",
")",
".",
"__init__",
"(",
"device",
"=",
"\"CPU\"",
")",
"self",
".",
"_resource_handle",
"=",
"variant_tensor",
"self",
".",
"_create_resource",
"=",
"resource_creator"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/ops/dataset_ops.py#L3203-L3216 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py | python | list_public_methods | (obj) | return [member for member in dir(obj)
if not member.startswith('_') and
callable(getattr(obj, member))] | Returns a list of attribute strings, found in the specified
object, which represent callable attributes | Returns a list of attribute strings, found in the specified
object, which represent callable attributes | [
"Returns",
"a",
"list",
"of",
"attribute",
"strings",
"found",
"in",
"the",
"specified",
"object",
"which",
"represent",
"callable",
"attributes"
] | def list_public_methods(obj):
"""Returns a list of attribute strings, found in the specified
object, which represent callable attributes"""
return [member for member in dir(obj)
if not member.startswith('_') and
callable(getattr(obj, member))] | [
"def",
"list_public_methods",
"(",
"obj",
")",
":",
"return",
"[",
"member",
"for",
"member",
"in",
"dir",
"(",
"obj",
")",
"if",
"not",
"member",
".",
"startswith",
"(",
"'_'",
")",
"and",
"callable",
"(",
"getattr",
"(",
"obj",
",",
"member",
")",
")",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py#L148-L154 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | NativePixelData.__init__ | (self, *args) | __init__(self, Bitmap bmp) -> NativePixelData
__init__(self, Bitmap bmp, Rect rect) -> NativePixelData
__init__(self, Bitmap bmp, Point pt, Size sz) -> NativePixelData | __init__(self, Bitmap bmp) -> NativePixelData
__init__(self, Bitmap bmp, Rect rect) -> NativePixelData
__init__(self, Bitmap bmp, Point pt, Size sz) -> NativePixelData | [
"__init__",
"(",
"self",
"Bitmap",
"bmp",
")",
"-",
">",
"NativePixelData",
"__init__",
"(",
"self",
"Bitmap",
"bmp",
"Rect",
"rect",
")",
"-",
">",
"NativePixelData",
"__init__",
"(",
"self",
"Bitmap",
"bmp",
"Point",
"pt",
"Size",
"sz",
")",
"-",
">",
"NativePixelData"
] | def __init__(self, *args):
"""
__init__(self, Bitmap bmp) -> NativePixelData
__init__(self, Bitmap bmp, Rect rect) -> NativePixelData
__init__(self, Bitmap bmp, Point pt, Size sz) -> NativePixelData
"""
_gdi_.NativePixelData_swiginit(self,_gdi_.new_NativePixelData(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_gdi_",
".",
"NativePixelData_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_NativePixelData",
"(",
"*",
"args",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1046-L1052 | ||
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/faster-rcnn/lib/datasets/pascal_voc.py | python | pascal_voc._load_image_set_index | (self) | return image_index | Load the indexes listed in this dataset's image set file. | Load the indexes listed in this dataset's image set file. | [
"Load",
"the",
"indexes",
"listed",
"in",
"this",
"dataset",
"s",
"image",
"set",
"file",
"."
] | def _load_image_set_index(self):
"""
Load the indexes listed in this dataset's image set file.
"""
# Example path to image set file:
# self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt
image_set_file = os.path.join(self._data_path, 'ImageSets', 'Main',
self._image_set + '.txt')
assert os.path.exists(image_set_file), \
'Path does not exist: {}'.format(image_set_file)
with open(image_set_file) as f:
image_index = [x.strip() for x in f.readlines()]
return image_index | [
"def",
"_load_image_set_index",
"(",
"self",
")",
":",
"# Example path to image set file:",
"# self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt",
"image_set_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_data_path",
",",
"'ImageSets'",
",",
"'Main'",
",",
"self",
".",
"_image_set",
"+",
"'.txt'",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"image_set_file",
")",
",",
"'Path does not exist: {}'",
".",
"format",
"(",
"image_set_file",
")",
"with",
"open",
"(",
"image_set_file",
")",
"as",
"f",
":",
"image_index",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"f",
".",
"readlines",
"(",
")",
"]",
"return",
"image_index"
] | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/faster-rcnn/lib/datasets/pascal_voc.py#L73-L85 | |
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/busco/GenomeAnalysis.py | python | GenomeAnalysis._check_tool_dependencies | (self) | check dependencies on tools
:raises SystemExit: if a Tool is not available | check dependencies on tools
:raises SystemExit: if a Tool is not available | [
"check",
"dependencies",
"on",
"tools",
":",
"raises",
"SystemExit",
":",
"if",
"a",
"Tool",
"is",
"not",
"available"
] | def _check_tool_dependencies(self):
"""
check dependencies on tools
:raises SystemExit: if a Tool is not available
"""
super(GenomeAnalysis, self)._check_tool_dependencies()
# check 'augustus' command availability
if not Tool.check_tool_available('augustus', self._params):
BuscoAnalysis._logger.error(
'\"augustus\" is not accessible, check its path in the config.ini.default file (do not include the commmand '
'in the path !), and '
'add it to your $PATH environmental variable (the entry in config.ini.default is not sufficient '
'for retraining to work properly)')
raise SystemExit
# check availability augustus - related commands
if not Tool.check_tool_available('etraining', self._params):
BuscoAnalysis._logger.error(
'\"etraining\" is not accessible, check its path in the config.ini.default file(do not include the commmand '
'in the path !), and '
'add it to your $PATH environmental variable (the entry in config.ini.default is not sufficient '
'for retraining to work properly)')
raise SystemExit
if not Tool.check_tool_available('gff2gbSmallDNA.pl', self._params):
BuscoAnalysis._logger.error(
'Impossible to locate the required script gff2gbSmallDNA.pl. '
'Check that you properly declared the path to augustus scripts folder in your '
'config.ini.default file (do not include the script name '
'in the path !)')
raise SystemExit
if not Tool.check_tool_available('new_species.pl', self._params):
BuscoAnalysis._logger.error(
'Impossible to locate the required script new_species.pl. '
'Check that you properly declared the path to augustus scripts folder in your '
'config.ini.default file (do not include the script name '
'in the path !)')
raise SystemExit
if not Tool.check_tool_available('optimize_augustus.pl', self._params):
BuscoAnalysis._logger.error(
'Impossible to locate the required script optimize_augustus.pl. '
'Check that you properly declared the path to augustus scripts folder in your '
'config.ini.default file (do not include the script name '
'in the path !)')
raise SystemExit | [
"def",
"_check_tool_dependencies",
"(",
"self",
")",
":",
"super",
"(",
"GenomeAnalysis",
",",
"self",
")",
".",
"_check_tool_dependencies",
"(",
")",
"# check 'augustus' command availability",
"if",
"not",
"Tool",
".",
"check_tool_available",
"(",
"'augustus'",
",",
"self",
".",
"_params",
")",
":",
"BuscoAnalysis",
".",
"_logger",
".",
"error",
"(",
"'\\\"augustus\\\" is not accessible, check its path in the config.ini.default file (do not include the commmand '",
"'in the path !), and '",
"'add it to your $PATH environmental variable (the entry in config.ini.default is not sufficient '",
"'for retraining to work properly)'",
")",
"raise",
"SystemExit",
"# check availability augustus - related commands",
"if",
"not",
"Tool",
".",
"check_tool_available",
"(",
"'etraining'",
",",
"self",
".",
"_params",
")",
":",
"BuscoAnalysis",
".",
"_logger",
".",
"error",
"(",
"'\\\"etraining\\\" is not accessible, check its path in the config.ini.default file(do not include the commmand '",
"'in the path !), and '",
"'add it to your $PATH environmental variable (the entry in config.ini.default is not sufficient '",
"'for retraining to work properly)'",
")",
"raise",
"SystemExit",
"if",
"not",
"Tool",
".",
"check_tool_available",
"(",
"'gff2gbSmallDNA.pl'",
",",
"self",
".",
"_params",
")",
":",
"BuscoAnalysis",
".",
"_logger",
".",
"error",
"(",
"'Impossible to locate the required script gff2gbSmallDNA.pl. '",
"'Check that you properly declared the path to augustus scripts folder in your '",
"'config.ini.default file (do not include the script name '",
"'in the path !)'",
")",
"raise",
"SystemExit",
"if",
"not",
"Tool",
".",
"check_tool_available",
"(",
"'new_species.pl'",
",",
"self",
".",
"_params",
")",
":",
"BuscoAnalysis",
".",
"_logger",
".",
"error",
"(",
"'Impossible to locate the required script new_species.pl. '",
"'Check that you properly declared the path to augustus scripts folder in your '",
"'config.ini.default file (do not include the script name '",
"'in the path !)'",
")",
"raise",
"SystemExit",
"if",
"not",
"Tool",
".",
"check_tool_available",
"(",
"'optimize_augustus.pl'",
",",
"self",
".",
"_params",
")",
":",
"BuscoAnalysis",
".",
"_logger",
".",
"error",
"(",
"'Impossible to locate the required script optimize_augustus.pl. '",
"'Check that you properly declared the path to augustus scripts folder in your '",
"'config.ini.default file (do not include the script name '",
"'in the path !)'",
")",
"raise",
"SystemExit"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/busco/GenomeAnalysis.py#L1099-L1145 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/ftplib.py | python | FTP.retrlines | (self, cmd, callback = None) | return self.voidresp() | Retrieve data in line mode. A new port is created for you.
Args:
cmd: A RETR, LIST, NLST, or MLSD command.
callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped.
[default: print_line()]
Returns:
The response code. | Retrieve data in line mode. A new port is created for you. | [
"Retrieve",
"data",
"in",
"line",
"mode",
".",
"A",
"new",
"port",
"is",
"created",
"for",
"you",
"."
] | def retrlines(self, cmd, callback = None):
"""Retrieve data in line mode. A new port is created for you.
Args:
cmd: A RETR, LIST, NLST, or MLSD command.
callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped.
[default: print_line()]
Returns:
The response code.
"""
if callback is None: callback = print_line
resp = self.sendcmd('TYPE A')
conn = self.transfercmd(cmd)
fp = conn.makefile('rb')
while 1:
line = fp.readline()
if self.debugging > 2: print '*retr*', repr(line)
if not line:
break
if line[-2:] == CRLF:
line = line[:-2]
elif line[-1:] == '\n':
line = line[:-1]
callback(line)
fp.close()
conn.close()
return self.voidresp() | [
"def",
"retrlines",
"(",
"self",
",",
"cmd",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
"is",
"None",
":",
"callback",
"=",
"print_line",
"resp",
"=",
"self",
".",
"sendcmd",
"(",
"'TYPE A'",
")",
"conn",
"=",
"self",
".",
"transfercmd",
"(",
"cmd",
")",
"fp",
"=",
"conn",
".",
"makefile",
"(",
"'rb'",
")",
"while",
"1",
":",
"line",
"=",
"fp",
".",
"readline",
"(",
")",
"if",
"self",
".",
"debugging",
">",
"2",
":",
"print",
"'*retr*'",
",",
"repr",
"(",
"line",
")",
"if",
"not",
"line",
":",
"break",
"if",
"line",
"[",
"-",
"2",
":",
"]",
"==",
"CRLF",
":",
"line",
"=",
"line",
"[",
":",
"-",
"2",
"]",
"elif",
"line",
"[",
"-",
"1",
":",
"]",
"==",
"'\\n'",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"callback",
"(",
"line",
")",
"fp",
".",
"close",
"(",
")",
"conn",
".",
"close",
"(",
")",
"return",
"self",
".",
"voidresp",
"(",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ftplib.py#L403-L431 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/pylib/utils/emulator.py | python | Emulator._DeleteAVD | (self) | Delete the AVD of this emulator. | Delete the AVD of this emulator. | [
"Delete",
"the",
"AVD",
"of",
"this",
"emulator",
"."
] | def _DeleteAVD(self):
"""Delete the AVD of this emulator."""
avd_command = [
self.android,
'--silent',
'delete',
'avd',
'--name', self.avd_name,
]
logging.info('Delete AVD command: %s', ' '.join(avd_command))
cmd_helper.RunCmd(avd_command) | [
"def",
"_DeleteAVD",
"(",
"self",
")",
":",
"avd_command",
"=",
"[",
"self",
".",
"android",
",",
"'--silent'",
",",
"'delete'",
",",
"'avd'",
",",
"'--name'",
",",
"self",
".",
"avd_name",
",",
"]",
"logging",
".",
"info",
"(",
"'Delete AVD command: %s'",
",",
"' '",
".",
"join",
"(",
"avd_command",
")",
")",
"cmd_helper",
".",
"RunCmd",
"(",
"avd_command",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/utils/emulator.py#L373-L383 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Menu.AppendItem | (*args, **kwargs) | return _core_.Menu_AppendItem(*args, **kwargs) | AppendItem(self, MenuItem item) -> MenuItem | AppendItem(self, MenuItem item) -> MenuItem | [
"AppendItem",
"(",
"self",
"MenuItem",
"item",
")",
"-",
">",
"MenuItem"
] | def AppendItem(*args, **kwargs):
"""AppendItem(self, MenuItem item) -> MenuItem"""
return _core_.Menu_AppendItem(*args, **kwargs) | [
"def",
"AppendItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Menu_AppendItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12029-L12031 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/tools/stats-viewer.py | python | ChromeCounter.__init__ | (self, data, name_offset, value_offset) | Create a new instance.
Args:
data: the shared data access object containing the counter
name_offset: the byte offset of the start of this counter's name
value_offset: the byte offset of the start of this counter's value | Create a new instance. | [
"Create",
"a",
"new",
"instance",
"."
] | def __init__(self, data, name_offset, value_offset):
"""Create a new instance.
Args:
data: the shared data access object containing the counter
name_offset: the byte offset of the start of this counter's name
value_offset: the byte offset of the start of this counter's value
"""
self.data = data
self.name_offset = name_offset
self.value_offset = value_offset | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"name_offset",
",",
"value_offset",
")",
":",
"self",
".",
"data",
"=",
"data",
"self",
".",
"name_offset",
"=",
"name_offset",
"self",
".",
"value_offset",
"=",
"value_offset"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/tools/stats-viewer.py#L386-L396 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/platform.py | python | python_version | () | return _sys_version()[1] | Returns the Python version as string 'major.minor.patchlevel'
Note that unlike the Python sys.version, the returned value
will always include the patchlevel (it defaults to 0). | Returns the Python version as string 'major.minor.patchlevel' | [
"Returns",
"the",
"Python",
"version",
"as",
"string",
"major",
".",
"minor",
".",
"patchlevel"
] | def python_version():
""" Returns the Python version as string 'major.minor.patchlevel'
Note that unlike the Python sys.version, the returned value
will always include the patchlevel (it defaults to 0).
"""
return _sys_version()[1] | [
"def",
"python_version",
"(",
")",
":",
"return",
"_sys_version",
"(",
")",
"[",
"1",
"]"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/platform.py#L1487-L1495 | |
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | scripts/cpp_lint.py | python | _CppLintState.SetCountingStyle | (self, counting_style) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style | [
"def",
"SetCountingStyle",
"(",
"self",
",",
"counting_style",
")",
":",
"self",
".",
"counting",
"=",
"counting_style"
] | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/cpp_lint.py#L713-L715 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/email/_header_value_parser.py | python | get_section | (value) | return section, value | '*' digits
The formal BNF is more complicated because leading 0s are not allowed. We
check for that and add a defect. We also assume no CFWS is allowed between
the '*' and the digits, though the RFC is not crystal clear on that.
The caller should already have dealt with leading CFWS. | '*' digits | [
"*",
"digits"
] | def get_section(value):
""" '*' digits
The formal BNF is more complicated because leading 0s are not allowed. We
check for that and add a defect. We also assume no CFWS is allowed between
the '*' and the digits, though the RFC is not crystal clear on that.
The caller should already have dealt with leading CFWS.
"""
section = Section()
if not value or value[0] != '*':
raise errors.HeaderParseError("Expected section but found {}".format(
value))
section.append(ValueTerminal('*', 'section-marker'))
value = value[1:]
if not value or not value[0].isdigit():
raise errors.HeaderParseError("Expected section number but "
"found {}".format(value))
digits = ''
while value and value[0].isdigit():
digits += value[0]
value = value[1:]
if digits[0] == '0' and digits != '0':
section.defects.append(errors.InvalidHeaderError(
"section number has an invalid leading 0"))
section.number = int(digits)
section.append(ValueTerminal(digits, 'digits'))
return section, value | [
"def",
"get_section",
"(",
"value",
")",
":",
"section",
"=",
"Section",
"(",
")",
"if",
"not",
"value",
"or",
"value",
"[",
"0",
"]",
"!=",
"'*'",
":",
"raise",
"errors",
".",
"HeaderParseError",
"(",
"\"Expected section but found {}\"",
".",
"format",
"(",
"value",
")",
")",
"section",
".",
"append",
"(",
"ValueTerminal",
"(",
"'*'",
",",
"'section-marker'",
")",
")",
"value",
"=",
"value",
"[",
"1",
":",
"]",
"if",
"not",
"value",
"or",
"not",
"value",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"raise",
"errors",
".",
"HeaderParseError",
"(",
"\"Expected section number but \"",
"\"found {}\"",
".",
"format",
"(",
"value",
")",
")",
"digits",
"=",
"''",
"while",
"value",
"and",
"value",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"digits",
"+=",
"value",
"[",
"0",
"]",
"value",
"=",
"value",
"[",
"1",
":",
"]",
"if",
"digits",
"[",
"0",
"]",
"==",
"'0'",
"and",
"digits",
"!=",
"'0'",
":",
"section",
".",
"defects",
".",
"append",
"(",
"errors",
".",
"InvalidHeaderError",
"(",
"\"section number has an invalid leading 0\"",
")",
")",
"section",
".",
"number",
"=",
"int",
"(",
"digits",
")",
"section",
".",
"append",
"(",
"ValueTerminal",
"(",
"digits",
",",
"'digits'",
")",
")",
"return",
"section",
",",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/_header_value_parser.py#L2240-L2267 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | external/tools/build/v2/build/property.py | python | __validate1 | (property) | Exit with error if property is not valid. | Exit with error if property is not valid. | [
"Exit",
"with",
"error",
"if",
"property",
"is",
"not",
"valid",
"."
] | def __validate1 (property):
""" Exit with error if property is not valid.
"""
msg = None
if not property.feature().free():
feature.validate_value_string (property.feature(), property.value()) | [
"def",
"__validate1",
"(",
"property",
")",
":",
"msg",
"=",
"None",
"if",
"not",
"property",
".",
"feature",
"(",
")",
".",
"free",
"(",
")",
":",
"feature",
".",
"validate_value_string",
"(",
"property",
".",
"feature",
"(",
")",
",",
"property",
".",
"value",
"(",
")",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/build/property.py#L339-L345 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/delete-columns-to-make-sorted-iii.py | python | Solution.minDeletionSize | (self, A) | return len(A[0]) - max(dp) | :type A: List[str]
:rtype: int | :type A: List[str]
:rtype: int | [
":",
"type",
"A",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"int"
] | def minDeletionSize(self, A):
"""
:type A: List[str]
:rtype: int
"""
dp = [1] * len(A[0])
for j in xrange(1, len(A[0])):
for i in xrange(j):
if all(A[k][i] <= A[k][j] for k in xrange(len(A))):
dp[j] = max(dp[j], dp[i]+1)
return len(A[0]) - max(dp) | [
"def",
"minDeletionSize",
"(",
"self",
",",
"A",
")",
":",
"dp",
"=",
"[",
"1",
"]",
"*",
"len",
"(",
"A",
"[",
"0",
"]",
")",
"for",
"j",
"in",
"xrange",
"(",
"1",
",",
"len",
"(",
"A",
"[",
"0",
"]",
")",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"j",
")",
":",
"if",
"all",
"(",
"A",
"[",
"k",
"]",
"[",
"i",
"]",
"<=",
"A",
"[",
"k",
"]",
"[",
"j",
"]",
"for",
"k",
"in",
"xrange",
"(",
"len",
"(",
"A",
")",
")",
")",
":",
"dp",
"[",
"j",
"]",
"=",
"max",
"(",
"dp",
"[",
"j",
"]",
",",
"dp",
"[",
"i",
"]",
"+",
"1",
")",
"return",
"len",
"(",
"A",
"[",
"0",
"]",
")",
"-",
"max",
"(",
"dp",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/delete-columns-to-make-sorted-iii.py#L5-L15 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/bindings/python/clang/cindex.py | python | Cursor.spelling | (self) | return self._spelling | Return the spelling of the entity pointed at by the cursor. | Return the spelling of the entity pointed at by the cursor. | [
"Return",
"the",
"spelling",
"of",
"the",
"entity",
"pointed",
"at",
"by",
"the",
"cursor",
"."
] | def spelling(self):
"""Return the spelling of the entity pointed at by the cursor."""
if not hasattr(self, '_spelling'):
self._spelling = conf.lib.clang_getCursorSpelling(self)
return self._spelling | [
"def",
"spelling",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_spelling'",
")",
":",
"self",
".",
"_spelling",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorSpelling",
"(",
"self",
")",
"return",
"self",
".",
"_spelling"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/bindings/python/clang/cindex.py#L1544-L1549 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/bucket_listing_ref.py | python | BucketListingBucket.__init__ | (self, storage_url, root_object=None) | Creates a BucketListingRef of type bucket.
Args:
storage_url: StorageUrl containing a bucket.
root_object: Underlying object metadata, if available. | Creates a BucketListingRef of type bucket. | [
"Creates",
"a",
"BucketListingRef",
"of",
"type",
"bucket",
"."
] | def __init__(self, storage_url, root_object=None):
"""Creates a BucketListingRef of type bucket.
Args:
storage_url: StorageUrl containing a bucket.
root_object: Underlying object metadata, if available.
"""
super(BucketListingBucket, self).__init__()
self._ref_type = self._BucketListingRefType.BUCKET
self._url_string = storage_url.url_string
self.storage_url = storage_url
self.root_object = root_object | [
"def",
"__init__",
"(",
"self",
",",
"storage_url",
",",
"root_object",
"=",
"None",
")",
":",
"super",
"(",
"BucketListingBucket",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_ref_type",
"=",
"self",
".",
"_BucketListingRefType",
".",
"BUCKET",
"self",
".",
"_url_string",
"=",
"storage_url",
".",
"url_string",
"self",
".",
"storage_url",
"=",
"storage_url",
"self",
".",
"root_object",
"=",
"root_object"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/bucket_listing_ref.py#L68-L79 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiManager.DoFrameLayout | (self) | This is an internal function which invokes :meth:`Sizer.Layout() <Sizer.Layout>`
on the frame's main sizer, then measures all the various UI items
and updates their internal rectangles.
:note: This should always be called instead of calling
`self._managed_window.Layout()` directly. | This is an internal function which invokes :meth:`Sizer.Layout() <Sizer.Layout>`
on the frame's main sizer, then measures all the various UI items
and updates their internal rectangles. | [
"This",
"is",
"an",
"internal",
"function",
"which",
"invokes",
":",
"meth",
":",
"Sizer",
".",
"Layout",
"()",
"<Sizer",
".",
"Layout",
">",
"on",
"the",
"frame",
"s",
"main",
"sizer",
"then",
"measures",
"all",
"the",
"various",
"UI",
"items",
"and",
"updates",
"their",
"internal",
"rectangles",
"."
] | def DoFrameLayout(self):
"""
This is an internal function which invokes :meth:`Sizer.Layout() <Sizer.Layout>`
on the frame's main sizer, then measures all the various UI items
and updates their internal rectangles.
:note: This should always be called instead of calling
`self._managed_window.Layout()` directly.
"""
self._frame.Layout()
for part in self._uiparts:
# get the rectangle of the UI part
# originally, this code looked like this:
# part.rect = wx.Rect(part.sizer_item.GetPosition(),
# part.sizer_item.GetSize())
# this worked quite well, with one exception: the mdi
# client window had a "deferred" size variable
# that returned the wrong size. It looks like
# a bug in wx, because the former size of the window
# was being returned. So, we will retrieve the part's
# rectangle via other means
part.rect = part.sizer_item.GetRect()
flag = part.sizer_item.GetFlag()
border = part.sizer_item.GetBorder()
if flag & wx.TOP:
part.rect.y -= border
part.rect.height += border
if flag & wx.LEFT:
part.rect.x -= border
part.rect.width += border
if flag & wx.BOTTOM:
part.rect.height += border
if flag & wx.RIGHT:
part.rect.width += border
if part.type == AuiDockUIPart.typeDock:
part.dock.rect = part.rect
if part.type == AuiDockUIPart.typePane:
part.pane.rect = part.rect | [
"def",
"DoFrameLayout",
"(",
"self",
")",
":",
"self",
".",
"_frame",
".",
"Layout",
"(",
")",
"for",
"part",
"in",
"self",
".",
"_uiparts",
":",
"# get the rectangle of the UI part",
"# originally, this code looked like this:",
"# part.rect = wx.Rect(part.sizer_item.GetPosition(),",
"# part.sizer_item.GetSize())",
"# this worked quite well, with one exception: the mdi",
"# client window had a \"deferred\" size variable",
"# that returned the wrong size. It looks like",
"# a bug in wx, because the former size of the window",
"# was being returned. So, we will retrieve the part's",
"# rectangle via other means",
"part",
".",
"rect",
"=",
"part",
".",
"sizer_item",
".",
"GetRect",
"(",
")",
"flag",
"=",
"part",
".",
"sizer_item",
".",
"GetFlag",
"(",
")",
"border",
"=",
"part",
".",
"sizer_item",
".",
"GetBorder",
"(",
")",
"if",
"flag",
"&",
"wx",
".",
"TOP",
":",
"part",
".",
"rect",
".",
"y",
"-=",
"border",
"part",
".",
"rect",
".",
"height",
"+=",
"border",
"if",
"flag",
"&",
"wx",
".",
"LEFT",
":",
"part",
".",
"rect",
".",
"x",
"-=",
"border",
"part",
".",
"rect",
".",
"width",
"+=",
"border",
"if",
"flag",
"&",
"wx",
".",
"BOTTOM",
":",
"part",
".",
"rect",
".",
"height",
"+=",
"border",
"if",
"flag",
"&",
"wx",
".",
"RIGHT",
":",
"part",
".",
"rect",
".",
"width",
"+=",
"border",
"if",
"part",
".",
"type",
"==",
"AuiDockUIPart",
".",
"typeDock",
":",
"part",
".",
"dock",
".",
"rect",
"=",
"part",
".",
"rect",
"if",
"part",
".",
"type",
"==",
"AuiDockUIPart",
".",
"typePane",
":",
"part",
".",
"pane",
".",
"rect",
"=",
"part",
".",
"rect"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L6850-L6892 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/control_flow_ops.py | python | WhileContext.grad_state | (self) | return self._grad_state | The gradient loop state. | The gradient loop state. | [
"The",
"gradient",
"loop",
"state",
"."
] | def grad_state(self):
"""The gradient loop state."""
return self._grad_state | [
"def",
"grad_state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_grad_state"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L2026-L2028 | |
jsupancic/deep_hand_pose | 22cbeae1a8410ff5d37c060c7315719d0a5d608f | python/caffe/io.py | python | load_image | (filename, color=True) | return img | Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale. | Load an image converting from grayscale or alpha as needed. | [
"Load",
"an",
"image",
"converting",
"from",
"grayscale",
"or",
"alpha",
"as",
"needed",
"."
] | def load_image(filename, color=True):
"""
Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale.
"""
img = skimage.img_as_float(skimage.io.imread(filename)).astype(np.float32)
if img.ndim == 2:
img = img[:, :, np.newaxis]
if color:
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img | [
"def",
"load_image",
"(",
"filename",
",",
"color",
"=",
"True",
")",
":",
"img",
"=",
"skimage",
".",
"img_as_float",
"(",
"skimage",
".",
"io",
".",
"imread",
"(",
"filename",
")",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"if",
"img",
".",
"ndim",
"==",
"2",
":",
"img",
"=",
"img",
"[",
":",
",",
":",
",",
"np",
".",
"newaxis",
"]",
"if",
"color",
":",
"img",
"=",
"np",
".",
"tile",
"(",
"img",
",",
"(",
"1",
",",
"1",
",",
"3",
")",
")",
"elif",
"img",
".",
"shape",
"[",
"2",
"]",
"==",
"4",
":",
"img",
"=",
"img",
"[",
":",
",",
":",
",",
":",
"3",
"]",
"return",
"img"
] | https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/python/caffe/io.py#L275-L299 | |
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | hasher-matcher-actioner/hmalib/matchers/filters.py | python | get_privacy_group_matcher_pdq_threshold | (
privacy_group_id: str,
) | return _get_privacy_group_matcher_pdq_threshold(
privacy_group_id, time.time() // PG_CONFIG_CACHE_TIME_SECONDS
) | Does this privacy group's have a custom pdq threshold; if so what is it?
otherwise return the default PDQ_CONFIDENT_MATCH_THRESHOLD.
Entries in the internal cache are cleared
every PG_CONFIG_CACHE_TIME_SECONDS seconds.
ToDo this should be refactored into a signal angostic interface eventaully
especially before we have another similarity based signal type in HMA
Impl: the // is python's integer division operator. Threw me off. :) | Does this privacy group's have a custom pdq threshold; if so what is it?
otherwise return the default PDQ_CONFIDENT_MATCH_THRESHOLD. | [
"Does",
"this",
"privacy",
"group",
"s",
"have",
"a",
"custom",
"pdq",
"threshold",
";",
"if",
"so",
"what",
"is",
"it?",
"otherwise",
"return",
"the",
"default",
"PDQ_CONFIDENT_MATCH_THRESHOLD",
"."
] | def get_privacy_group_matcher_pdq_threshold(
privacy_group_id: str,
) -> int:
"""
Does this privacy group's have a custom pdq threshold; if so what is it?
otherwise return the default PDQ_CONFIDENT_MATCH_THRESHOLD.
Entries in the internal cache are cleared
every PG_CONFIG_CACHE_TIME_SECONDS seconds.
ToDo this should be refactored into a signal angostic interface eventaully
especially before we have another similarity based signal type in HMA
Impl: the // is python's integer division operator. Threw me off. :)
"""
return _get_privacy_group_matcher_pdq_threshold(
privacy_group_id, time.time() // PG_CONFIG_CACHE_TIME_SECONDS
) | [
"def",
"get_privacy_group_matcher_pdq_threshold",
"(",
"privacy_group_id",
":",
"str",
",",
")",
"->",
"int",
":",
"return",
"_get_privacy_group_matcher_pdq_threshold",
"(",
"privacy_group_id",
",",
"time",
".",
"time",
"(",
")",
"//",
"PG_CONFIG_CACHE_TIME_SECONDS",
")"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/hasher-matcher-actioner/hmalib/matchers/filters.py#L201-L218 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/engine/properties.py | python | Properties.kstress_cv | (self) | return kst | Calculates the quantum centroid virial kinetic stress tensor
estimator.
Note that this is not divided by the volume or the number of beads.
Returns:
A 3*3 tensor with all the components of the tensor. | Calculates the quantum centroid virial kinetic stress tensor
estimator. | [
"Calculates",
"the",
"quantum",
"centroid",
"virial",
"kinetic",
"stress",
"tensor",
"estimator",
"."
] | def kstress_cv(self):
"""Calculates the quantum centroid virial kinetic stress tensor
estimator.
Note that this is not divided by the volume or the number of beads.
Returns:
A 3*3 tensor with all the components of the tensor.
"""
kst = np.zeros((3,3),float)
q = depstrip(self.beads.q)
qc = depstrip(self.beads.qc)
pc = depstrip(self.beads.pc)
m = depstrip(self.beads.m)
fall = depstrip(self.forces.f)
na3 = 3*self.beads.natoms
for b in range(self.beads.nbeads):
for i in range(3):
for j in range(i,3):
kst[i,j] -= np.dot(q[b,i:na3:3] - qc[i:na3:3],
fall[b,j:na3:3])
# return the CV estimator MULTIPLIED BY NBEADS -- again for consistency with the virial, kstress_MD, etc...
for i in range(3):
kst[i,i] += self.beads.nbeads * ( np.dot(pc[i:na3:3],pc[i:na3:3]/m) )
return kst | [
"def",
"kstress_cv",
"(",
"self",
")",
":",
"kst",
"=",
"np",
".",
"zeros",
"(",
"(",
"3",
",",
"3",
")",
",",
"float",
")",
"q",
"=",
"depstrip",
"(",
"self",
".",
"beads",
".",
"q",
")",
"qc",
"=",
"depstrip",
"(",
"self",
".",
"beads",
".",
"qc",
")",
"pc",
"=",
"depstrip",
"(",
"self",
".",
"beads",
".",
"pc",
")",
"m",
"=",
"depstrip",
"(",
"self",
".",
"beads",
".",
"m",
")",
"fall",
"=",
"depstrip",
"(",
"self",
".",
"forces",
".",
"f",
")",
"na3",
"=",
"3",
"*",
"self",
".",
"beads",
".",
"natoms",
"for",
"b",
"in",
"range",
"(",
"self",
".",
"beads",
".",
"nbeads",
")",
":",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
",",
"3",
")",
":",
"kst",
"[",
"i",
",",
"j",
"]",
"-=",
"np",
".",
"dot",
"(",
"q",
"[",
"b",
",",
"i",
":",
"na3",
":",
"3",
"]",
"-",
"qc",
"[",
"i",
":",
"na3",
":",
"3",
"]",
",",
"fall",
"[",
"b",
",",
"j",
":",
"na3",
":",
"3",
"]",
")",
"# return the CV estimator MULTIPLIED BY NBEADS -- again for consistency with the virial, kstress_MD, etc...",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"kst",
"[",
"i",
",",
"i",
"]",
"+=",
"self",
".",
"beads",
".",
"nbeads",
"*",
"(",
"np",
".",
"dot",
"(",
"pc",
"[",
"i",
":",
"na3",
":",
"3",
"]",
",",
"pc",
"[",
"i",
":",
"na3",
":",
"3",
"]",
"/",
"m",
")",
")",
"return",
"kst"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/properties.py#L760-L788 | |
godotengine/godot | 39562294ff3e6a273f9a73f97bc54791a4e98f07 | doc/tools/make_rst.py | python | translate | (string) | return strings_l10n.get(string, string) | Translate a string based on translations sourced from `doc/translations/*.po`
for a language if defined via the --lang command line argument.
Returns the original string if no translation exists. | Translate a string based on translations sourced from `doc/translations/*.po`
for a language if defined via the --lang command line argument.
Returns the original string if no translation exists. | [
"Translate",
"a",
"string",
"based",
"on",
"translations",
"sourced",
"from",
"doc",
"/",
"translations",
"/",
"*",
".",
"po",
"for",
"a",
"language",
"if",
"defined",
"via",
"the",
"--",
"lang",
"command",
"line",
"argument",
".",
"Returns",
"the",
"original",
"string",
"if",
"no",
"translation",
"exists",
"."
] | def translate(string): # type: (str) -> str
"""Translate a string based on translations sourced from `doc/translations/*.po`
for a language if defined via the --lang command line argument.
Returns the original string if no translation exists.
"""
return strings_l10n.get(string, string) | [
"def",
"translate",
"(",
"string",
")",
":",
"# type: (str) -> str",
"return",
"strings_l10n",
".",
"get",
"(",
"string",
",",
"string",
")"
] | https://github.com/godotengine/godot/blob/39562294ff3e6a273f9a73f97bc54791a4e98f07/doc/tools/make_rst.py#L511-L516 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/depot_tools/cpplint.py | python | CheckIncludeLine | (filename, clean_lines, linenum, include_state, error) | Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found. | Check rules that are applicable to #include lines. | [
"Check",
"rules",
"that",
"are",
"applicable",
"to",
"#include",
"lines",
"."
] | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
# Only do this check if the included header follows google naming
# conventions. If not, assume that it's a 3rd party API that
# requires special include conventions.
#
# We also make an exception for Lua headers, which follow google
# naming convention but not the include convention.
match = Match(r'#include\s*"([^/]+\.h)"', line)
if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
error(filename, linenum, 'build/include_directory', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
duplicate_line = include_state.FindHeader(include)
if duplicate_line >= 0:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, duplicate_line))
elif (include.endswith('.cc') and
os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
error(filename, linenum, 'build/include', 4,
'Do not include .cc files from other packages')
elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
include_state.include_list[-1].append((include, linenum))
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include) | [
"def",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
":",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"# \"include\" should use the new style \"foo/bar.h\" instead of just \"bar.h\"",
"# Only do this check if the included header follows google naming",
"# conventions. If not, assume that it's a 3rd party API that",
"# requires special include conventions.",
"#",
"# We also make an exception for Lua headers, which follow google",
"# naming convention but not the include convention.",
"match",
"=",
"Match",
"(",
"r'#include\\s*\"([^/]+\\.h)\"'",
",",
"line",
")",
"if",
"match",
"and",
"not",
"_THIRD_PARTY_HEADERS_PATTERN",
".",
"match",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_directory'",
",",
"4",
",",
"'Include the directory when naming .h files'",
")",
"# we shouldn't include a file more than once. actually, there are a",
"# handful of instances where doing so is okay, but in general it's",
"# not.",
"match",
"=",
"_RE_PATTERN_INCLUDE",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"include",
"=",
"match",
".",
"group",
"(",
"2",
")",
"is_system",
"=",
"(",
"match",
".",
"group",
"(",
"1",
")",
"==",
"'<'",
")",
"duplicate_line",
"=",
"include_state",
".",
"FindHeader",
"(",
"include",
")",
"if",
"duplicate_line",
">=",
"0",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'\"%s\" already included at %s:%s'",
"%",
"(",
"include",
",",
"filename",
",",
"duplicate_line",
")",
")",
"elif",
"(",
"include",
".",
"endswith",
"(",
"'.cc'",
")",
"and",
"os",
".",
"path",
".",
"dirname",
"(",
"fileinfo",
".",
"RepositoryName",
"(",
")",
")",
"!=",
"os",
".",
"path",
".",
"dirname",
"(",
"include",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'Do not include .cc files from other packages'",
")",
"elif",
"not",
"_THIRD_PARTY_HEADERS_PATTERN",
".",
"match",
"(",
"include",
")",
":",
"include_state",
".",
"include_list",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"(",
"include",
",",
"linenum",
")",
")",
"# We want to ensure that headers appear in the right order:",
"# 1) for foo.cc, foo.h (preferred location)",
"# 2) c system files",
"# 3) cpp system files",
"# 4) for foo.cc, foo.h (deprecated location)",
"# 5) other google headers",
"#",
"# We classify each include statement as one of those 5 types",
"# using a number of techniques. The include_state object keeps",
"# track of the highest type seen, and complains if we see a",
"# lower type after that.",
"error_message",
"=",
"include_state",
".",
"CheckNextIncludeOrder",
"(",
"_ClassifyInclude",
"(",
"fileinfo",
",",
"include",
",",
"is_system",
")",
")",
"if",
"error_message",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_order'",
",",
"4",
",",
"'%s. Should be: %s.h, c system, c++ system, other.'",
"%",
"(",
"error_message",
",",
"fileinfo",
".",
"BaseName",
"(",
")",
")",
")",
"canonical_include",
"=",
"include_state",
".",
"CanonicalizeAlphabeticalOrder",
"(",
"include",
")",
"if",
"not",
"include_state",
".",
"IsInAlphabeticalOrder",
"(",
"clean_lines",
",",
"linenum",
",",
"canonical_include",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_alpha'",
",",
"4",
",",
"'Include \"%s\" not in alphabetical order'",
"%",
"include",
")",
"include_state",
".",
"SetLastHeader",
"(",
"canonical_include",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L4390-L4460 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/back/ie_ir_ver_2/emitter.py | python | soft_get | (node, attr) | return node.soft_get(attr) if hasattr(node, 'soft_get') and callable(node.soft_get) else '<SUB-ELEMENT>' | If node has soft_get callable member, returns node.soft_get(attr), else return <SUB-ELEMENT> | If node has soft_get callable member, returns node.soft_get(attr), else return <SUB-ELEMENT> | [
"If",
"node",
"has",
"soft_get",
"callable",
"member",
"returns",
"node",
".",
"soft_get",
"(",
"attr",
")",
"else",
"return",
"<SUB",
"-",
"ELEMENT",
">"
] | def soft_get(node, attr):
""" If node has soft_get callable member, returns node.soft_get(attr), else return <SUB-ELEMENT> """
return node.soft_get(attr) if hasattr(node, 'soft_get') and callable(node.soft_get) else '<SUB-ELEMENT>' | [
"def",
"soft_get",
"(",
"node",
",",
"attr",
")",
":",
"return",
"node",
".",
"soft_get",
"(",
"attr",
")",
"if",
"hasattr",
"(",
"node",
",",
"'soft_get'",
")",
"and",
"callable",
"(",
"node",
".",
"soft_get",
")",
"else",
"'<SUB-ELEMENT>'"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/back/ie_ir_ver_2/emitter.py#L224-L226 | |
tomahawk-player/tomahawk-resolvers | 7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d | archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/python_message.py | python | _ExtensionDict.__setitem__ | (self, extension_handle, value) | If extension_handle specifies a non-repeated, scalar extension
field, sets the value of that field. | If extension_handle specifies a non-repeated, scalar extension
field, sets the value of that field. | [
"If",
"extension_handle",
"specifies",
"a",
"non",
"-",
"repeated",
"scalar",
"extension",
"field",
"sets",
"the",
"value",
"of",
"that",
"field",
"."
] | def __setitem__(self, extension_handle, value):
"""If extension_handle specifies a non-repeated, scalar extension
field, sets the value of that field.
"""
_VerifyExtensionHandle(self._extended_message, extension_handle)
if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED or
extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE):
raise TypeError(
'Cannot assign to extension "%s" because it is a repeated or '
'composite type.' % extension_handle.full_name)
# It's slightly wasteful to lookup the type checker each time,
# but we expect this to be a vanishingly uncommon case anyway.
type_checker = type_checkers.GetTypeChecker(
extension_handle.cpp_type, extension_handle.type)
type_checker.CheckValue(value)
self._extended_message._fields[extension_handle] = value
self._extended_message._Modified() | [
"def",
"__setitem__",
"(",
"self",
",",
"extension_handle",
",",
"value",
")",
":",
"_VerifyExtensionHandle",
"(",
"self",
".",
"_extended_message",
",",
"extension_handle",
")",
"if",
"(",
"extension_handle",
".",
"label",
"==",
"_FieldDescriptor",
".",
"LABEL_REPEATED",
"or",
"extension_handle",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
")",
":",
"raise",
"TypeError",
"(",
"'Cannot assign to extension \"%s\" because it is a repeated or '",
"'composite type.'",
"%",
"extension_handle",
".",
"full_name",
")",
"# It's slightly wasteful to lookup the type checker each time,",
"# but we expect this to be a vanishingly uncommon case anyway.",
"type_checker",
"=",
"type_checkers",
".",
"GetTypeChecker",
"(",
"extension_handle",
".",
"cpp_type",
",",
"extension_handle",
".",
"type",
")",
"type_checker",
".",
"CheckValue",
"(",
"value",
")",
"self",
".",
"_extended_message",
".",
"_fields",
"[",
"extension_handle",
"]",
"=",
"value",
"self",
".",
"_extended_message",
".",
"_Modified",
"(",
")"
] | https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/python_message.py#L1068-L1087 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | benchmarks/functional_autograd_benchmark/torchvision_models.py | python | conv1x1 | (in_planes, out_planes, stride=1) | return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | 1x1 convolution | 1x1 convolution | [
"1x1",
"convolution"
] | def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | [
"def",
"conv1x1",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"1",
",",
"stride",
"=",
"stride",
",",
"bias",
"=",
"False",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/functional_autograd_benchmark/torchvision_models.py#L22-L24 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime.AddTS | (*args, **kwargs) | return _misc_.DateTime_AddTS(*args, **kwargs) | AddTS(self, TimeSpan diff) -> DateTime | AddTS(self, TimeSpan diff) -> DateTime | [
"AddTS",
"(",
"self",
"TimeSpan",
"diff",
")",
"-",
">",
"DateTime"
] | def AddTS(*args, **kwargs):
"""AddTS(self, TimeSpan diff) -> DateTime"""
return _misc_.DateTime_AddTS(*args, **kwargs) | [
"def",
"AddTS",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_AddTS",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4057-L4059 | |
cathywu/Sentiment-Analysis | eb501fd1375c0c3f3ab430f963255f1bb858e659 | PyML-0.7.9/PyML/preproc/preproc.py | python | pca | (X, numcomp = None) | return numpy.dot(X, v) | returns the matrix X as represented in the numcomp leading principal
components
if numcomp is None, all principal components are returned | returns the matrix X as represented in the numcomp leading principal
components
if numcomp is None, all principal components are returned | [
"returns",
"the",
"matrix",
"X",
"as",
"represented",
"in",
"the",
"numcomp",
"leading",
"principal",
"components",
"if",
"numcomp",
"is",
"None",
"all",
"principal",
"components",
"are",
"returned"
] | def pca(X, numcomp = None) :
'''returns the matrix X as represented in the numcomp leading principal
components
if numcomp is None, all principal components are returned'''
d = numpy.shape(X)[1]
if numcomp is None :
numcomp = d
[u,s,v] = numpy.linalg.svd(X)
v = numpy.transpose(v)
v = v[:,:numcomp]
print numpy.shape(X)
return numpy.dot(X, v) | [
"def",
"pca",
"(",
"X",
",",
"numcomp",
"=",
"None",
")",
":",
"d",
"=",
"numpy",
".",
"shape",
"(",
"X",
")",
"[",
"1",
"]",
"if",
"numcomp",
"is",
"None",
":",
"numcomp",
"=",
"d",
"[",
"u",
",",
"s",
",",
"v",
"]",
"=",
"numpy",
".",
"linalg",
".",
"svd",
"(",
"X",
")",
"v",
"=",
"numpy",
".",
"transpose",
"(",
"v",
")",
"v",
"=",
"v",
"[",
":",
",",
":",
"numcomp",
"]",
"print",
"numpy",
".",
"shape",
"(",
"X",
")",
"return",
"numpy",
".",
"dot",
"(",
"X",
",",
"v",
")"
] | https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/preproc/preproc.py#L10-L23 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/httputil.py | python | parse_request_start_line | (line: str) | return RequestStartLine(method, path, version) | Returns a (method, path, version) tuple for an HTTP 1.x request line.
The response is a `collections.namedtuple`.
>>> parse_request_start_line("GET /foo HTTP/1.1")
RequestStartLine(method='GET', path='/foo', version='HTTP/1.1') | Returns a (method, path, version) tuple for an HTTP 1.x request line. | [
"Returns",
"a",
"(",
"method",
"path",
"version",
")",
"tuple",
"for",
"an",
"HTTP",
"1",
".",
"x",
"request",
"line",
"."
] | def parse_request_start_line(line: str) -> RequestStartLine:
"""Returns a (method, path, version) tuple for an HTTP 1.x request line.
The response is a `collections.namedtuple`.
>>> parse_request_start_line("GET /foo HTTP/1.1")
RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
"""
try:
method, path, version = line.split(" ")
except ValueError:
# https://tools.ietf.org/html/rfc7230#section-3.1.1
# invalid request-line SHOULD respond with a 400 (Bad Request)
raise HTTPInputError("Malformed HTTP request line")
if not _http_version_re.match(version):
raise HTTPInputError(
"Malformed HTTP version in HTTP Request-Line: %r" % version
)
return RequestStartLine(method, path, version) | [
"def",
"parse_request_start_line",
"(",
"line",
":",
"str",
")",
"->",
"RequestStartLine",
":",
"try",
":",
"method",
",",
"path",
",",
"version",
"=",
"line",
".",
"split",
"(",
"\" \"",
")",
"except",
"ValueError",
":",
"# https://tools.ietf.org/html/rfc7230#section-3.1.1",
"# invalid request-line SHOULD respond with a 400 (Bad Request)",
"raise",
"HTTPInputError",
"(",
"\"Malformed HTTP request line\"",
")",
"if",
"not",
"_http_version_re",
".",
"match",
"(",
"version",
")",
":",
"raise",
"HTTPInputError",
"(",
"\"Malformed HTTP version in HTTP Request-Line: %r\"",
"%",
"version",
")",
"return",
"RequestStartLine",
"(",
"method",
",",
"path",
",",
"version",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/httputil.py#L882-L900 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/api/liquidation_api.py | python | LiquidationApi.liquidation_get | (self, **kwargs) | Get liquidation orders. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.liquidation_get(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str symbol: Instrument symbol. Send a bare series (e.g. XBT) to get data for the nearest expiring contract in that series. You can also send a timeframe, e.g. `XBT:quarterly`. Timeframes are `nearest`, `daily`, `weekly`, `monthly`, `quarterly`, `biquarterly`, and `perpetual`.
:param str filter: Generic table filter. Send JSON key/value pairs, such as `{\"key\": \"value\"}`. You can key on individual fields, and do more advanced querying on timestamps. See the [Timestamp Docs](https://www.bitmex.com/app/restAPI#Timestamp-Filters) for more details.
:param str columns: Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect.
:param float count: Number of results to fetch.
:param float start: Starting point for results.
:param bool reverse: If true, will sort results newest first.
:param datetime start_time: Starting date filter for results.
:param datetime end_time: Ending date filter for results.
:return: list[Liquidation]
If the method is called asynchronously,
returns the request thread. | Get liquidation orders. # noqa: E501 | [
"Get",
"liquidation",
"orders",
".",
"#",
"noqa",
":",
"E501"
] | def liquidation_get(self, **kwargs): # noqa: E501
"""Get liquidation orders. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.liquidation_get(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str symbol: Instrument symbol. Send a bare series (e.g. XBT) to get data for the nearest expiring contract in that series. You can also send a timeframe, e.g. `XBT:quarterly`. Timeframes are `nearest`, `daily`, `weekly`, `monthly`, `quarterly`, `biquarterly`, and `perpetual`.
:param str filter: Generic table filter. Send JSON key/value pairs, such as `{\"key\": \"value\"}`. You can key on individual fields, and do more advanced querying on timestamps. See the [Timestamp Docs](https://www.bitmex.com/app/restAPI#Timestamp-Filters) for more details.
:param str columns: Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect.
:param float count: Number of results to fetch.
:param float start: Starting point for results.
:param bool reverse: If true, will sort results newest first.
:param datetime start_time: Starting date filter for results.
:param datetime end_time: Ending date filter for results.
:return: list[Liquidation]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.liquidation_get_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.liquidation_get_with_http_info(**kwargs) # noqa: E501
return data | [
"def",
"liquidation_get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"liquidation_get_with_http_info",
"(",
"*",
"*",
"kwargs",
")",
"# noqa: E501",
"else",
":",
"(",
"data",
")",
"=",
"self",
".",
"liquidation_get_with_http_info",
"(",
"*",
"*",
"kwargs",
")",
"# noqa: E501",
"return",
"data"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/api/liquidation_api.py#L36-L62 | ||
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/sonnx.py | python | SingaBackend._run_node | (cls, operator, inputs) | return outputs | run a single singa operator from singa operator
Args:
operator (Operator): the Operator instance
inputs (Tensor[]): a list of SINGA Tensor
Returns:
list, the output | run a single singa operator from singa operator
Args:
operator (Operator): the Operator instance
inputs (Tensor[]): a list of SINGA Tensor
Returns:
list, the output | [
"run",
"a",
"single",
"singa",
"operator",
"from",
"singa",
"operator",
"Args",
":",
"operator",
"(",
"Operator",
")",
":",
"the",
"Operator",
"instance",
"inputs",
"(",
"Tensor",
"[]",
")",
":",
"a",
"list",
"of",
"SINGA",
"Tensor",
"Returns",
":",
"list",
"the",
"output"
] | def _run_node(cls, operator, inputs):
"""
run a single singa operator from singa operator
Args:
operator (Operator): the Operator instance
inputs (Tensor[]): a list of SINGA Tensor
Returns:
list, the output
"""
outputs = operator(*inputs)
if not isinstance(outputs, collections.Iterable):
outputs = [outputs]
return outputs | [
"def",
"_run_node",
"(",
"cls",
",",
"operator",
",",
"inputs",
")",
":",
"outputs",
"=",
"operator",
"(",
"*",
"inputs",
")",
"if",
"not",
"isinstance",
"(",
"outputs",
",",
"collections",
".",
"Iterable",
")",
":",
"outputs",
"=",
"[",
"outputs",
"]",
"return",
"outputs"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/sonnx.py#L1819-L1831 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/plot.py | python | PlotCanvas.SetEnableLegend | (self, value) | Set True to enable legend. | Set True to enable legend. | [
"Set",
"True",
"to",
"enable",
"legend",
"."
] | def SetEnableLegend(self, value):
"""Set True to enable legend."""
if value not in [True, False]:
raise TypeError("Value should be True or False")
self._legendEnabled = value
self.Redraw() | [
"def",
"SetEnableLegend",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"TypeError",
"(",
"\"Value should be True or False\"",
")",
"self",
".",
"_legendEnabled",
"=",
"value",
"self",
".",
"Redraw",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/plot.py#L954-L959 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGridInterface.Items | (self) | This attribute is a pythonic iterator over all items in this
`PropertyGrid` property container, excluding only private child
properties. Usage is simple::
for prop in propGrid.Items:
print(prop)
:see: `wx.propgrid.PropertyGridInterface.Properties`
`wx.propgrid.PropertyGridInterface.GetPyIterator` | This attribute is a pythonic iterator over all items in this
`PropertyGrid` property container, excluding only private child
properties. Usage is simple:: | [
"This",
"attribute",
"is",
"a",
"pythonic",
"iterator",
"over",
"all",
"items",
"in",
"this",
"PropertyGrid",
"property",
"container",
"excluding",
"only",
"private",
"child",
"properties",
".",
"Usage",
"is",
"simple",
"::"
] | def Items(self):
"""
This attribute is a pythonic iterator over all items in this
`PropertyGrid` property container, excluding only private child
properties. Usage is simple::
for prop in propGrid.Items:
print(prop)
:see: `wx.propgrid.PropertyGridInterface.Properties`
`wx.propgrid.PropertyGridInterface.GetPyIterator`
"""
it = self.GetVIterator(PG_ITERATE_NORMAL | PG_ITERATE_CATEGORIES)
while not it.AtEnd():
yield it.GetProperty()
it.Next() | [
"def",
"Items",
"(",
"self",
")",
":",
"it",
"=",
"self",
".",
"GetVIterator",
"(",
"PG_ITERATE_NORMAL",
"|",
"PG_ITERATE_CATEGORIES",
")",
"while",
"not",
"it",
".",
"AtEnd",
"(",
")",
":",
"yield",
"it",
".",
"GetProperty",
"(",
")",
"it",
".",
"Next",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1783-L1798 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/MythTV/methodheap.py | python | MythBE.getSGList | (self,host,sg,path,filenamesonly=False) | Returns a tuple of directories, files, and filesizes.
Two special modes
'filenamesonly' returns only filenames, no directories or size
empty path base directories returns base storage group paths | Returns a tuple of directories, files, and filesizes.
Two special modes
'filenamesonly' returns only filenames, no directories or size
empty path base directories returns base storage group paths | [
"Returns",
"a",
"tuple",
"of",
"directories",
"files",
"and",
"filesizes",
".",
"Two",
"special",
"modes",
"filenamesonly",
"returns",
"only",
"filenames",
"no",
"directories",
"or",
"size",
"empty",
"path",
"base",
"directories",
"returns",
"base",
"storage",
"group",
"paths"
] | def getSGList(self,host,sg,path,filenamesonly=False):
"""
Returns a tuple of directories, files, and filesizes.
Two special modes
'filenamesonly' returns only filenames, no directories or size
empty path base directories returns base storage group paths
"""
if filenamesonly: path = '' # force empty path
res = self.backendCommand(BACKEND_SEP.join(\
['QUERY_SG_GETFILELIST',host,sg,path,
str(int(filenamesonly))]\
)).split(BACKEND_SEP)
if res[0] == 'EMPTY LIST':
return -1
if res[0] == 'SLAVE UNREACHABLE: ':
return -2
dirs = []
files = []
sizes = []
for entry in res:
if filenamesonly:
files.append(entry)
elif path == '':
type,name = entry.split('::')
dirs.append(name)
else:
se = entry.split('::')
if se[0] == 'file':
files.append(se[1])
sizes.append(se[2])
elif se[0] == 'dir':
dirs.append(se[1])
if filenamesonly:
return files
elif path == '':
return dirs
else:
return (dirs, files, sizes) | [
"def",
"getSGList",
"(",
"self",
",",
"host",
",",
"sg",
",",
"path",
",",
"filenamesonly",
"=",
"False",
")",
":",
"if",
"filenamesonly",
":",
"path",
"=",
"''",
"# force empty path",
"res",
"=",
"self",
".",
"backendCommand",
"(",
"BACKEND_SEP",
".",
"join",
"(",
"[",
"'QUERY_SG_GETFILELIST'",
",",
"host",
",",
"sg",
",",
"path",
",",
"str",
"(",
"int",
"(",
"filenamesonly",
")",
")",
"]",
")",
")",
".",
"split",
"(",
"BACKEND_SEP",
")",
"if",
"res",
"[",
"0",
"]",
"==",
"'EMPTY LIST'",
":",
"return",
"-",
"1",
"if",
"res",
"[",
"0",
"]",
"==",
"'SLAVE UNREACHABLE: '",
":",
"return",
"-",
"2",
"dirs",
"=",
"[",
"]",
"files",
"=",
"[",
"]",
"sizes",
"=",
"[",
"]",
"for",
"entry",
"in",
"res",
":",
"if",
"filenamesonly",
":",
"files",
".",
"append",
"(",
"entry",
")",
"elif",
"path",
"==",
"''",
":",
"type",
",",
"name",
"=",
"entry",
".",
"split",
"(",
"'::'",
")",
"dirs",
".",
"append",
"(",
"name",
")",
"else",
":",
"se",
"=",
"entry",
".",
"split",
"(",
"'::'",
")",
"if",
"se",
"[",
"0",
"]",
"==",
"'file'",
":",
"files",
".",
"append",
"(",
"se",
"[",
"1",
"]",
")",
"sizes",
".",
"append",
"(",
"se",
"[",
"2",
"]",
")",
"elif",
"se",
"[",
"0",
"]",
"==",
"'dir'",
":",
"dirs",
".",
"append",
"(",
"se",
"[",
"1",
"]",
")",
"if",
"filenamesonly",
":",
"return",
"files",
"elif",
"path",
"==",
"''",
":",
"return",
"dirs",
"else",
":",
"return",
"(",
"dirs",
",",
"files",
",",
"sizes",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/methodheap.py#L357-L394 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py | python | make_export_strategy | (serving_input_fn,
default_output_alternative_key=None,
assets_extra=None,
as_text=False,
exports_to_keep=5) | return export_strategy.ExportStrategy('Servo', export_fn) | Create an ExportStrategy for use with Experiment.
Args:
serving_input_fn: A function that takes no arguments and returns an
`InputFnOps`.
default_output_alternative_key: the name of the head to serve when an
incoming serving request does not explicitly request a specific head.
Must be `None` if the estimator inherits from ${tf.estimator.Estimator}
or for single-headed models.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported SavedModel. Each key should give the destination
path (including the filename) relative to the assets.extra directory.
The corresponding value gives the full path of the source file to be
copied. For example, the simple case of copying a single file without
renaming it is specified as
`{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
as_text: whether to write the SavedModel proto in text format.
exports_to_keep: Number of exports to keep. Older exports will be
garbage-collected. Defaults to 5. Set to None to disable garbage
collection.
Returns:
An ExportStrategy that can be passed to the Experiment constructor. | Create an ExportStrategy for use with Experiment. | [
"Create",
"an",
"ExportStrategy",
"for",
"use",
"with",
"Experiment",
"."
] | def make_export_strategy(serving_input_fn,
default_output_alternative_key=None,
assets_extra=None,
as_text=False,
exports_to_keep=5):
"""Create an ExportStrategy for use with Experiment.
Args:
serving_input_fn: A function that takes no arguments and returns an
`InputFnOps`.
default_output_alternative_key: the name of the head to serve when an
incoming serving request does not explicitly request a specific head.
Must be `None` if the estimator inherits from ${tf.estimator.Estimator}
or for single-headed models.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported SavedModel. Each key should give the destination
path (including the filename) relative to the assets.extra directory.
The corresponding value gives the full path of the source file to be
copied. For example, the simple case of copying a single file without
renaming it is specified as
`{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
as_text: whether to write the SavedModel proto in text format.
exports_to_keep: Number of exports to keep. Older exports will be
garbage-collected. Defaults to 5. Set to None to disable garbage
collection.
Returns:
An ExportStrategy that can be passed to the Experiment constructor.
"""
def export_fn(estimator, export_dir_base, checkpoint_path=None):
"""Exports the given Estimator as a SavedModel.
Args:
estimator: the Estimator to export.
export_dir_base: A string containing a directory to write the exported
graph and checkpoints.
checkpoint_path: The checkpoint path to export. If None (the default),
the most recent checkpoint found within the model directory is chosen.
Returns:
The string path to the exported directory.
Raises:
ValueError: If `estimator` is a ${tf.estimator.Estimator} instance
and `default_output_alternative_key` was specified.
"""
if isinstance(estimator, core_estimator.Estimator):
if default_output_alternative_key is not None:
raise ValueError(
'default_output_alternative_key is not supported in core '
'Estimator. Given: {}'.format(default_output_alternative_key))
export_result = estimator.export_savedmodel(
export_dir_base,
serving_input_fn,
assets_extra=assets_extra,
as_text=as_text,
checkpoint_path=checkpoint_path)
else:
export_result = estimator.export_savedmodel(
export_dir_base,
serving_input_fn,
default_output_alternative_key=default_output_alternative_key,
assets_extra=assets_extra,
as_text=as_text,
checkpoint_path=checkpoint_path)
garbage_collect_exports(export_dir_base, exports_to_keep)
return export_result
return export_strategy.ExportStrategy('Servo', export_fn) | [
"def",
"make_export_strategy",
"(",
"serving_input_fn",
",",
"default_output_alternative_key",
"=",
"None",
",",
"assets_extra",
"=",
"None",
",",
"as_text",
"=",
"False",
",",
"exports_to_keep",
"=",
"5",
")",
":",
"def",
"export_fn",
"(",
"estimator",
",",
"export_dir_base",
",",
"checkpoint_path",
"=",
"None",
")",
":",
"\"\"\"Exports the given Estimator as a SavedModel.\n\n Args:\n estimator: the Estimator to export.\n export_dir_base: A string containing a directory to write the exported\n graph and checkpoints.\n checkpoint_path: The checkpoint path to export. If None (the default),\n the most recent checkpoint found within the model directory is chosen.\n\n Returns:\n The string path to the exported directory.\n\n Raises:\n ValueError: If `estimator` is a ${tf.estimator.Estimator} instance\n and `default_output_alternative_key` was specified.\n \"\"\"",
"if",
"isinstance",
"(",
"estimator",
",",
"core_estimator",
".",
"Estimator",
")",
":",
"if",
"default_output_alternative_key",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'default_output_alternative_key is not supported in core '",
"'Estimator. Given: {}'",
".",
"format",
"(",
"default_output_alternative_key",
")",
")",
"export_result",
"=",
"estimator",
".",
"export_savedmodel",
"(",
"export_dir_base",
",",
"serving_input_fn",
",",
"assets_extra",
"=",
"assets_extra",
",",
"as_text",
"=",
"as_text",
",",
"checkpoint_path",
"=",
"checkpoint_path",
")",
"else",
":",
"export_result",
"=",
"estimator",
".",
"export_savedmodel",
"(",
"export_dir_base",
",",
"serving_input_fn",
",",
"default_output_alternative_key",
"=",
"default_output_alternative_key",
",",
"assets_extra",
"=",
"assets_extra",
",",
"as_text",
"=",
"as_text",
",",
"checkpoint_path",
"=",
"checkpoint_path",
")",
"garbage_collect_exports",
"(",
"export_dir_base",
",",
"exports_to_keep",
")",
"return",
"export_result",
"return",
"export_strategy",
".",
"ExportStrategy",
"(",
"'Servo'",
",",
"export_fn",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py#L389-L459 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/processpool.py | python | ClientFactory.__init__ | (self, client_kwargs=None) | Creates S3 clients for processes
Botocore sessions and clients are not pickleable so they cannot be
inherited across Process boundaries. Instead, they must be instantiated
once a process is running. | Creates S3 clients for processes | [
"Creates",
"S3",
"clients",
"for",
"processes"
] | def __init__(self, client_kwargs=None):
"""Creates S3 clients for processes
Botocore sessions and clients are not pickleable so they cannot be
inherited across Process boundaries. Instead, they must be instantiated
once a process is running.
"""
self._client_kwargs = client_kwargs
if self._client_kwargs is None:
self._client_kwargs = {}
client_config = deepcopy(self._client_kwargs.get('config', Config()))
if not client_config.user_agent_extra:
client_config.user_agent_extra = PROCESS_USER_AGENT
else:
client_config.user_agent_extra += " " + PROCESS_USER_AGENT
self._client_kwargs['config'] = client_config | [
"def",
"__init__",
"(",
"self",
",",
"client_kwargs",
"=",
"None",
")",
":",
"self",
".",
"_client_kwargs",
"=",
"client_kwargs",
"if",
"self",
".",
"_client_kwargs",
"is",
"None",
":",
"self",
".",
"_client_kwargs",
"=",
"{",
"}",
"client_config",
"=",
"deepcopy",
"(",
"self",
".",
"_client_kwargs",
".",
"get",
"(",
"'config'",
",",
"Config",
"(",
")",
")",
")",
"if",
"not",
"client_config",
".",
"user_agent_extra",
":",
"client_config",
".",
"user_agent_extra",
"=",
"PROCESS_USER_AGENT",
"else",
":",
"client_config",
".",
"user_agent_extra",
"+=",
"\" \"",
"+",
"PROCESS_USER_AGENT",
"self",
".",
"_client_kwargs",
"[",
"'config'",
"]",
"=",
"client_config"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/processpool.py#L543-L559 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/importlib-metadata/py2/importlib_metadata/__init__.py | python | files | (distribution_name) | return distribution(distribution_name).files | Return a list of files for the named package.
:param distribution_name: The name of the distribution package to query.
:return: List of files composing the distribution. | Return a list of files for the named package. | [
"Return",
"a",
"list",
"of",
"files",
"for",
"the",
"named",
"package",
"."
] | def files(distribution_name):
"""Return a list of files for the named package.
:param distribution_name: The name of the distribution package to query.
:return: List of files composing the distribution.
"""
return distribution(distribution_name).files | [
"def",
"files",
"(",
"distribution_name",
")",
":",
"return",
"distribution",
"(",
"distribution_name",
")",
".",
"files"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/importlib-metadata/py2/importlib_metadata/__init__.py#L689-L695 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/ceph-volume/ceph_volume/util/system.py | python | get_mounts | (devices=False, paths=False, realpath=False) | Create a mapping of all available system mounts so that other helpers can
detect nicely what path or device is mounted
It ignores (most of) non existing devices, but since some setups might need
some extra device information, it will make an exception for:
- tmpfs
- devtmpfs
- /dev/root
If ``devices`` is set to ``True`` the mapping will be a device-to-path(s),
if ``paths`` is set to ``True`` then the mapping will be
a path-to-device(s)
:param realpath: Resolve devices to use their realpaths. This is useful for
paths like LVM where more than one path can point to the same device | Create a mapping of all available system mounts so that other helpers can
detect nicely what path or device is mounted | [
"Create",
"a",
"mapping",
"of",
"all",
"available",
"system",
"mounts",
"so",
"that",
"other",
"helpers",
"can",
"detect",
"nicely",
"what",
"path",
"or",
"device",
"is",
"mounted"
] | def get_mounts(devices=False, paths=False, realpath=False):
"""
Create a mapping of all available system mounts so that other helpers can
detect nicely what path or device is mounted
It ignores (most of) non existing devices, but since some setups might need
some extra device information, it will make an exception for:
- tmpfs
- devtmpfs
- /dev/root
If ``devices`` is set to ``True`` the mapping will be a device-to-path(s),
if ``paths`` is set to ``True`` then the mapping will be
a path-to-device(s)
:param realpath: Resolve devices to use their realpaths. This is useful for
paths like LVM where more than one path can point to the same device
"""
devices_mounted = {}
paths_mounted = {}
do_not_skip = ['tmpfs', 'devtmpfs', '/dev/root']
default_to_devices = devices is False and paths is False
with open(PROCDIR + '/mounts', 'rb') as mounts:
proc_mounts = mounts.readlines()
for line in proc_mounts:
fields = [as_string(f) for f in line.split()]
if len(fields) < 3:
continue
if realpath:
device = os.path.realpath(fields[0]) if fields[0].startswith('/') else fields[0]
else:
device = fields[0]
path = os.path.realpath(fields[1])
# only care about actual existing devices
if not os.path.exists(device) or not device.startswith('/'):
if device not in do_not_skip:
continue
if device in devices_mounted.keys():
devices_mounted[device].append(path)
else:
devices_mounted[device] = [path]
if path in paths_mounted.keys():
paths_mounted[path].append(device)
else:
paths_mounted[path] = [device]
# Default to returning information for devices if
if devices is True or default_to_devices:
return devices_mounted
else:
return paths_mounted | [
"def",
"get_mounts",
"(",
"devices",
"=",
"False",
",",
"paths",
"=",
"False",
",",
"realpath",
"=",
"False",
")",
":",
"devices_mounted",
"=",
"{",
"}",
"paths_mounted",
"=",
"{",
"}",
"do_not_skip",
"=",
"[",
"'tmpfs'",
",",
"'devtmpfs'",
",",
"'/dev/root'",
"]",
"default_to_devices",
"=",
"devices",
"is",
"False",
"and",
"paths",
"is",
"False",
"with",
"open",
"(",
"PROCDIR",
"+",
"'/mounts'",
",",
"'rb'",
")",
"as",
"mounts",
":",
"proc_mounts",
"=",
"mounts",
".",
"readlines",
"(",
")",
"for",
"line",
"in",
"proc_mounts",
":",
"fields",
"=",
"[",
"as_string",
"(",
"f",
")",
"for",
"f",
"in",
"line",
".",
"split",
"(",
")",
"]",
"if",
"len",
"(",
"fields",
")",
"<",
"3",
":",
"continue",
"if",
"realpath",
":",
"device",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"fields",
"[",
"0",
"]",
")",
"if",
"fields",
"[",
"0",
"]",
".",
"startswith",
"(",
"'/'",
")",
"else",
"fields",
"[",
"0",
"]",
"else",
":",
"device",
"=",
"fields",
"[",
"0",
"]",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"fields",
"[",
"1",
"]",
")",
"# only care about actual existing devices",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"device",
")",
"or",
"not",
"device",
".",
"startswith",
"(",
"'/'",
")",
":",
"if",
"device",
"not",
"in",
"do_not_skip",
":",
"continue",
"if",
"device",
"in",
"devices_mounted",
".",
"keys",
"(",
")",
":",
"devices_mounted",
"[",
"device",
"]",
".",
"append",
"(",
"path",
")",
"else",
":",
"devices_mounted",
"[",
"device",
"]",
"=",
"[",
"path",
"]",
"if",
"path",
"in",
"paths_mounted",
".",
"keys",
"(",
")",
":",
"paths_mounted",
"[",
"path",
"]",
".",
"append",
"(",
"device",
")",
"else",
":",
"paths_mounted",
"[",
"path",
"]",
"=",
"[",
"device",
"]",
"# Default to returning information for devices if",
"if",
"devices",
"is",
"True",
"or",
"default_to_devices",
":",
"return",
"devices_mounted",
"else",
":",
"return",
"paths_mounted"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/util/system.py#L286-L339 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/MythTV/database.py | python | DBData._pull | (self) | Updates table with data pulled from database. | Updates table with data pulled from database. | [
"Updates",
"table",
"with",
"data",
"pulled",
"from",
"database",
"."
] | def _pull(self):
"""Updates table with data pulled from database."""
with self._db.cursor(self._log) as cursor:
cursor.execute("""SELECT * FROM %s WHERE %s""" \
% (self._table, self._where), self._getwheredat())
res = cursor.fetchall()
if len(res) == 0:
raise MythError('DBData() could not read from database')
elif len(res) > 1:
raise MythError('DBData() could not find unique entry')
data = res[0]
DictData.update(self, self._process(data)) | [
"def",
"_pull",
"(",
"self",
")",
":",
"with",
"self",
".",
"_db",
".",
"cursor",
"(",
"self",
".",
"_log",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"SELECT * FROM %s WHERE %s\"\"\"",
"%",
"(",
"self",
".",
"_table",
",",
"self",
".",
"_where",
")",
",",
"self",
".",
"_getwheredat",
"(",
")",
")",
"res",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"if",
"len",
"(",
"res",
")",
"==",
"0",
":",
"raise",
"MythError",
"(",
"'DBData() could not read from database'",
")",
"elif",
"len",
"(",
"res",
")",
">",
"1",
":",
"raise",
"MythError",
"(",
"'DBData() could not find unique entry'",
")",
"data",
"=",
"res",
"[",
"0",
"]",
"DictData",
".",
"update",
"(",
"self",
",",
"self",
".",
"_process",
"(",
"data",
")",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/database.py#L197-L208 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_extends/parallel_compile/tbe_compiler/tbe_job_manager.py | python | post_job | (jobs, new_job) | add the new job into jobs list
:param jobs: job list
:param new_job : new job
:return: None | add the new job into jobs list
:param jobs: job list
:param new_job : new job
:return: None | [
"add",
"the",
"new",
"job",
"into",
"jobs",
"list",
":",
"param",
"jobs",
":",
"job",
"list",
":",
"param",
"new_job",
":",
"new",
"job",
":",
"return",
":",
"None"
] | def post_job(jobs, new_job):
"""
add the new job into jobs list
:param jobs: job list
:param new_job : new job
:return: None
"""
if new_job.source_id not in jobs.keys():
jobs[new_job.source_id] = dict()
jobs[new_job.source_id][new_job.id] = new_job
else:
jobs[new_job.source_id][new_job.id] = new_job | [
"def",
"post_job",
"(",
"jobs",
",",
"new_job",
")",
":",
"if",
"new_job",
".",
"source_id",
"not",
"in",
"jobs",
".",
"keys",
"(",
")",
":",
"jobs",
"[",
"new_job",
".",
"source_id",
"]",
"=",
"dict",
"(",
")",
"jobs",
"[",
"new_job",
".",
"source_id",
"]",
"[",
"new_job",
".",
"id",
"]",
"=",
"new_job",
"else",
":",
"jobs",
"[",
"new_job",
".",
"source_id",
"]",
"[",
"new_job",
".",
"id",
"]",
"=",
"new_job"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parallel_compile/tbe_compiler/tbe_job_manager.py#L485-L496 | ||
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/generator/msvs.py | python | _InitNinjaFlavor | (params, target_list, target_dicts) | Initialize targets for the ninja flavor.
This sets up the necessary variables in the targets to generate msvs projects
that use ninja as an external builder. The variables in the spec are only set
if they have not been set. This allows individual specs to override the
default values initialized here.
Arguments:
params: Params provided to the generator.
target_list: List of target pairs: 'base/base.gyp:base'.
target_dicts: Dict of target properties keyed on target pair. | Initialize targets for the ninja flavor. | [
"Initialize",
"targets",
"for",
"the",
"ninja",
"flavor",
"."
] | def _InitNinjaFlavor(params, target_list, target_dicts):
"""Initialize targets for the ninja flavor.
This sets up the necessary variables in the targets to generate msvs projects
that use ninja as an external builder. The variables in the spec are only set
if they have not been set. This allows individual specs to override the
default values initialized here.
Arguments:
params: Params provided to the generator.
target_list: List of target pairs: 'base/base.gyp:base'.
target_dicts: Dict of target properties keyed on target pair.
"""
for qualified_target in target_list:
spec = target_dicts[qualified_target]
if spec.get('msvs_external_builder'):
# The spec explicitly defined an external builder, so don't change it.
continue
path_to_ninja = spec.get('msvs_path_to_ninja', 'ninja.exe')
spec['msvs_external_builder'] = 'ninja'
if not spec.get('msvs_external_builder_out_dir'):
gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target)
gyp_dir = os.path.dirname(gyp_file)
configuration = '$(Configuration)'
if params.get('target_arch') == 'x64':
configuration += '_x64'
spec['msvs_external_builder_out_dir'] = os.path.join(
gyp.common.RelativePath(params['options'].toplevel_dir, gyp_dir),
ninja_generator.ComputeOutputDir(params),
configuration)
if not spec.get('msvs_external_builder_build_cmd'):
spec['msvs_external_builder_build_cmd'] = [
path_to_ninja,
'-C',
'$(OutDir)',
'$(ProjectName)',
]
if not spec.get('msvs_external_builder_clean_cmd'):
spec['msvs_external_builder_clean_cmd'] = [
path_to_ninja,
'-C',
'$(OutDir)',
'-tclean',
'$(ProjectName)',
] | [
"def",
"_InitNinjaFlavor",
"(",
"params",
",",
"target_list",
",",
"target_dicts",
")",
":",
"for",
"qualified_target",
"in",
"target_list",
":",
"spec",
"=",
"target_dicts",
"[",
"qualified_target",
"]",
"if",
"spec",
".",
"get",
"(",
"'msvs_external_builder'",
")",
":",
"# The spec explicitly defined an external builder, so don't change it.",
"continue",
"path_to_ninja",
"=",
"spec",
".",
"get",
"(",
"'msvs_path_to_ninja'",
",",
"'ninja.exe'",
")",
"spec",
"[",
"'msvs_external_builder'",
"]",
"=",
"'ninja'",
"if",
"not",
"spec",
".",
"get",
"(",
"'msvs_external_builder_out_dir'",
")",
":",
"gyp_file",
",",
"_",
",",
"_",
"=",
"gyp",
".",
"common",
".",
"ParseQualifiedTarget",
"(",
"qualified_target",
")",
"gyp_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"gyp_file",
")",
"configuration",
"=",
"'$(Configuration)'",
"if",
"params",
".",
"get",
"(",
"'target_arch'",
")",
"==",
"'x64'",
":",
"configuration",
"+=",
"'_x64'",
"spec",
"[",
"'msvs_external_builder_out_dir'",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"gyp",
".",
"common",
".",
"RelativePath",
"(",
"params",
"[",
"'options'",
"]",
".",
"toplevel_dir",
",",
"gyp_dir",
")",
",",
"ninja_generator",
".",
"ComputeOutputDir",
"(",
"params",
")",
",",
"configuration",
")",
"if",
"not",
"spec",
".",
"get",
"(",
"'msvs_external_builder_build_cmd'",
")",
":",
"spec",
"[",
"'msvs_external_builder_build_cmd'",
"]",
"=",
"[",
"path_to_ninja",
",",
"'-C'",
",",
"'$(OutDir)'",
",",
"'$(ProjectName)'",
",",
"]",
"if",
"not",
"spec",
".",
"get",
"(",
"'msvs_external_builder_clean_cmd'",
")",
":",
"spec",
"[",
"'msvs_external_builder_clean_cmd'",
"]",
"=",
"[",
"path_to_ninja",
",",
"'-C'",
",",
"'$(OutDir)'",
",",
"'-tclean'",
",",
"'$(ProjectName)'",
",",
"]"
] | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/msvs.py#L1842-L1887 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/datetime.py | python | timedelta.days | (self) | return self._days | days | days | [
"days"
] | def days(self):
"""days"""
return self._days | [
"def",
"days",
"(",
"self",
")",
":",
"return",
"self",
".",
"_days"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/datetime.py#L626-L628 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/sparse/linalg/_onenormest.py | python | onenormest | (A, t=2, itmax=5, compute_v=False, compute_w=False) | Compute a lower bound of the 1-norm of a sparse matrix.
Parameters
----------
A : ndarray or other linear operator
A linear operator that can be transposed and that can
produce matrix products.
t : int, optional
A positive parameter controlling the tradeoff between
accuracy versus time and memory usage.
Larger values take longer and use more memory
but give more accurate output.
itmax : int, optional
Use at most this many iterations.
compute_v : bool, optional
Request a norm-maximizing linear operator input vector if True.
compute_w : bool, optional
Request a norm-maximizing linear operator output vector if True.
Returns
-------
est : float
An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
The vector such that ||Av||_1 == est*||v||_1.
It can be thought of as an input to the linear operator
that gives an output with particularly large norm.
w : ndarray, optional
The vector Av which has relatively large 1-norm.
It can be thought of as an output of the linear operator
that is relatively large in norm compared to the input.
Notes
-----
This is algorithm 2.4 of [1].
In [2] it is described as follows.
"This algorithm typically requires the evaluation of
about 4t matrix-vector products and almost invariably
produces a norm estimate (which is, in fact, a lower
bound on the norm) correct to within a factor 3."
.. versionadded:: 0.13.0
References
----------
.. [1] Nicholas J. Higham and Francoise Tisseur (2000),
"A Block Algorithm for Matrix 1-Norm Estimation,
with an Application to 1-Norm Pseudospectra."
SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201.
.. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
"A new scaling and squaring algorithm for the matrix exponential."
SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import onenormest
>>> A = csc_matrix([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float)
>>> A.todense()
matrix([[ 1., 0., 0.],
[ 5., 8., 2.],
[ 0., -1., 0.]])
>>> onenormest(A)
9.0
>>> np.linalg.norm(A.todense(), ord=1)
9.0 | Compute a lower bound of the 1-norm of a sparse matrix. | [
"Compute",
"a",
"lower",
"bound",
"of",
"the",
"1",
"-",
"norm",
"of",
"a",
"sparse",
"matrix",
"."
] | def onenormest(A, t=2, itmax=5, compute_v=False, compute_w=False):
"""
Compute a lower bound of the 1-norm of a sparse matrix.
Parameters
----------
A : ndarray or other linear operator
A linear operator that can be transposed and that can
produce matrix products.
t : int, optional
A positive parameter controlling the tradeoff between
accuracy versus time and memory usage.
Larger values take longer and use more memory
but give more accurate output.
itmax : int, optional
Use at most this many iterations.
compute_v : bool, optional
Request a norm-maximizing linear operator input vector if True.
compute_w : bool, optional
Request a norm-maximizing linear operator output vector if True.
Returns
-------
est : float
An underestimate of the 1-norm of the sparse matrix.
v : ndarray, optional
The vector such that ||Av||_1 == est*||v||_1.
It can be thought of as an input to the linear operator
that gives an output with particularly large norm.
w : ndarray, optional
The vector Av which has relatively large 1-norm.
It can be thought of as an output of the linear operator
that is relatively large in norm compared to the input.
Notes
-----
This is algorithm 2.4 of [1].
In [2] it is described as follows.
"This algorithm typically requires the evaluation of
about 4t matrix-vector products and almost invariably
produces a norm estimate (which is, in fact, a lower
bound on the norm) correct to within a factor 3."
.. versionadded:: 0.13.0
References
----------
.. [1] Nicholas J. Higham and Francoise Tisseur (2000),
"A Block Algorithm for Matrix 1-Norm Estimation,
with an Application to 1-Norm Pseudospectra."
SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201.
.. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
"A new scaling and squaring algorithm for the matrix exponential."
SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import onenormest
>>> A = csc_matrix([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float)
>>> A.todense()
matrix([[ 1., 0., 0.],
[ 5., 8., 2.],
[ 0., -1., 0.]])
>>> onenormest(A)
9.0
>>> np.linalg.norm(A.todense(), ord=1)
9.0
"""
# Check the input.
A = aslinearoperator(A)
if A.shape[0] != A.shape[1]:
raise ValueError('expected the operator to act like a square matrix')
# If the operator size is small compared to t,
# then it is easier to compute the exact norm.
# Otherwise estimate the norm.
n = A.shape[1]
if t >= n:
A_explicit = np.asarray(aslinearoperator(A).matmat(np.identity(n)))
if A_explicit.shape != (n, n):
raise Exception('internal error: ',
'unexpected shape ' + str(A_explicit.shape))
col_abs_sums = abs(A_explicit).sum(axis=0)
if col_abs_sums.shape != (n, ):
raise Exception('internal error: ',
'unexpected shape ' + str(col_abs_sums.shape))
argmax_j = np.argmax(col_abs_sums)
v = elementary_vector(n, argmax_j)
w = A_explicit[:, argmax_j]
est = col_abs_sums[argmax_j]
else:
est, v, w, nmults, nresamples = _onenormest_core(A, A.H, t, itmax)
# Report the norm estimate along with some certificates of the estimate.
if compute_v or compute_w:
result = (est,)
if compute_v:
result += (v,)
if compute_w:
result += (w,)
return result
else:
return est | [
"def",
"onenormest",
"(",
"A",
",",
"t",
"=",
"2",
",",
"itmax",
"=",
"5",
",",
"compute_v",
"=",
"False",
",",
"compute_w",
"=",
"False",
")",
":",
"# Check the input.",
"A",
"=",
"aslinearoperator",
"(",
"A",
")",
"if",
"A",
".",
"shape",
"[",
"0",
"]",
"!=",
"A",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'expected the operator to act like a square matrix'",
")",
"# If the operator size is small compared to t,",
"# then it is easier to compute the exact norm.",
"# Otherwise estimate the norm.",
"n",
"=",
"A",
".",
"shape",
"[",
"1",
"]",
"if",
"t",
">=",
"n",
":",
"A_explicit",
"=",
"np",
".",
"asarray",
"(",
"aslinearoperator",
"(",
"A",
")",
".",
"matmat",
"(",
"np",
".",
"identity",
"(",
"n",
")",
")",
")",
"if",
"A_explicit",
".",
"shape",
"!=",
"(",
"n",
",",
"n",
")",
":",
"raise",
"Exception",
"(",
"'internal error: '",
",",
"'unexpected shape '",
"+",
"str",
"(",
"A_explicit",
".",
"shape",
")",
")",
"col_abs_sums",
"=",
"abs",
"(",
"A_explicit",
")",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"if",
"col_abs_sums",
".",
"shape",
"!=",
"(",
"n",
",",
")",
":",
"raise",
"Exception",
"(",
"'internal error: '",
",",
"'unexpected shape '",
"+",
"str",
"(",
"col_abs_sums",
".",
"shape",
")",
")",
"argmax_j",
"=",
"np",
".",
"argmax",
"(",
"col_abs_sums",
")",
"v",
"=",
"elementary_vector",
"(",
"n",
",",
"argmax_j",
")",
"w",
"=",
"A_explicit",
"[",
":",
",",
"argmax_j",
"]",
"est",
"=",
"col_abs_sums",
"[",
"argmax_j",
"]",
"else",
":",
"est",
",",
"v",
",",
"w",
",",
"nmults",
",",
"nresamples",
"=",
"_onenormest_core",
"(",
"A",
",",
"A",
".",
"H",
",",
"t",
",",
"itmax",
")",
"# Report the norm estimate along with some certificates of the estimate.",
"if",
"compute_v",
"or",
"compute_w",
":",
"result",
"=",
"(",
"est",
",",
")",
"if",
"compute_v",
":",
"result",
"+=",
"(",
"v",
",",
")",
"if",
"compute_w",
":",
"result",
"+=",
"(",
"w",
",",
")",
"return",
"result",
"else",
":",
"return",
"est"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/linalg/_onenormest.py#L13-L119 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/tix.py | python | Grid.nearest | (self, x, y) | return self._getints(self.tk.call(self, 'nearest', x, y)) | Return coordinate of cell nearest pixel coordinate (x,y) | Return coordinate of cell nearest pixel coordinate (x,y) | [
"Return",
"coordinate",
"of",
"cell",
"nearest",
"pixel",
"coordinate",
"(",
"x",
"y",
")"
] | def nearest(self, x, y):
"Return coordinate of cell nearest pixel coordinate (x,y)"
return self._getints(self.tk.call(self, 'nearest', x, y)) | [
"def",
"nearest",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'nearest'",
",",
"x",
",",
"y",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/tix.py#L1867-L1869 | |
OpenLightingProject/ola | d1433a1bed73276fbe55ce18c03b1c208237decc | python/ola/rpc/StreamRpcChannel.py | python | StreamRpcChannel._ProcessIncomingData | (self) | Process the received data. | Process the received data. | [
"Process",
"the",
"received",
"data",
"."
] | def _ProcessIncomingData(self):
"""Process the received data."""
while True:
if not self._expected_size:
# this is a new msg
raw_header = self._GrabData(4)
if not raw_header:
# not enough data yet
return
if self._log_msgs:
logging.debug("recvhdr<-" + str(binascii.hexlify(raw_header)))
header = struct.unpack('=L', raw_header)[0]
version, size = self._DecodeHeader(header)
if version != self.PROTOCOL_VERSION:
ola_logger.warning('Protocol mismatch: %d != %d', version,
self.PROTOCOL_VERSION)
self._skip_message = True
self._expected_size = size
data = self._GrabData(self._expected_size)
if not data:
# not enough data yet
return
if self._log_msgs:
logging.debug("recvmsg<-" + str(binascii.hexlify(data)))
if not self._skip_message:
self._HandleNewMessage(data)
self._expected_size = 0
self._skip_message = 0 | [
"def",
"_ProcessIncomingData",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"not",
"self",
".",
"_expected_size",
":",
"# this is a new msg",
"raw_header",
"=",
"self",
".",
"_GrabData",
"(",
"4",
")",
"if",
"not",
"raw_header",
":",
"# not enough data yet",
"return",
"if",
"self",
".",
"_log_msgs",
":",
"logging",
".",
"debug",
"(",
"\"recvhdr<-\"",
"+",
"str",
"(",
"binascii",
".",
"hexlify",
"(",
"raw_header",
")",
")",
")",
"header",
"=",
"struct",
".",
"unpack",
"(",
"'=L'",
",",
"raw_header",
")",
"[",
"0",
"]",
"version",
",",
"size",
"=",
"self",
".",
"_DecodeHeader",
"(",
"header",
")",
"if",
"version",
"!=",
"self",
".",
"PROTOCOL_VERSION",
":",
"ola_logger",
".",
"warning",
"(",
"'Protocol mismatch: %d != %d'",
",",
"version",
",",
"self",
".",
"PROTOCOL_VERSION",
")",
"self",
".",
"_skip_message",
"=",
"True",
"self",
".",
"_expected_size",
"=",
"size",
"data",
"=",
"self",
".",
"_GrabData",
"(",
"self",
".",
"_expected_size",
")",
"if",
"not",
"data",
":",
"# not enough data yet",
"return",
"if",
"self",
".",
"_log_msgs",
":",
"logging",
".",
"debug",
"(",
"\"recvmsg<-\"",
"+",
"str",
"(",
"binascii",
".",
"hexlify",
"(",
"data",
")",
")",
")",
"if",
"not",
"self",
".",
"_skip_message",
":",
"self",
".",
"_HandleNewMessage",
"(",
"data",
")",
"self",
".",
"_expected_size",
"=",
"0",
"self",
".",
"_skip_message",
"=",
"0"
] | https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/rpc/StreamRpcChannel.py#L241-L272 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/traceback.py | python | extract_stack | (f=None, limit=None) | return stack | Extract the raw traceback from the current stack frame.
The return value has the same format as for extract_tb(). The
optional 'f' and 'limit' arguments have the same meaning as for
print_stack(). Each item in the list is a quadruple (filename,
line number, function name, text), and the entries are in order
from oldest to newest stack frame. | Extract the raw traceback from the current stack frame. | [
"Extract",
"the",
"raw",
"traceback",
"from",
"the",
"current",
"stack",
"frame",
"."
] | def extract_stack(f=None, limit=None):
"""Extract the raw traceback from the current stack frame.
The return value has the same format as for extract_tb(). The
optional 'f' and 'limit' arguments have the same meaning as for
print_stack(). Each item in the list is a quadruple (filename,
line number, function name, text), and the entries are in order
from oldest to newest stack frame.
"""
if f is None:
f = sys._getframe().f_back
stack = StackSummary.extract(walk_stack(f), limit=limit)
stack.reverse()
return stack | [
"def",
"extract_stack",
"(",
"f",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"f",
"is",
"None",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
"stack",
"=",
"StackSummary",
".",
"extract",
"(",
"walk_stack",
"(",
"f",
")",
",",
"limit",
"=",
"limit",
")",
"stack",
".",
"reverse",
"(",
")",
"return",
"stack"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/traceback.py#L200-L213 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | GridRangeSelectEvent.__init__ | (self, *args, **kwargs) | __init__(self, int id, EventType type, Grid obj, GridCellCoords topLeft,
GridCellCoords bottomRight, bool sel=True,
bool control=False, bool shift=False, bool alt=False,
bool meta=False) -> GridRangeSelectEvent | __init__(self, int id, EventType type, Grid obj, GridCellCoords topLeft,
GridCellCoords bottomRight, bool sel=True,
bool control=False, bool shift=False, bool alt=False,
bool meta=False) -> GridRangeSelectEvent | [
"__init__",
"(",
"self",
"int",
"id",
"EventType",
"type",
"Grid",
"obj",
"GridCellCoords",
"topLeft",
"GridCellCoords",
"bottomRight",
"bool",
"sel",
"=",
"True",
"bool",
"control",
"=",
"False",
"bool",
"shift",
"=",
"False",
"bool",
"alt",
"=",
"False",
"bool",
"meta",
"=",
"False",
")",
"-",
">",
"GridRangeSelectEvent"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, int id, EventType type, Grid obj, GridCellCoords topLeft,
GridCellCoords bottomRight, bool sel=True,
bool control=False, bool shift=False, bool alt=False,
bool meta=False) -> GridRangeSelectEvent
"""
_grid.GridRangeSelectEvent_swiginit(self,_grid.new_GridRangeSelectEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_grid",
".",
"GridRangeSelectEvent_swiginit",
"(",
"self",
",",
"_grid",
".",
"new_GridRangeSelectEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2393-L2400 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/profiler/profile_context.py | python | ProfileContext.profiler | (self) | return self._profiler | Returns the current profiler object. | Returns the current profiler object. | [
"Returns",
"the",
"current",
"profiler",
"object",
"."
] | def profiler(self):
"""Returns the current profiler object."""
if not self._profiler:
self._profiler = model_analyzer.Profiler(ops.get_default_graph())
return self._profiler | [
"def",
"profiler",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_profiler",
":",
"self",
".",
"_profiler",
"=",
"model_analyzer",
".",
"Profiler",
"(",
"ops",
".",
"get_default_graph",
"(",
")",
")",
"return",
"self",
".",
"_profiler"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/profiler/profile_context.py#L181-L185 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.