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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Window.SetExtraStyle | (*args, **kwargs) | return _core_.Window_SetExtraStyle(*args, **kwargs) | SetExtraStyle(self, long exStyle)
Sets the extra style bits for the window. Extra styles are the less
often used style bits which can't be set with the constructor or with
SetWindowStyleFlag() | SetExtraStyle(self, long exStyle) | [
"SetExtraStyle",
"(",
"self",
"long",
"exStyle",
")"
] | def SetExtraStyle(*args, **kwargs):
"""
SetExtraStyle(self, long exStyle)
Sets the extra style bits for the window. Extra styles are the less
often used style bits which can't be set with the constructor or with
SetWindowStyleFlag()
"""
return _core_.Window_SetExtraStyle(*args, **kwargs) | [
"def",
"SetExtraStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_SetExtraStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L10063-L10071 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/array_grad.py | python | _ReshapeToInput | (op, grad) | return array_ops.reshape(grad, array_ops.shape(op.inputs[0])) | Reshapes the gradient to the shape of the original input. | Reshapes the gradient to the shape of the original input. | [
"Reshapes",
"the",
"gradient",
"to",
"the",
"shape",
"of",
"the",
"original",
"input",
"."
] | def _ReshapeToInput(op, grad):
"""Reshapes the gradient to the shape of the original input."""
return array_ops.reshape(grad, array_ops.shape(op.inputs[0])) | [
"def",
"_ReshapeToInput",
"(",
"op",
",",
"grad",
")",
":",
"return",
"array_ops",
".",
"reshape",
"(",
"grad",
",",
"array_ops",
".",
"shape",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/array_grad.py#L486-L488 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py | python | build_sdist | (sdist_directory, config_settings) | Invoke the mandatory build_sdist hook. | Invoke the mandatory build_sdist hook. | [
"Invoke",
"the",
"mandatory",
"build_sdist",
"hook",
"."
] | def build_sdist(sdist_directory, config_settings):
"""Invoke the mandatory build_sdist hook."""
backend = _build_backend()
try:
return backend.build_sdist(sdist_directory, config_settings)
except getattr(backend, 'UnsupportedOperation', _DummyException):
raise GotUnsupportedOperation(traceback.format_exc()) | [
"def",
"build_sdist",
"(",
"sdist_directory",
",",
"config_settings",
")",
":",
"backend",
"=",
"_build_backend",
"(",
")",
"try",
":",
"return",
"backend",
".",
"build_sdist",
"(",
"sdist_directory",
",",
"config_settings",
")",
"except",
"getattr",
"(",
"backend",
",",
"'UnsupportedOperation'",
",",
"_DummyException",
")",
":",
"raise",
"GotUnsupportedOperation",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py#L463-L475 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/backend.py | python | clip | (x, min_value, max_value) | return clip_ops.clip_by_value(x, min_value, max_value) | Element-wise value clipping.
Arguments:
x: Tensor or variable.
min_value: Python float or integer.
max_value: Python float or integer.
Returns:
A tensor. | Element-wise value clipping. | [
"Element",
"-",
"wise",
"value",
"clipping",
"."
] | def clip(x, min_value, max_value):
"""Element-wise value clipping.
Arguments:
x: Tensor or variable.
min_value: Python float or integer.
max_value: Python float or integer.
Returns:
A tensor.
"""
if max_value is not None and max_value < min_value:
max_value = min_value
if max_value is None:
max_value = np.inf
min_value = _to_tensor(min_value, x.dtype.base_dtype)
max_value = _to_tensor(max_value, x.dtype.base_dtype)
return clip_ops.clip_by_value(x, min_value, max_value) | [
"def",
"clip",
"(",
"x",
",",
"min_value",
",",
"max_value",
")",
":",
"if",
"max_value",
"is",
"not",
"None",
"and",
"max_value",
"<",
"min_value",
":",
"max_value",
"=",
"min_value",
"if",
"max_value",
"is",
"None",
":",
"max_value",
"=",
"np",
".",
"inf",
"min_value",
"=",
"_to_tensor",
"(",
"min_value",
",",
"x",
".",
"dtype",
".",
"base_dtype",
")",
"max_value",
"=",
"_to_tensor",
"(",
"max_value",
",",
"x",
".",
"dtype",
".",
"base_dtype",
")",
"return",
"clip_ops",
".",
"clip_by_value",
"(",
"x",
",",
"min_value",
",",
"max_value",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L1645-L1662 | |
NervanaSystems/ngraph | f677a119765ca30636cf407009dabd118664951f | python/src/ngraph/utils/types.py | python | as_nodes | (*input_values: NodeInput) | return [as_node(input_value) for input_value in input_values] | Return input values as nodes. Scalars will be converted to Constant nodes. | Return input values as nodes. Scalars will be converted to Constant nodes. | [
"Return",
"input",
"values",
"as",
"nodes",
".",
"Scalars",
"will",
"be",
"converted",
"to",
"Constant",
"nodes",
"."
] | def as_nodes(*input_values: NodeInput) -> List[Node]:
"""Return input values as nodes. Scalars will be converted to Constant nodes."""
return [as_node(input_value) for input_value in input_values] | [
"def",
"as_nodes",
"(",
"*",
"input_values",
":",
"NodeInput",
")",
"->",
"List",
"[",
"Node",
"]",
":",
"return",
"[",
"as_node",
"(",
"input_value",
")",
"for",
"input_value",
"in",
"input_values",
"]"
] | https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/utils/types.py#L145-L147 | |
calamares/calamares | 9f6f82405b3074af7c99dc26487d2e46e4ece3e5 | src/modules/networkcfg/main.py | python | get_live_user | () | return None | Gets the "live user" login. This might be "live", or "nitrux",
or something similar: it is the login name used *right now*,
and network configurations saved for that user, should be applied
also for the installed user (which probably has a different name). | Gets the "live user" login. This might be "live", or "nitrux",
or something similar: it is the login name used *right now*,
and network configurations saved for that user, should be applied
also for the installed user (which probably has a different name). | [
"Gets",
"the",
"live",
"user",
"login",
".",
"This",
"might",
"be",
"live",
"or",
"nitrux",
"or",
"something",
"similar",
":",
"it",
"is",
"the",
"login",
"name",
"used",
"*",
"right",
"now",
"*",
"and",
"network",
"configurations",
"saved",
"for",
"that",
"user",
"should",
"be",
"applied",
"also",
"for",
"the",
"installed",
"user",
"(",
"which",
"probably",
"has",
"a",
"different",
"name",
")",
"."
] | def get_live_user():
"""
Gets the "live user" login. This might be "live", or "nitrux",
or something similar: it is the login name used *right now*,
and network configurations saved for that user, should be applied
also for the installed user (which probably has a different name).
"""
# getlogin() is a thin-wrapper, and depends on getlogin(3),
# which reads utmp -- and utmp isn't always set up right.
try:
return os.getlogin()
except OSError:
pass
# getpass will return the **current** user, which is generally root.
# That isn't very useful, because the network settings have been
# made outside of Calamares-running-as-root, as a different user.
#
# If Calamares is running as non-root, though, this is fine.
import getpass
name = getpass.getuser()
if name != "root":
return name
# TODO: other mechanisms, e.g. guessing that "live" is the name
# TODO: support a what-is-the-live-user setting
return None | [
"def",
"get_live_user",
"(",
")",
":",
"# getlogin() is a thin-wrapper, and depends on getlogin(3),",
"# which reads utmp -- and utmp isn't always set up right.",
"try",
":",
"return",
"os",
".",
"getlogin",
"(",
")",
"except",
"OSError",
":",
"pass",
"# getpass will return the **current** user, which is generally root.",
"# That isn't very useful, because the network settings have been",
"# made outside of Calamares-running-as-root, as a different user.",
"#",
"# If Calamares is running as non-root, though, this is fine.",
"import",
"getpass",
"name",
"=",
"getpass",
".",
"getuser",
"(",
")",
"if",
"name",
"!=",
"\"root\"",
":",
"return",
"name",
"# TODO: other mechanisms, e.g. guessing that \"live\" is the name",
"# TODO: support a what-is-the-live-user setting",
"return",
"None"
] | https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/networkcfg/main.py#L32-L57 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/command/easy_install.py | python | WindowsScriptWriter._use_header | (new_header) | return sys.platform != 'win32' or find_executable(clean_header) | Should _adjust_header use the replaced header?
On non-windows systems, always use. On
Windows systems, only use the replaced header if it resolves
to an executable on the system. | Should _adjust_header use the replaced header? | [
"Should",
"_adjust_header",
"use",
"the",
"replaced",
"header?"
] | def _use_header(new_header):
"""
Should _adjust_header use the replaced header?
On non-windows systems, always use. On
Windows systems, only use the replaced header if it resolves
to an executable on the system.
"""
clean_header = new_header[2:-1].strip('"')
return sys.platform != 'win32' or find_executable(clean_header) | [
"def",
"_use_header",
"(",
"new_header",
")",
":",
"clean_header",
"=",
"new_header",
"[",
"2",
":",
"-",
"1",
"]",
".",
"strip",
"(",
"'\"'",
")",
"return",
"sys",
".",
"platform",
"!=",
"'win32'",
"or",
"find_executable",
"(",
"clean_header",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/command/easy_install.py#L2214-L2223 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/front/subgraph_matcher.py | python | SubgraphMatch.single_input_node | (self, port: int) | return input_nodes[0] | The function does the same as function 'input_nodes' but it relies on fact that there is just one node that
gets input tensor for sub-graph input with number 'port', so it return just tuple (Node, nodePort) or raises
exception if the amount of nodes is not equal to 1.
:param port: input port of the sub-graph.
:return: tuple describing node of the sub-graph getting tensor through the specified port. | The function does the same as function 'input_nodes' but it relies on fact that there is just one node that
gets input tensor for sub-graph input with number 'port', so it return just tuple (Node, nodePort) or raises
exception if the amount of nodes is not equal to 1.
:param port: input port of the sub-graph.
:return: tuple describing node of the sub-graph getting tensor through the specified port. | [
"The",
"function",
"does",
"the",
"same",
"as",
"function",
"input_nodes",
"but",
"it",
"relies",
"on",
"fact",
"that",
"there",
"is",
"just",
"one",
"node",
"that",
"gets",
"input",
"tensor",
"for",
"sub",
"-",
"graph",
"input",
"with",
"number",
"port",
"so",
"it",
"return",
"just",
"tuple",
"(",
"Node",
"nodePort",
")",
"or",
"raises",
"exception",
"if",
"the",
"amount",
"of",
"nodes",
"is",
"not",
"equal",
"to",
"1",
".",
":",
"param",
"port",
":",
"input",
"port",
"of",
"the",
"sub",
"-",
"graph",
".",
":",
"return",
":",
"tuple",
"describing",
"node",
"of",
"the",
"sub",
"-",
"graph",
"getting",
"tensor",
"through",
"the",
"specified",
"port",
"."
] | def single_input_node(self, port: int):
"""
The function does the same as function 'input_nodes' but it relies on fact that there is just one node that
gets input tensor for sub-graph input with number 'port', so it return just tuple (Node, nodePort) or raises
exception if the amount of nodes is not equal to 1.
:param port: input port of the sub-graph.
:return: tuple describing node of the sub-graph getting tensor through the specified port.
"""
input_nodes = self.input_nodes(port)
if len(input_nodes) != 1:
raise Error('The amount of input nodes for port "{}" is not equal to 1. '.format(port) +
refer_to_faq_msg(33))
return input_nodes[0] | [
"def",
"single_input_node",
"(",
"self",
",",
"port",
":",
"int",
")",
":",
"input_nodes",
"=",
"self",
".",
"input_nodes",
"(",
"port",
")",
"if",
"len",
"(",
"input_nodes",
")",
"!=",
"1",
":",
"raise",
"Error",
"(",
"'The amount of input nodes for port \"{}\" is not equal to 1. '",
".",
"format",
"(",
"port",
")",
"+",
"refer_to_faq_msg",
"(",
"33",
")",
")",
"return",
"input_nodes",
"[",
"0",
"]"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/subgraph_matcher.py#L95-L107 | |
google/filament | d21f092645b8e1e312307cbf89f1484891347c63 | third_party/spirv-tools/utils/generate_language_headers.py | python | make_path_to_file | (f) | Makes all ancestor directories to the given file, if they
don't yet exist.
Arguments:
f: The file whose ancestor directories are to be created. | Makes all ancestor directories to the given file, if they
don't yet exist. | [
"Makes",
"all",
"ancestor",
"directories",
"to",
"the",
"given",
"file",
"if",
"they",
"don",
"t",
"yet",
"exist",
"."
] | def make_path_to_file(f):
"""Makes all ancestor directories to the given file, if they
don't yet exist.
Arguments:
f: The file whose ancestor directories are to be created.
"""
dir = os.path.dirname(os.path.abspath(f))
try:
os.makedirs(dir)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(dir):
pass
else:
raise | [
"def",
"make_path_to_file",
"(",
"f",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"f",
")",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"dir",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"dir",
")",
":",
"pass",
"else",
":",
"raise"
] | https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/spirv-tools/utils/generate_language_headers.py#L23-L37 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/models.py | python | Response.ok | (self) | return True | Returns True if :attr:`status_code` is less than 400, False if not.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``. | Returns True if :attr:`status_code` is less than 400, False if not. | [
"Returns",
"True",
"if",
":",
"attr",
":",
"status_code",
"is",
"less",
"than",
"400",
"False",
"if",
"not",
"."
] | def ok(self):
"""Returns True if :attr:`status_code` is less than 400, False if not.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
try:
self.raise_for_status()
except HTTPError:
return False
return True | [
"def",
"ok",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"raise_for_status",
"(",
")",
"except",
"HTTPError",
":",
"return",
"False",
"return",
"True"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/requests/models.py#L693-L705 | |
lukasmonk/lucaschess | 13e2e5cb13b38a720ccf897af649054a64bcb914 | Code/QT/QTUtil.py | python | qtBrush | (nColor) | return QtGui.QBrush(qtColor(nColor)) | Genera un brush a partir de un dato numerico | Genera un brush a partir de un dato numerico | [
"Genera",
"un",
"brush",
"a",
"partir",
"de",
"un",
"dato",
"numerico"
] | def qtBrush(nColor):
"""
Genera un brush a partir de un dato numerico
"""
return QtGui.QBrush(qtColor(nColor)) | [
"def",
"qtBrush",
"(",
"nColor",
")",
":",
"return",
"QtGui",
".",
"QBrush",
"(",
"qtColor",
"(",
"nColor",
")",
")"
] | https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/QT/QTUtil.py#L108-L112 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mach/mach/config.py | python | ConfigProvider.register_setting | (cls, section, option, type_cls, default=DefaultValue,
choices=None, domain=None) | Register a config setting with this type.
This is a convenience method to populate available settings. It is
typically called in the class's _register_settings() implementation.
Each setting must have:
section -- str section to which the setting belongs. This is how
settings are grouped.
option -- str id for the setting. This must be unique within the
section it appears.
type -- a ConfigType-derived type defining the type of the setting.
Each setting has the following optional parameters:
default -- The default value for the setting. If None (the default)
there is no default.
choices -- A set of values this setting can hold. Values not in
this set are invalid.
domain -- Translation domain for this setting. By default, the
domain is the same as the section name. | Register a config setting with this type. | [
"Register",
"a",
"config",
"setting",
"with",
"this",
"type",
"."
] | def register_setting(cls, section, option, type_cls, default=DefaultValue,
choices=None, domain=None):
"""Register a config setting with this type.
This is a convenience method to populate available settings. It is
typically called in the class's _register_settings() implementation.
Each setting must have:
section -- str section to which the setting belongs. This is how
settings are grouped.
option -- str id for the setting. This must be unique within the
section it appears.
type -- a ConfigType-derived type defining the type of the setting.
Each setting has the following optional parameters:
default -- The default value for the setting. If None (the default)
there is no default.
choices -- A set of values this setting can hold. Values not in
this set are invalid.
domain -- Translation domain for this setting. By default, the
domain is the same as the section name.
"""
if not section in cls.config_settings:
cls.config_settings[section] = {}
if option in cls.config_settings[section]:
raise Exception('Setting has already been registered: %s.%s' % (
section, option))
domain = domain if domain is not None else section
meta = {
'short': '%s.short' % option,
'full': '%s.full' % option,
'type_cls': type_cls,
'domain': domain,
'localedir': cls.config_settings_locale_directory,
}
if default != DefaultValue:
meta['default'] = default
if choices is not None:
meta['choices'] = choices
cls.config_settings[section][option] = meta | [
"def",
"register_setting",
"(",
"cls",
",",
"section",
",",
"option",
",",
"type_cls",
",",
"default",
"=",
"DefaultValue",
",",
"choices",
"=",
"None",
",",
"domain",
"=",
"None",
")",
":",
"if",
"not",
"section",
"in",
"cls",
".",
"config_settings",
":",
"cls",
".",
"config_settings",
"[",
"section",
"]",
"=",
"{",
"}",
"if",
"option",
"in",
"cls",
".",
"config_settings",
"[",
"section",
"]",
":",
"raise",
"Exception",
"(",
"'Setting has already been registered: %s.%s'",
"%",
"(",
"section",
",",
"option",
")",
")",
"domain",
"=",
"domain",
"if",
"domain",
"is",
"not",
"None",
"else",
"section",
"meta",
"=",
"{",
"'short'",
":",
"'%s.short'",
"%",
"option",
",",
"'full'",
":",
"'%s.full'",
"%",
"option",
",",
"'type_cls'",
":",
"type_cls",
",",
"'domain'",
":",
"domain",
",",
"'localedir'",
":",
"cls",
".",
"config_settings_locale_directory",
",",
"}",
"if",
"default",
"!=",
"DefaultValue",
":",
"meta",
"[",
"'default'",
"]",
"=",
"default",
"if",
"choices",
"is",
"not",
"None",
":",
"meta",
"[",
"'choices'",
"]",
"=",
"choices",
"cls",
".",
"config_settings",
"[",
"section",
"]",
"[",
"option",
"]",
"=",
"meta"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mach/mach/config.py#L195-L246 | ||
oneapi-src/oneTBB | c9e43df34675ae5d9481c7ceab048085e3d5dae1 | python/tbb/pool.py | python | AbstractResultCollector.__init__ | (self, to_notify) | \param to_notify ApplyResult object to notify when all the
results we're waiting for become available. Can be None. | \param to_notify ApplyResult object to notify when all the
results we're waiting for become available. Can be None. | [
"\\",
"param",
"to_notify",
"ApplyResult",
"object",
"to",
"notify",
"when",
"all",
"the",
"results",
"we",
"re",
"waiting",
"for",
"become",
"available",
".",
"Can",
"be",
"None",
"."
] | def __init__(self, to_notify):
"""
\param to_notify ApplyResult object to notify when all the
results we're waiting for become available. Can be None.
"""
self._to_notify = to_notify | [
"def",
"__init__",
"(",
"self",
",",
"to_notify",
")",
":",
"self",
".",
"_to_notify",
"=",
"to_notify"
] | https://github.com/oneapi-src/oneTBB/blob/c9e43df34675ae5d9481c7ceab048085e3d5dae1/python/tbb/pool.py#L407-L412 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/extending.py | python | include_path | () | return path | Returns the C include directory path. | Returns the C include directory path. | [
"Returns",
"the",
"C",
"include",
"directory",
"path",
"."
] | def include_path():
"""Returns the C include directory path.
"""
include_dir = os.path.dirname(os.path.dirname(numba.__file__))
path = os.path.abspath(include_dir)
return path | [
"def",
"include_path",
"(",
")",
":",
"include_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"numba",
".",
"__file__",
")",
")",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"include_dir",
")",
"return",
"path"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/extending.py#L409-L414 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32comext/axscript/client/error.py | python | ProcessAXScriptException | (scriptingSite, debugManager, exceptionInstance) | General function to handle any exception in AX code
This function creates an instance of our IActiveScriptError interface, and
gives it to the host, along with out exception class. The host will
likely call back on the IActiveScriptError interface to get the source text
and other information not normally in COM exceptions. | General function to handle any exception in AX code | [
"General",
"function",
"to",
"handle",
"any",
"exception",
"in",
"AX",
"code"
] | def ProcessAXScriptException(scriptingSite, debugManager, exceptionInstance):
"""General function to handle any exception in AX code
This function creates an instance of our IActiveScriptError interface, and
gives it to the host, along with out exception class. The host will
likely call back on the IActiveScriptError interface to get the source text
and other information not normally in COM exceptions.
"""
# traceback.print_exc()
instance = IActiveScriptError()
instance._SetExceptionInfo(exceptionInstance)
gateway = win32com.server.util.wrap(instance, axscript.IID_IActiveScriptError)
if debugManager:
fCallOnError = debugManager.HandleRuntimeError()
if not fCallOnError:
return None
try:
result = scriptingSite.OnScriptError(gateway)
except pythoncom.com_error as details:
print("**OnScriptError failed:", details)
print("Exception description:'%s'" % (repr(exceptionInstance.description)))
print("Exception text:'%s'" % (repr(exceptionInstance.linetext)))
result = winerror.S_FALSE
if result == winerror.S_OK:
# If the above returns NOERROR, it is assumed the error has been
# correctly registered and the value SCRIPT_E_REPORTED is returned.
ret = win32com.server.exception.COMException(scode=axscript.SCRIPT_E_REPORTED)
return ret
else:
# The error is taken to be unreported and is propagated up the call stack
# via the IDispatch::Invoke's EXCEPINFO parameter (hr returned is DISP_E_EXCEPTION.
return exceptionInstance | [
"def",
"ProcessAXScriptException",
"(",
"scriptingSite",
",",
"debugManager",
",",
"exceptionInstance",
")",
":",
"# \ttraceback.print_exc()",
"instance",
"=",
"IActiveScriptError",
"(",
")",
"instance",
".",
"_SetExceptionInfo",
"(",
"exceptionInstance",
")",
"gateway",
"=",
"win32com",
".",
"server",
".",
"util",
".",
"wrap",
"(",
"instance",
",",
"axscript",
".",
"IID_IActiveScriptError",
")",
"if",
"debugManager",
":",
"fCallOnError",
"=",
"debugManager",
".",
"HandleRuntimeError",
"(",
")",
"if",
"not",
"fCallOnError",
":",
"return",
"None",
"try",
":",
"result",
"=",
"scriptingSite",
".",
"OnScriptError",
"(",
"gateway",
")",
"except",
"pythoncom",
".",
"com_error",
"as",
"details",
":",
"print",
"(",
"\"**OnScriptError failed:\"",
",",
"details",
")",
"print",
"(",
"\"Exception description:'%s'\"",
"%",
"(",
"repr",
"(",
"exceptionInstance",
".",
"description",
")",
")",
")",
"print",
"(",
"\"Exception text:'%s'\"",
"%",
"(",
"repr",
"(",
"exceptionInstance",
".",
"linetext",
")",
")",
")",
"result",
"=",
"winerror",
".",
"S_FALSE",
"if",
"result",
"==",
"winerror",
".",
"S_OK",
":",
"# If the above returns NOERROR, it is assumed the error has been",
"# correctly registered and the value SCRIPT_E_REPORTED is returned.",
"ret",
"=",
"win32com",
".",
"server",
".",
"exception",
".",
"COMException",
"(",
"scode",
"=",
"axscript",
".",
"SCRIPT_E_REPORTED",
")",
"return",
"ret",
"else",
":",
"# The error is taken to be unreported and is propagated up the call stack",
"# via the IDispatch::Invoke's EXCEPINFO parameter (hr returned is DISP_E_EXCEPTION.",
"return",
"exceptionInstance"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32comext/axscript/client/error.py#L238-L271 | ||
infinidb/infinidb | 6c9f5dfdabc41ad80e81ba9e1a4eb0d7271a5d23 | writeengine/bulk/bulkload.py | python | build_tool | (tool) | Use the tool dictionary to determine if required tool exists
and build if not | Use the tool dictionary to determine if required tool exists
and build if not | [
"Use",
"the",
"tool",
"dictionary",
"to",
"determine",
"if",
"required",
"tool",
"exists",
"and",
"build",
"if",
"not"
] | def build_tool(tool):
"""
Use the tool dictionary to determine if required tool exists
and build if not
"""
if not os.path.exists(tool['path']+tool['tool']):
logger.warn ("Building %s before continuing"%tool['tool'])
curdir=os.getcwd()
os.chdir(tool['path'])
exec_cmd(tool['builder'], tool['args'])
os.chdir(curdir) | [
"def",
"build_tool",
"(",
"tool",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"tool",
"[",
"'path'",
"]",
"+",
"tool",
"[",
"'tool'",
"]",
")",
":",
"logger",
".",
"warn",
"(",
"\"Building %s before continuing\"",
"%",
"tool",
"[",
"'tool'",
"]",
")",
"curdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"tool",
"[",
"'path'",
"]",
")",
"exec_cmd",
"(",
"tool",
"[",
"'builder'",
"]",
",",
"tool",
"[",
"'args'",
"]",
")",
"os",
".",
"chdir",
"(",
"curdir",
")"
] | https://github.com/infinidb/infinidb/blob/6c9f5dfdabc41ad80e81ba9e1a4eb0d7271a5d23/writeengine/bulk/bulkload.py#L168-L179 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/address.py | python | Address.associate | (self, instance_id=None, network_interface_id=None, private_ip_address=None, allow_reassociation=False, dry_run=False) | return self.connection.associate_address(
instance_id=instance_id,
public_ip=self.public_ip,
network_interface_id=network_interface_id,
private_ip_address=private_ip_address,
allow_reassociation=allow_reassociation,
dry_run=dry_run
) | Associate this Elastic IP address with a currently running instance.
:see: :meth:`boto.ec2.connection.EC2Connection.associate_address` | Associate this Elastic IP address with a currently running instance.
:see: :meth:`boto.ec2.connection.EC2Connection.associate_address` | [
"Associate",
"this",
"Elastic",
"IP",
"address",
"with",
"a",
"currently",
"running",
"instance",
".",
":",
"see",
":",
":",
"meth",
":",
"boto",
".",
"ec2",
".",
"connection",
".",
"EC2Connection",
".",
"associate_address"
] | def associate(self, instance_id=None, network_interface_id=None, private_ip_address=None, allow_reassociation=False, dry_run=False):
"""
Associate this Elastic IP address with a currently running instance.
:see: :meth:`boto.ec2.connection.EC2Connection.associate_address`
"""
if self.allocation_id:
return self.connection.associate_address(
instance_id=instance_id,
public_ip=self.public_ip,
allocation_id=self.allocation_id,
network_interface_id=network_interface_id,
private_ip_address=private_ip_address,
allow_reassociation=allow_reassociation,
dry_run=dry_run
)
return self.connection.associate_address(
instance_id=instance_id,
public_ip=self.public_ip,
network_interface_id=network_interface_id,
private_ip_address=private_ip_address,
allow_reassociation=allow_reassociation,
dry_run=dry_run
) | [
"def",
"associate",
"(",
"self",
",",
"instance_id",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"private_ip_address",
"=",
"None",
",",
"allow_reassociation",
"=",
"False",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"self",
".",
"allocation_id",
":",
"return",
"self",
".",
"connection",
".",
"associate_address",
"(",
"instance_id",
"=",
"instance_id",
",",
"public_ip",
"=",
"self",
".",
"public_ip",
",",
"allocation_id",
"=",
"self",
".",
"allocation_id",
",",
"network_interface_id",
"=",
"network_interface_id",
",",
"private_ip_address",
"=",
"private_ip_address",
",",
"allow_reassociation",
"=",
"allow_reassociation",
",",
"dry_run",
"=",
"dry_run",
")",
"return",
"self",
".",
"connection",
".",
"associate_address",
"(",
"instance_id",
"=",
"instance_id",
",",
"public_ip",
"=",
"self",
".",
"public_ip",
",",
"network_interface_id",
"=",
"network_interface_id",
",",
"private_ip_address",
"=",
"private_ip_address",
",",
"allow_reassociation",
"=",
"allow_reassociation",
",",
"dry_run",
"=",
"dry_run",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/address.py#L92-L114 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/training/learning_rate_decay.py | python | piecewise_constant | (x, boundaries, values, name=None) | Piecewise constant from boundaries and interval values.
Example: use a learning rate that's 1.0 for the first 100000 steps, 0.5
for steps 100001 to 110000, and 0.1 for any additional steps.
```python
global_step = tf.Variable(0, trainable=False)
boundaries = [100000, 110000]
values = [1.0, 0.5, 0.1]
learning_rate = tf.train.piecewise_constant(global_step, boundaries, values)
# Later, whenever we perform an optimization step, we increment global_step.
```
Args:
x: A 0-D scalar `Tensor`. Must be one of the following types: `float32`,
`float64`, `uint8`, `int8`, `int16`, `int32`, `int64`.
boundaries: A list of `Tensor`s or `int`s or `float`s with strictly
increasing entries, and with all elements having the same type as `x`.
values: A list of `Tensor`s or float`s or `int`s that specifies the values
for the intervals defined by `boundaries`. It should have one more element
than `boundaries`, and all elements should have the same type.
name: A string. Optional name of the operation. Defaults to
'PiecewiseConstant'.
Returns:
A 0-D Tensor. Its value is `values[0]` when `x <= boundaries[0]`,
`values[1]` when `x > boundaries[0]` and `x <= boundaries[1]`, ...,
and values[-1] when `x > boundaries[-1]`. | Piecewise constant from boundaries and interval values. | [
"Piecewise",
"constant",
"from",
"boundaries",
"and",
"interval",
"values",
"."
] | def piecewise_constant(x, boundaries, values, name=None):
""" Piecewise constant from boundaries and interval values.
Example: use a learning rate that's 1.0 for the first 100000 steps, 0.5
for steps 100001 to 110000, and 0.1 for any additional steps.
```python
global_step = tf.Variable(0, trainable=False)
boundaries = [100000, 110000]
values = [1.0, 0.5, 0.1]
learning_rate = tf.train.piecewise_constant(global_step, boundaries, values)
# Later, whenever we perform an optimization step, we increment global_step.
```
Args:
x: A 0-D scalar `Tensor`. Must be one of the following types: `float32`,
`float64`, `uint8`, `int8`, `int16`, `int32`, `int64`.
boundaries: A list of `Tensor`s or `int`s or `float`s with strictly
increasing entries, and with all elements having the same type as `x`.
values: A list of `Tensor`s or float`s or `int`s that specifies the values
for the intervals defined by `boundaries`. It should have one more element
than `boundaries`, and all elements should have the same type.
name: A string. Optional name of the operation. Defaults to
'PiecewiseConstant'.
Returns:
A 0-D Tensor. Its value is `values[0]` when `x <= boundaries[0]`,
`values[1]` when `x > boundaries[0]` and `x <= boundaries[1]`, ...,
and values[-1] when `x > boundaries[-1]`.
"""
with ops.name_scope(name, 'PiecewiseConstant',
[x, boundaries, values, name]) as name:
x = ops.convert_to_tensor(x)
# Avoid explicit conversion to x's dtype. This could result in faulty
# comparisons, for example if floats are converted to integers.
boundaries = ops.convert_n_to_tensor(boundaries)
if not all(b.dtype == x.dtype for b in boundaries):
raise ValueError('boundaries must have the same dtype as x.')
# TODO(rdipietro): Ensure that boundaries' elements are strictly increasing.
values = ops.convert_n_to_tensor(values)
if not all(v.dtype == values[0].dtype for v in values):
raise ValueError('values must have elements all with the same dtype.')
pred_fn_pairs = {}
pred_fn_pairs[x <= boundaries[0]] = lambda: values[0]
pred_fn_pairs[x > boundaries[-1]] = lambda: values[-1]
for low, high, v in zip(boundaries[:-1], boundaries[1:], values[1:-1]):
# Need to bind v here; can do this with lambda v=v: ...
pred = (x > low) & (x <= high)
pred_fn_pairs[pred] = lambda v=v: v
# The default isn't needed here because our conditions are mutually
# exclusive and exhaustive, but tf.case requires it.
default = lambda: values[0]
return control_flow_ops.case(pred_fn_pairs, default, exclusive=True) | [
"def",
"piecewise_constant",
"(",
"x",
",",
"boundaries",
",",
"values",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'PiecewiseConstant'",
",",
"[",
"x",
",",
"boundaries",
",",
"values",
",",
"name",
"]",
")",
"as",
"name",
":",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
")",
"# Avoid explicit conversion to x's dtype. This could result in faulty",
"# comparisons, for example if floats are converted to integers.",
"boundaries",
"=",
"ops",
".",
"convert_n_to_tensor",
"(",
"boundaries",
")",
"if",
"not",
"all",
"(",
"b",
".",
"dtype",
"==",
"x",
".",
"dtype",
"for",
"b",
"in",
"boundaries",
")",
":",
"raise",
"ValueError",
"(",
"'boundaries must have the same dtype as x.'",
")",
"# TODO(rdipietro): Ensure that boundaries' elements are strictly increasing.",
"values",
"=",
"ops",
".",
"convert_n_to_tensor",
"(",
"values",
")",
"if",
"not",
"all",
"(",
"v",
".",
"dtype",
"==",
"values",
"[",
"0",
"]",
".",
"dtype",
"for",
"v",
"in",
"values",
")",
":",
"raise",
"ValueError",
"(",
"'values must have elements all with the same dtype.'",
")",
"pred_fn_pairs",
"=",
"{",
"}",
"pred_fn_pairs",
"[",
"x",
"<=",
"boundaries",
"[",
"0",
"]",
"]",
"=",
"lambda",
":",
"values",
"[",
"0",
"]",
"pred_fn_pairs",
"[",
"x",
">",
"boundaries",
"[",
"-",
"1",
"]",
"]",
"=",
"lambda",
":",
"values",
"[",
"-",
"1",
"]",
"for",
"low",
",",
"high",
",",
"v",
"in",
"zip",
"(",
"boundaries",
"[",
":",
"-",
"1",
"]",
",",
"boundaries",
"[",
"1",
":",
"]",
",",
"values",
"[",
"1",
":",
"-",
"1",
"]",
")",
":",
"# Need to bind v here; can do this with lambda v=v: ...",
"pred",
"=",
"(",
"x",
">",
"low",
")",
"&",
"(",
"x",
"<=",
"high",
")",
"pred_fn_pairs",
"[",
"pred",
"]",
"=",
"lambda",
"v",
"=",
"v",
":",
"v",
"# The default isn't needed here because our conditions are mutually",
"# exclusive and exhaustive, but tf.case requires it.",
"default",
"=",
"lambda",
":",
"values",
"[",
"0",
"]",
"return",
"control_flow_ops",
".",
"case",
"(",
"pred_fn_pairs",
",",
"default",
",",
"exclusive",
"=",
"True",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/learning_rate_decay.py#L93-L149 | ||
facebook/hhvm | cd8d20db628e93583fffa0194aaca937af9b2692 | hphp/tools/gdb/gdbutils.py | python | deref | (val) | Fully dereference a value, stripping away *, &, and all known smart
pointer wrappers (as well as const/volatile qualifiers). | Fully dereference a value, stripping away *, &, and all known smart
pointer wrappers (as well as const/volatile qualifiers). | [
"Fully",
"dereference",
"a",
"value",
"stripping",
"away",
"*",
"&",
"and",
"all",
"known",
"smart",
"pointer",
"wrappers",
"(",
"as",
"well",
"as",
"const",
"/",
"volatile",
"qualifiers",
")",
"."
] | def deref(val):
"""Fully dereference a value, stripping away *, &, and all known smart
pointer wrappers (as well as const/volatile qualifiers)."""
p = rawptr(val)
if p is None:
return val.cast(rawtype(val.type))
else:
return deref(p.referenced_value()) | [
"def",
"deref",
"(",
"val",
")",
":",
"p",
"=",
"rawptr",
"(",
"val",
")",
"if",
"p",
"is",
"None",
":",
"return",
"val",
".",
"cast",
"(",
"rawtype",
"(",
"val",
".",
"type",
")",
")",
"else",
":",
"return",
"deref",
"(",
"p",
".",
"referenced_value",
"(",
")",
")"
] | https://github.com/facebook/hhvm/blob/cd8d20db628e93583fffa0194aaca937af9b2692/hphp/tools/gdb/gdbutils.py#L347-L356 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/codecs.py | python | IncrementalEncoder.setstate | (self, state) | Set the current state of the encoder. state must have been
returned by getstate(). | Set the current state of the encoder. state must have been
returned by getstate(). | [
"Set",
"the",
"current",
"state",
"of",
"the",
"encoder",
".",
"state",
"must",
"have",
"been",
"returned",
"by",
"getstate",
"()",
"."
] | def setstate(self, state):
"""
Set the current state of the encoder. state must have been
returned by getstate().
""" | [
"def",
"setstate",
"(",
"self",
",",
"state",
")",
":"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/codecs.py#L190-L194 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/categorical.py | python | Categorical.fillna | (self, value=None, method=None, limit=None) | return self._constructor(codes, dtype=self.dtype, fastpath=True) | Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series
If a scalar value is passed it is used to fill all missing values.
Alternatively, a Series or dict can be used to fill in different
values for each index. The value should not be a list. The
value(s) passed should either be in the categories or should be
NaN.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
limit : int, default None
(Not implemented yet for Categorical!)
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill. In other words, if there is
a gap with more than this number of consecutive NaNs, it will only
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled.
Returns
-------
filled : Categorical with NA/NaN filled | Fill NA/NaN values using the specified method. | [
"Fill",
"NA",
"/",
"NaN",
"values",
"using",
"the",
"specified",
"method",
"."
] | def fillna(self, value=None, method=None, limit=None):
"""
Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series
If a scalar value is passed it is used to fill all missing values.
Alternatively, a Series or dict can be used to fill in different
values for each index. The value should not be a list. The
value(s) passed should either be in the categories or should be
NaN.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
limit : int, default None
(Not implemented yet for Categorical!)
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill. In other words, if there is
a gap with more than this number of consecutive NaNs, it will only
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled.
Returns
-------
filled : Categorical with NA/NaN filled
"""
value, method = validate_fillna_kwargs(
value, method, validate_scalar_dict_value=False
)
if value is None:
value = np.nan
if limit is not None:
raise NotImplementedError(
"specifying a limit for fillna has not been implemented yet"
)
codes = self._codes
# pad / bfill
if method is not None:
values = self.to_dense().reshape(-1, len(self))
values = interpolate_2d(values, method, 0, None, value).astype(
self.categories.dtype
)[0]
codes = _get_codes_for_values(values, self.categories)
else:
# If value is a dict or a Series (a dict value has already
# been converted to a Series)
if isinstance(value, ABCSeries):
if not value[~value.isin(self.categories)].isna().all():
raise ValueError("fill value must be in categories")
values_codes = _get_codes_for_values(value, self.categories)
indexer = np.where(codes == -1)
codes[indexer] = values_codes[indexer]
# If value is not a dict or Series it should be a scalar
elif is_hashable(value):
if not isna(value) and value not in self.categories:
raise ValueError("fill value must be in categories")
mask = codes == -1
if mask.any():
codes = codes.copy()
if isna(value):
codes[mask] = -1
else:
codes[mask] = self.categories.get_loc(value)
else:
raise TypeError(
f"'value' parameter must be a scalar, dict "
f"or Series, but you passed a {type(value).__name__}"
)
return self._constructor(codes, dtype=self.dtype, fastpath=True) | [
"def",
"fillna",
"(",
"self",
",",
"value",
"=",
"None",
",",
"method",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"value",
",",
"method",
"=",
"validate_fillna_kwargs",
"(",
"value",
",",
"method",
",",
"validate_scalar_dict_value",
"=",
"False",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"np",
".",
"nan",
"if",
"limit",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"specifying a limit for fillna has not been implemented yet\"",
")",
"codes",
"=",
"self",
".",
"_codes",
"# pad / bfill",
"if",
"method",
"is",
"not",
"None",
":",
"values",
"=",
"self",
".",
"to_dense",
"(",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"len",
"(",
"self",
")",
")",
"values",
"=",
"interpolate_2d",
"(",
"values",
",",
"method",
",",
"0",
",",
"None",
",",
"value",
")",
".",
"astype",
"(",
"self",
".",
"categories",
".",
"dtype",
")",
"[",
"0",
"]",
"codes",
"=",
"_get_codes_for_values",
"(",
"values",
",",
"self",
".",
"categories",
")",
"else",
":",
"# If value is a dict or a Series (a dict value has already",
"# been converted to a Series)",
"if",
"isinstance",
"(",
"value",
",",
"ABCSeries",
")",
":",
"if",
"not",
"value",
"[",
"~",
"value",
".",
"isin",
"(",
"self",
".",
"categories",
")",
"]",
".",
"isna",
"(",
")",
".",
"all",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"fill value must be in categories\"",
")",
"values_codes",
"=",
"_get_codes_for_values",
"(",
"value",
",",
"self",
".",
"categories",
")",
"indexer",
"=",
"np",
".",
"where",
"(",
"codes",
"==",
"-",
"1",
")",
"codes",
"[",
"indexer",
"]",
"=",
"values_codes",
"[",
"indexer",
"]",
"# If value is not a dict or Series it should be a scalar",
"elif",
"is_hashable",
"(",
"value",
")",
":",
"if",
"not",
"isna",
"(",
"value",
")",
"and",
"value",
"not",
"in",
"self",
".",
"categories",
":",
"raise",
"ValueError",
"(",
"\"fill value must be in categories\"",
")",
"mask",
"=",
"codes",
"==",
"-",
"1",
"if",
"mask",
".",
"any",
"(",
")",
":",
"codes",
"=",
"codes",
".",
"copy",
"(",
")",
"if",
"isna",
"(",
"value",
")",
":",
"codes",
"[",
"mask",
"]",
"=",
"-",
"1",
"else",
":",
"codes",
"[",
"mask",
"]",
"=",
"self",
".",
"categories",
".",
"get_loc",
"(",
"value",
")",
"else",
":",
"raise",
"TypeError",
"(",
"f\"'value' parameter must be a scalar, dict \"",
"f\"or Series, but you passed a {type(value).__name__}\"",
")",
"return",
"self",
".",
"_constructor",
"(",
"codes",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"fastpath",
"=",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/categorical.py#L1689-L1771 | |
SIPp/sipp | f44d0cf5dec0013eff8fd7b4da885d455aa82e0e | cpplint.py | python | FindEndOfExpressionInLine | (line, startpos, depth, startchar, endchar) | return -1 | Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
Index just after endchar. | Find the position just after the matching endchar. | [
"Find",
"the",
"position",
"just",
"after",
"the",
"matching",
"endchar",
"."
] | def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
"""Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
Index just after endchar.
"""
for i in xrange(startpos, len(line)):
if line[i] == startchar:
depth += 1
elif line[i] == endchar:
depth -= 1
if depth == 0:
return i + 1
return -1 | [
"def",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"startpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"startpos",
",",
"len",
"(",
"line",
")",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"startchar",
":",
"depth",
"+=",
"1",
"elif",
"line",
"[",
"i",
"]",
"==",
"endchar",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"return",
"i",
"+",
"1",
"return",
"-",
"1"
] | https://github.com/SIPp/sipp/blob/f44d0cf5dec0013eff8fd7b4da885d455aa82e0e/cpplint.py#L1031-L1051 | |
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/generators/MdDocPage.py | python | MdDocPage.accept | (self, visitor) | The operation in Visitor design pattern that takes a visitor as an argument
and calls the visitor's method that corresponds to this element.
@raise Exception: if the given visitor is not a subclass of AbstractVisitor | The operation in Visitor design pattern that takes a visitor as an argument
and calls the visitor's method that corresponds to this element. | [
"The",
"operation",
"in",
"Visitor",
"design",
"pattern",
"that",
"takes",
"a",
"visitor",
"as",
"an",
"argument",
"and",
"calls",
"the",
"visitor",
"s",
"method",
"that",
"corresponds",
"to",
"this",
"element",
"."
] | def accept(self, visitor):
"""
The operation in Visitor design pattern that takes a visitor as an argument
and calls the visitor's method that corresponds to this element.
@raise Exception: if the given visitor is not a subclass of AbstractVisitor
"""
# visitor should be extended from the AbstractVisitor class
if issubclass(visitor.__class__, AbstractVisitor.AbstractVisitor):
visitor.mdPageVisit(self.__obj)
else:
DEBUG.error(
"MdDoc.accept() - the given visitor is not a subclass of AbstractVisitor!"
)
raise Exception(
"MdDoc.accept() - the given visitor is not a subclass of AbstractVisitor!"
) | [
"def",
"accept",
"(",
"self",
",",
"visitor",
")",
":",
"# visitor should be extended from the AbstractVisitor class",
"if",
"issubclass",
"(",
"visitor",
".",
"__class__",
",",
"AbstractVisitor",
".",
"AbstractVisitor",
")",
":",
"visitor",
".",
"mdPageVisit",
"(",
"self",
".",
"__obj",
")",
"else",
":",
"DEBUG",
".",
"error",
"(",
"\"MdDoc.accept() - the given visitor is not a subclass of AbstractVisitor!\"",
")",
"raise",
"Exception",
"(",
"\"MdDoc.accept() - the given visitor is not a subclass of AbstractVisitor!\"",
")"
] | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/MdDocPage.py#L69-L84 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.WordPartRight | (*args, **kwargs) | return _stc.StyledTextCtrl_WordPartRight(*args, **kwargs) | WordPartRight(self)
Move to the change next in capitalisation. | WordPartRight(self) | [
"WordPartRight",
"(",
"self",
")"
] | def WordPartRight(*args, **kwargs):
"""
WordPartRight(self)
Move to the change next in capitalisation.
"""
return _stc.StyledTextCtrl_WordPartRight(*args, **kwargs) | [
"def",
"WordPartRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_WordPartRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L5120-L5126 | |
limbo018/DREAMPlace | 146c3b9fd003d1acd52c96d9fd02e3f0a05154e4 | dreamplace/BasicPlace.py | python | BasicPlace.build_legality_check | (self, params, placedb, data_collections, device) | return legality_check.LegalityCheck(
node_size_x=data_collections.node_size_x,
node_size_y=data_collections.node_size_y,
flat_region_boxes=data_collections.flat_region_boxes,
flat_region_boxes_start=data_collections.flat_region_boxes_start,
node2fence_region_map=data_collections.node2fence_region_map,
xl=placedb.xl,
yl=placedb.yl,
xh=placedb.xh,
yh=placedb.yh,
site_width=placedb.site_width,
row_height=placedb.row_height,
scale_factor=params.scale_factor,
num_terminals=placedb.num_terminals,
num_movable_nodes=placedb.num_movable_nodes) | @brief legality check
@param params parameters
@param placedb placement database
@param data_collections a collection of all data and variables required for constructing the ops
@param device cpu or cuda | [] | def build_legality_check(self, params, placedb, data_collections, device):
"""
@brief legality check
@param params parameters
@param placedb placement database
@param data_collections a collection of all data and variables required for constructing the ops
@param device cpu or cuda
"""
return legality_check.LegalityCheck(
node_size_x=data_collections.node_size_x,
node_size_y=data_collections.node_size_y,
flat_region_boxes=data_collections.flat_region_boxes,
flat_region_boxes_start=data_collections.flat_region_boxes_start,
node2fence_region_map=data_collections.node2fence_region_map,
xl=placedb.xl,
yl=placedb.yl,
xh=placedb.xh,
yh=placedb.yh,
site_width=placedb.site_width,
row_height=placedb.row_height,
scale_factor=params.scale_factor,
num_terminals=placedb.num_terminals,
num_movable_nodes=placedb.num_movable_nodes) | [
"def",
"build_legality_check",
"(",
"self",
",",
"params",
",",
"placedb",
",",
"data_collections",
",",
"device",
")",
":",
"return",
"legality_check",
".",
"LegalityCheck",
"(",
"node_size_x",
"=",
"data_collections",
".",
"node_size_x",
",",
"node_size_y",
"=",
"data_collections",
".",
"node_size_y",
",",
"flat_region_boxes",
"=",
"data_collections",
".",
"flat_region_boxes",
",",
"flat_region_boxes_start",
"=",
"data_collections",
".",
"flat_region_boxes_start",
",",
"node2fence_region_map",
"=",
"data_collections",
".",
"node2fence_region_map",
",",
"xl",
"=",
"placedb",
".",
"xl",
",",
"yl",
"=",
"placedb",
".",
"yl",
",",
"xh",
"=",
"placedb",
".",
"xh",
",",
"yh",
"=",
"placedb",
".",
"yh",
",",
"site_width",
"=",
"placedb",
".",
"site_width",
",",
"row_height",
"=",
"placedb",
".",
"row_height",
",",
"scale_factor",
"=",
"params",
".",
"scale_factor",
",",
"num_terminals",
"=",
"placedb",
".",
"num_terminals",
",",
"num_movable_nodes",
"=",
"placedb",
".",
"num_movable_nodes",
")"
] | https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/BasicPlace.py#L548-L570 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextBuffer.BeginStandardBullet | (*args, **kwargs) | return _richtext.RichTextBuffer_BeginStandardBullet(*args, **kwargs) | BeginStandardBullet(self, String bulletName, int leftIndent, int leftSubIndent,
int bulletStyle=TEXT_ATTR_BULLET_STYLE_STANDARD) -> bool | BeginStandardBullet(self, String bulletName, int leftIndent, int leftSubIndent,
int bulletStyle=TEXT_ATTR_BULLET_STYLE_STANDARD) -> bool | [
"BeginStandardBullet",
"(",
"self",
"String",
"bulletName",
"int",
"leftIndent",
"int",
"leftSubIndent",
"int",
"bulletStyle",
"=",
"TEXT_ATTR_BULLET_STYLE_STANDARD",
")",
"-",
">",
"bool"
] | def BeginStandardBullet(*args, **kwargs):
"""
BeginStandardBullet(self, String bulletName, int leftIndent, int leftSubIndent,
int bulletStyle=TEXT_ATTR_BULLET_STYLE_STANDARD) -> bool
"""
return _richtext.RichTextBuffer_BeginStandardBullet(*args, **kwargs) | [
"def",
"BeginStandardBullet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_BeginStandardBullet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2440-L2445 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags2man.py | python | ProgramInfo.Filter | (self) | Filter parsed data to create derived fields. | Filter parsed data to create derived fields. | [
"Filter",
"parsed",
"data",
"to",
"create",
"derived",
"fields",
"."
] | def Filter(self):
"""Filter parsed data to create derived fields."""
if not self.desc:
self.short_desc = ''
return
for i in range(len(self.desc)): # replace full path with name
if self.desc[i].find(self.executable) >= 0:
self.desc[i] = self.desc[i].replace(self.executable, self.name)
self.short_desc = self.desc[0]
word_list = self.short_desc.split(' ')
all_names = [ self.name, self.short_name, ]
# Since the short_desc is always listed right after the name,
# trim it from the short_desc
while word_list and (word_list[0] in all_names
or word_list[0].lower() in all_names):
del word_list[0]
self.short_desc = '' # signal need to reconstruct
if not self.short_desc and word_list:
self.short_desc = ' '.join(word_list) | [
"def",
"Filter",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"desc",
":",
"self",
".",
"short_desc",
"=",
"''",
"return",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"desc",
")",
")",
":",
"# replace full path with name",
"if",
"self",
".",
"desc",
"[",
"i",
"]",
".",
"find",
"(",
"self",
".",
"executable",
")",
">=",
"0",
":",
"self",
".",
"desc",
"[",
"i",
"]",
"=",
"self",
".",
"desc",
"[",
"i",
"]",
".",
"replace",
"(",
"self",
".",
"executable",
",",
"self",
".",
"name",
")",
"self",
".",
"short_desc",
"=",
"self",
".",
"desc",
"[",
"0",
"]",
"word_list",
"=",
"self",
".",
"short_desc",
".",
"split",
"(",
"' '",
")",
"all_names",
"=",
"[",
"self",
".",
"name",
",",
"self",
".",
"short_name",
",",
"]",
"# Since the short_desc is always listed right after the name,",
"# trim it from the short_desc",
"while",
"word_list",
"and",
"(",
"word_list",
"[",
"0",
"]",
"in",
"all_names",
"or",
"word_list",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"in",
"all_names",
")",
":",
"del",
"word_list",
"[",
"0",
"]",
"self",
".",
"short_desc",
"=",
"''",
"# signal need to reconstruct",
"if",
"not",
"self",
".",
"short_desc",
"and",
"word_list",
":",
"self",
".",
"short_desc",
"=",
"' '",
".",
"join",
"(",
"word_list",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags2man.py#L411-L431 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/init_ops_v2.py | python | TruncatedNormal.__call__ | (self, shape, dtype=dtypes.float32) | return self._random_generator.truncated_normal(shape, self.mean,
self.stddev, dtype) | Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported.
Raises:
ValueError: If the dtype is not floating point | Returns a tensor object initialized as specified by the initializer. | [
"Returns",
"a",
"tensor",
"object",
"initialized",
"as",
"specified",
"by",
"the",
"initializer",
"."
] | def __call__(self, shape, dtype=dtypes.float32):
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only floating point types are
supported.
Raises:
ValueError: If the dtype is not floating point
"""
dtype = _assert_float_dtype(dtype)
return self._random_generator.truncated_normal(shape, self.mean,
self.stddev, dtype) | [
"def",
"__call__",
"(",
"self",
",",
"shape",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
")",
":",
"dtype",
"=",
"_assert_float_dtype",
"(",
"dtype",
")",
"return",
"self",
".",
"_random_generator",
".",
"truncated_normal",
"(",
"shape",
",",
"self",
".",
"mean",
",",
"self",
".",
"stddev",
",",
"dtype",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/init_ops_v2.py#L330-L343 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py | python | FitParameters.value | (self, name) | return self._unique_params[name].value | Return the value of a given parameter | Return the value of a given parameter | [
"Return",
"the",
"value",
"of",
"a",
"given",
"parameter"
] | def value(self, name):
"""Return the value of a given parameter"""
return self._unique_params[name].value | [
"def",
"value",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_unique_params",
"[",
"name",
"]",
".",
"value"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py#L163-L165 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Tools/qt5.py | python | qm2rcc.run | (self) | Create a qrc file including the inputs | Create a qrc file including the inputs | [
"Create",
"a",
"qrc",
"file",
"including",
"the",
"inputs"
] | def run(self):
"""Create a qrc file including the inputs"""
txt = '\n'.join(['<file>%s</file>' % k.path_from(self.outputs[0].parent) for k in self.inputs])
code = '<!DOCTYPE RCC><RCC version="1.0">\n<qresource>\n%s\n</qresource>\n</RCC>' % txt
self.outputs[0].write(code) | [
"def",
"run",
"(",
"self",
")",
":",
"txt",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"'<file>%s</file>'",
"%",
"k",
".",
"path_from",
"(",
"self",
".",
"outputs",
"[",
"0",
"]",
".",
"parent",
")",
"for",
"k",
"in",
"self",
".",
"inputs",
"]",
")",
"code",
"=",
"'<!DOCTYPE RCC><RCC version=\"1.0\">\\n<qresource>\\n%s\\n</qresource>\\n</RCC>'",
"%",
"txt",
"self",
".",
"outputs",
"[",
"0",
"]",
".",
"write",
"(",
"code",
")"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/qt5.py#L472-L476 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiNotebook.Create | (*args, **kwargs) | return _aui.AuiNotebook_Create(*args, **kwargs) | Create(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0) -> bool
Do the 2nd phase and create the GUI control. | Create(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"ID_ANY",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0",
")",
"-",
">",
"bool"
] | def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0) -> bool
Do the 2nd phase and create the GUI control.
"""
return _aui.AuiNotebook_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiNotebook_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L1296-L1303 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py | python | PtyProcess.spawn | (
cls, argv, cwd=None, env=None, echo=True, preexec_fn=None,
dimensions=(24, 80)) | return inst | Start the given command in a child process in a pseudo terminal.
This does all the fork/exec type of stuff for a pty, and returns an
instance of PtyProcess.
If preexec_fn is supplied, it will be called with no arguments in the
child process before exec-ing the specified command.
It may, for instance, set signal handlers to SIG_DFL or SIG_IGN.
Dimensions of the psuedoterminal used for the subprocess can be
specified as a tuple (rows, cols), or the default (24, 80) will be used. | Start the given command in a child process in a pseudo terminal. | [
"Start",
"the",
"given",
"command",
"in",
"a",
"child",
"process",
"in",
"a",
"pseudo",
"terminal",
"."
] | def spawn(
cls, argv, cwd=None, env=None, echo=True, preexec_fn=None,
dimensions=(24, 80)):
'''Start the given command in a child process in a pseudo terminal.
This does all the fork/exec type of stuff for a pty, and returns an
instance of PtyProcess.
If preexec_fn is supplied, it will be called with no arguments in the
child process before exec-ing the specified command.
It may, for instance, set signal handlers to SIG_DFL or SIG_IGN.
Dimensions of the psuedoterminal used for the subprocess can be
specified as a tuple (rows, cols), or the default (24, 80) will be used.
'''
# Note that it is difficult for this method to fail.
# You cannot detect if the child process cannot start.
# So the only way you can tell if the child process started
# or not is to try to read from the file descriptor. If you get
# EOF immediately then it means that the child is already dead.
# That may not necessarily be bad because you may have spawned a child
# that performs some task; creates no stdout output; and then dies.
if not isinstance(argv, (list, tuple)):
raise TypeError("Expected a list or tuple for argv, got %r" % argv)
# Shallow copy of argv so we can modify it
argv = argv[:]
command = argv[0]
command_with_path = which(command)
if command_with_path is None:
raise FileNotFoundError('The command was not found or was not ' +
'executable: %s.' % command)
command = command_with_path
argv[0] = command
# [issue #119] To prevent the case where exec fails and the user is
# stuck interacting with a python child process instead of whatever
# was expected, we implement the solution from
# http://stackoverflow.com/a/3703179 to pass the exception to the
# parent process
# [issue #119] 1. Before forking, open a pipe in the parent process.
exec_err_pipe_read, exec_err_pipe_write = os.pipe()
if use_native_pty_fork:
pid, fd = pty.fork()
else:
# Use internal fork_pty, for Solaris
pid, fd = _fork_pty.fork_pty()
# Some platforms must call setwinsize() and setecho() from the
# child process, and others from the master process. We do both,
# allowing IOError for either.
if pid == CHILD:
# set window size
try:
_setwinsize(STDIN_FILENO, *dimensions)
except IOError as err:
if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
raise
# disable echo if spawn argument echo was unset
if not echo:
try:
_setecho(STDIN_FILENO, False)
except (IOError, termios.error) as err:
if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
raise
# [issue #119] 3. The child closes the reading end and sets the
# close-on-exec flag for the writing end.
os.close(exec_err_pipe_read)
fcntl.fcntl(exec_err_pipe_write, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
# Do not allow child to inherit open file descriptors from parent,
# with the exception of the exec_err_pipe_write of the pipe
# Impose ceiling on max_fd: AIX bugfix for users with unlimited
# nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange()
# occasionally raises out of range error
max_fd = min(1048576, resource.getrlimit(resource.RLIMIT_NOFILE)[0])
os.closerange(3, exec_err_pipe_write)
os.closerange(exec_err_pipe_write+1, max_fd)
if cwd is not None:
os.chdir(cwd)
if preexec_fn is not None:
try:
preexec_fn()
except Exception as e:
ename = type(e).__name__
tosend = '{}:0:{}'.format(ename, str(e))
if PY3:
tosend = tosend.encode('utf-8')
os.write(exec_err_pipe_write, tosend)
os.close(exec_err_pipe_write)
os._exit(1)
try:
if env is None:
os.execv(command, argv)
else:
os.execvpe(command, argv, env)
except OSError as err:
# [issue #119] 5. If exec fails, the child writes the error
# code back to the parent using the pipe, then exits.
tosend = 'OSError:{}:{}'.format(err.errno, str(err))
if PY3:
tosend = tosend.encode('utf-8')
os.write(exec_err_pipe_write, tosend)
os.close(exec_err_pipe_write)
os._exit(os.EX_OSERR)
# Parent
inst = cls(pid, fd)
# Set some informational attributes
inst.argv = argv
if env is not None:
inst.env = env
if cwd is not None:
inst.launch_dir = cwd
# [issue #119] 2. After forking, the parent closes the writing end
# of the pipe and reads from the reading end.
os.close(exec_err_pipe_write)
exec_err_data = os.read(exec_err_pipe_read, 4096)
os.close(exec_err_pipe_read)
# [issue #119] 6. The parent reads eof (a zero-length read) if the
# child successfully performed exec, since close-on-exec made
# successful exec close the writing end of the pipe. Or, if exec
# failed, the parent reads the error code and can proceed
# accordingly. Either way, the parent blocks until the child calls
# exec.
if len(exec_err_data) != 0:
try:
errclass, errno_s, errmsg = exec_err_data.split(b':', 2)
exctype = getattr(builtins, errclass.decode('ascii'), Exception)
exception = exctype(errmsg.decode('utf-8', 'replace'))
if exctype is OSError:
exception.errno = int(errno_s)
except:
raise Exception('Subprocess failed, got bad error data: %r'
% exec_err_data)
else:
raise exception
try:
inst.setwinsize(*dimensions)
except IOError as err:
if err.args[0] not in (errno.EINVAL, errno.ENOTTY, errno.ENXIO):
raise
return inst | [
"def",
"spawn",
"(",
"cls",
",",
"argv",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"echo",
"=",
"True",
",",
"preexec_fn",
"=",
"None",
",",
"dimensions",
"=",
"(",
"24",
",",
"80",
")",
")",
":",
"# Note that it is difficult for this method to fail.",
"# You cannot detect if the child process cannot start.",
"# So the only way you can tell if the child process started",
"# or not is to try to read from the file descriptor. If you get",
"# EOF immediately then it means that the child is already dead.",
"# That may not necessarily be bad because you may have spawned a child",
"# that performs some task; creates no stdout output; and then dies.",
"if",
"not",
"isinstance",
"(",
"argv",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a list or tuple for argv, got %r\"",
"%",
"argv",
")",
"# Shallow copy of argv so we can modify it",
"argv",
"=",
"argv",
"[",
":",
"]",
"command",
"=",
"argv",
"[",
"0",
"]",
"command_with_path",
"=",
"which",
"(",
"command",
")",
"if",
"command_with_path",
"is",
"None",
":",
"raise",
"FileNotFoundError",
"(",
"'The command was not found or was not '",
"+",
"'executable: %s.'",
"%",
"command",
")",
"command",
"=",
"command_with_path",
"argv",
"[",
"0",
"]",
"=",
"command",
"# [issue #119] To prevent the case where exec fails and the user is",
"# stuck interacting with a python child process instead of whatever",
"# was expected, we implement the solution from",
"# http://stackoverflow.com/a/3703179 to pass the exception to the",
"# parent process",
"# [issue #119] 1. Before forking, open a pipe in the parent process.",
"exec_err_pipe_read",
",",
"exec_err_pipe_write",
"=",
"os",
".",
"pipe",
"(",
")",
"if",
"use_native_pty_fork",
":",
"pid",
",",
"fd",
"=",
"pty",
".",
"fork",
"(",
")",
"else",
":",
"# Use internal fork_pty, for Solaris",
"pid",
",",
"fd",
"=",
"_fork_pty",
".",
"fork_pty",
"(",
")",
"# Some platforms must call setwinsize() and setecho() from the",
"# child process, and others from the master process. We do both,",
"# allowing IOError for either.",
"if",
"pid",
"==",
"CHILD",
":",
"# set window size",
"try",
":",
"_setwinsize",
"(",
"STDIN_FILENO",
",",
"*",
"dimensions",
")",
"except",
"IOError",
"as",
"err",
":",
"if",
"err",
".",
"args",
"[",
"0",
"]",
"not",
"in",
"(",
"errno",
".",
"EINVAL",
",",
"errno",
".",
"ENOTTY",
")",
":",
"raise",
"# disable echo if spawn argument echo was unset",
"if",
"not",
"echo",
":",
"try",
":",
"_setecho",
"(",
"STDIN_FILENO",
",",
"False",
")",
"except",
"(",
"IOError",
",",
"termios",
".",
"error",
")",
"as",
"err",
":",
"if",
"err",
".",
"args",
"[",
"0",
"]",
"not",
"in",
"(",
"errno",
".",
"EINVAL",
",",
"errno",
".",
"ENOTTY",
")",
":",
"raise",
"# [issue #119] 3. The child closes the reading end and sets the",
"# close-on-exec flag for the writing end.",
"os",
".",
"close",
"(",
"exec_err_pipe_read",
")",
"fcntl",
".",
"fcntl",
"(",
"exec_err_pipe_write",
",",
"fcntl",
".",
"F_SETFD",
",",
"fcntl",
".",
"FD_CLOEXEC",
")",
"# Do not allow child to inherit open file descriptors from parent,",
"# with the exception of the exec_err_pipe_write of the pipe",
"# Impose ceiling on max_fd: AIX bugfix for users with unlimited",
"# nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange()",
"# occasionally raises out of range error",
"max_fd",
"=",
"min",
"(",
"1048576",
",",
"resource",
".",
"getrlimit",
"(",
"resource",
".",
"RLIMIT_NOFILE",
")",
"[",
"0",
"]",
")",
"os",
".",
"closerange",
"(",
"3",
",",
"exec_err_pipe_write",
")",
"os",
".",
"closerange",
"(",
"exec_err_pipe_write",
"+",
"1",
",",
"max_fd",
")",
"if",
"cwd",
"is",
"not",
"None",
":",
"os",
".",
"chdir",
"(",
"cwd",
")",
"if",
"preexec_fn",
"is",
"not",
"None",
":",
"try",
":",
"preexec_fn",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"ename",
"=",
"type",
"(",
"e",
")",
".",
"__name__",
"tosend",
"=",
"'{}:0:{}'",
".",
"format",
"(",
"ename",
",",
"str",
"(",
"e",
")",
")",
"if",
"PY3",
":",
"tosend",
"=",
"tosend",
".",
"encode",
"(",
"'utf-8'",
")",
"os",
".",
"write",
"(",
"exec_err_pipe_write",
",",
"tosend",
")",
"os",
".",
"close",
"(",
"exec_err_pipe_write",
")",
"os",
".",
"_exit",
"(",
"1",
")",
"try",
":",
"if",
"env",
"is",
"None",
":",
"os",
".",
"execv",
"(",
"command",
",",
"argv",
")",
"else",
":",
"os",
".",
"execvpe",
"(",
"command",
",",
"argv",
",",
"env",
")",
"except",
"OSError",
"as",
"err",
":",
"# [issue #119] 5. If exec fails, the child writes the error",
"# code back to the parent using the pipe, then exits.",
"tosend",
"=",
"'OSError:{}:{}'",
".",
"format",
"(",
"err",
".",
"errno",
",",
"str",
"(",
"err",
")",
")",
"if",
"PY3",
":",
"tosend",
"=",
"tosend",
".",
"encode",
"(",
"'utf-8'",
")",
"os",
".",
"write",
"(",
"exec_err_pipe_write",
",",
"tosend",
")",
"os",
".",
"close",
"(",
"exec_err_pipe_write",
")",
"os",
".",
"_exit",
"(",
"os",
".",
"EX_OSERR",
")",
"# Parent",
"inst",
"=",
"cls",
"(",
"pid",
",",
"fd",
")",
"# Set some informational attributes",
"inst",
".",
"argv",
"=",
"argv",
"if",
"env",
"is",
"not",
"None",
":",
"inst",
".",
"env",
"=",
"env",
"if",
"cwd",
"is",
"not",
"None",
":",
"inst",
".",
"launch_dir",
"=",
"cwd",
"# [issue #119] 2. After forking, the parent closes the writing end",
"# of the pipe and reads from the reading end.",
"os",
".",
"close",
"(",
"exec_err_pipe_write",
")",
"exec_err_data",
"=",
"os",
".",
"read",
"(",
"exec_err_pipe_read",
",",
"4096",
")",
"os",
".",
"close",
"(",
"exec_err_pipe_read",
")",
"# [issue #119] 6. The parent reads eof (a zero-length read) if the",
"# child successfully performed exec, since close-on-exec made",
"# successful exec close the writing end of the pipe. Or, if exec",
"# failed, the parent reads the error code and can proceed",
"# accordingly. Either way, the parent blocks until the child calls",
"# exec.",
"if",
"len",
"(",
"exec_err_data",
")",
"!=",
"0",
":",
"try",
":",
"errclass",
",",
"errno_s",
",",
"errmsg",
"=",
"exec_err_data",
".",
"split",
"(",
"b':'",
",",
"2",
")",
"exctype",
"=",
"getattr",
"(",
"builtins",
",",
"errclass",
".",
"decode",
"(",
"'ascii'",
")",
",",
"Exception",
")",
"exception",
"=",
"exctype",
"(",
"errmsg",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
")",
"if",
"exctype",
"is",
"OSError",
":",
"exception",
".",
"errno",
"=",
"int",
"(",
"errno_s",
")",
"except",
":",
"raise",
"Exception",
"(",
"'Subprocess failed, got bad error data: %r'",
"%",
"exec_err_data",
")",
"else",
":",
"raise",
"exception",
"try",
":",
"inst",
".",
"setwinsize",
"(",
"*",
"dimensions",
")",
"except",
"IOError",
"as",
"err",
":",
"if",
"err",
".",
"args",
"[",
"0",
"]",
"not",
"in",
"(",
"errno",
".",
"EINVAL",
",",
"errno",
".",
"ENOTTY",
",",
"errno",
".",
"ENXIO",
")",
":",
"raise",
"return",
"inst"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L179-L338 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/io/ros.py | python | publisher | (topic,klampt_type,convert_kwargs=None,ros_type=None,**kwargs) | return KlamptROSPublisher((lambda rosobj,converter=converter,kwargs=convert_kwargs:converter(rosobj,**kwargs)),
topic,ros_msg_class,**kwargs) | Convenience function. The publisher can be called in the form
pub.publish(klampt_obj), which will convert a klampt_obj to a ROS message
before publishing to a topic.
Returns:
KlamptROSPublisher | Convenience function. The publisher can be called in the form
pub.publish(klampt_obj), which will convert a klampt_obj to a ROS message
before publishing to a topic. | [
"Convenience",
"function",
".",
"The",
"publisher",
"can",
"be",
"called",
"in",
"the",
"form",
"pub",
".",
"publish",
"(",
"klampt_obj",
")",
"which",
"will",
"convert",
"a",
"klampt_obj",
"to",
"a",
"ROS",
"message",
"before",
"publishing",
"to",
"a",
"topic",
"."
] | def publisher(topic,klampt_type,convert_kwargs=None,ros_type=None,**kwargs):
"""Convenience function. The publisher can be called in the form
pub.publish(klampt_obj), which will convert a klampt_obj to a ROS message
before publishing to a topic.
Returns:
KlamptROSPublisher
"""
if convert_kwargs is None:
convert_kwargs = dict()
if not isinstance(klampt_type,str):
klampt_type = klampt_type.__class__.__name__
if ros_type is None:
ros_type = supportedKlamptTypes[klampt_type]
if ros_type in ['SensorMsg','ShapeMsg']:
raise ValueError("Klamp't object is ambiguous, need to specify a ROS type")
converter = 'to_' + ros_type
assert converter in globals(),"Can't convert from ROS message type "+ros_type
converter = globals()[converter]
ros_msg_class = globals()[ros_type]
return KlamptROSPublisher((lambda rosobj,converter=converter,kwargs=convert_kwargs:converter(rosobj,**kwargs)),
topic,ros_msg_class,**kwargs) | [
"def",
"publisher",
"(",
"topic",
",",
"klampt_type",
",",
"convert_kwargs",
"=",
"None",
",",
"ros_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"convert_kwargs",
"is",
"None",
":",
"convert_kwargs",
"=",
"dict",
"(",
")",
"if",
"not",
"isinstance",
"(",
"klampt_type",
",",
"str",
")",
":",
"klampt_type",
"=",
"klampt_type",
".",
"__class__",
".",
"__name__",
"if",
"ros_type",
"is",
"None",
":",
"ros_type",
"=",
"supportedKlamptTypes",
"[",
"klampt_type",
"]",
"if",
"ros_type",
"in",
"[",
"'SensorMsg'",
",",
"'ShapeMsg'",
"]",
":",
"raise",
"ValueError",
"(",
"\"Klamp't object is ambiguous, need to specify a ROS type\"",
")",
"converter",
"=",
"'to_'",
"+",
"ros_type",
"assert",
"converter",
"in",
"globals",
"(",
")",
",",
"\"Can't convert from ROS message type \"",
"+",
"ros_type",
"converter",
"=",
"globals",
"(",
")",
"[",
"converter",
"]",
"ros_msg_class",
"=",
"globals",
"(",
")",
"[",
"ros_type",
"]",
"return",
"KlamptROSPublisher",
"(",
"(",
"lambda",
"rosobj",
",",
"converter",
"=",
"converter",
",",
"kwargs",
"=",
"convert_kwargs",
":",
"converter",
"(",
"rosobj",
",",
"*",
"*",
"kwargs",
")",
")",
",",
"topic",
",",
"ros_msg_class",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/ros.py#L882-L903 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Variable.trace_variable | (self, mode, callback) | return cbname | Define a trace callback for the variable.
MODE is one of "r", "w", "u" for read, write, undefine.
CALLBACK must be a function which is called when
the variable is read, written or undefined.
Return the name of the callback.
This deprecated method wraps a deprecated Tcl method that will
likely be removed in the future. Use trace_add() instead. | Define a trace callback for the variable. | [
"Define",
"a",
"trace",
"callback",
"for",
"the",
"variable",
"."
] | def trace_variable(self, mode, callback):
"""Define a trace callback for the variable.
MODE is one of "r", "w", "u" for read, write, undefine.
CALLBACK must be a function which is called when
the variable is read, written or undefined.
Return the name of the callback.
This deprecated method wraps a deprecated Tcl method that will
likely be removed in the future. Use trace_add() instead.
"""
# TODO: Add deprecation warning
cbname = self._register(callback)
self._tk.call("trace", "variable", self._name, mode, cbname)
return cbname | [
"def",
"trace_variable",
"(",
"self",
",",
"mode",
",",
"callback",
")",
":",
"# TODO: Add deprecation warning",
"cbname",
"=",
"self",
".",
"_register",
"(",
"callback",
")",
"self",
".",
"_tk",
".",
"call",
"(",
"\"trace\"",
",",
"\"variable\"",
",",
"self",
".",
"_name",
",",
"mode",
",",
"cbname",
")",
"return",
"cbname"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L407-L422 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/dis.py | python | distb | (tb=None, *, file=None) | Disassemble a traceback (default: last traceback). | Disassemble a traceback (default: last traceback). | [
"Disassemble",
"a",
"traceback",
"(",
"default",
":",
"last",
"traceback",
")",
"."
] | def distb(tb=None, *, file=None):
"""Disassemble a traceback (default: last traceback)."""
if tb is None:
try:
tb = sys.last_traceback
except AttributeError:
raise RuntimeError("no last traceback to disassemble") from None
while tb.tb_next: tb = tb.tb_next
disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file) | [
"def",
"distb",
"(",
"tb",
"=",
"None",
",",
"*",
",",
"file",
"=",
"None",
")",
":",
"if",
"tb",
"is",
"None",
":",
"try",
":",
"tb",
"=",
"sys",
".",
"last_traceback",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"\"no last traceback to disassemble\"",
")",
"from",
"None",
"while",
"tb",
".",
"tb_next",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"disassemble",
"(",
"tb",
".",
"tb_frame",
".",
"f_code",
",",
"tb",
".",
"tb_lasti",
",",
"file",
"=",
"file",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/dis.py#L88-L96 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/report.py | python | _ComputeCpuBusyness | (activity, load_start, satisfied_end) | return result | Generates a breakdown of CPU activity between |load_start| and
|satisfied_end|. | Generates a breakdown of CPU activity between |load_start| and
|satisfied_end|. | [
"Generates",
"a",
"breakdown",
"of",
"CPU",
"activity",
"between",
"|load_start|",
"and",
"|satisfied_end|",
"."
] | def _ComputeCpuBusyness(activity, load_start, satisfied_end):
"""Generates a breakdown of CPU activity between |load_start| and
|satisfied_end|."""
duration = float(satisfied_end - load_start)
result = {
'activity_frac': (
activity.MainRendererThreadBusyness(load_start, satisfied_end)
/ duration),
}
activity_breakdown = activity.ComputeActivity(load_start, satisfied_end)
result['parsing_frac'] = (
sum(activity_breakdown['parsing'].values()) / duration)
result['script_frac'] = (
sum(activity_breakdown['script'].values()) / duration)
return result | [
"def",
"_ComputeCpuBusyness",
"(",
"activity",
",",
"load_start",
",",
"satisfied_end",
")",
":",
"duration",
"=",
"float",
"(",
"satisfied_end",
"-",
"load_start",
")",
"result",
"=",
"{",
"'activity_frac'",
":",
"(",
"activity",
".",
"MainRendererThreadBusyness",
"(",
"load_start",
",",
"satisfied_end",
")",
"/",
"duration",
")",
",",
"}",
"activity_breakdown",
"=",
"activity",
".",
"ComputeActivity",
"(",
"load_start",
",",
"satisfied_end",
")",
"result",
"[",
"'parsing_frac'",
"]",
"=",
"(",
"sum",
"(",
"activity_breakdown",
"[",
"'parsing'",
"]",
".",
"values",
"(",
")",
")",
"/",
"duration",
")",
"result",
"[",
"'script_frac'",
"]",
"=",
"(",
"sum",
"(",
"activity_breakdown",
"[",
"'script'",
"]",
".",
"values",
"(",
")",
")",
"/",
"duration",
")",
"return",
"result"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/report.py#L24-L39 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Control_FindAccelIndex | (*args, **kwargs) | return _core_.Control_FindAccelIndex(*args, **kwargs) | Control_FindAccelIndex(String label) -> int
Return the accel index in the string or -1 if none. | Control_FindAccelIndex(String label) -> int | [
"Control_FindAccelIndex",
"(",
"String",
"label",
")",
"-",
">",
"int"
] | def Control_FindAccelIndex(*args, **kwargs):
"""
Control_FindAccelIndex(String label) -> int
Return the accel index in the string or -1 if none.
"""
return _core_.Control_FindAccelIndex(*args, **kwargs) | [
"def",
"Control_FindAccelIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Control_FindAccelIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12801-L12807 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/v7.9.317/tools/sanitizers/sancov_formatter.py | python | process_symbolizer_output | (output, build_dir) | return {k: sorted(file_map[k]) for k in file_map if keep(k)} | Post-process llvm symbolizer output.
Excludes files outside the v8 checkout or given in exclusion list above
from further processing. Drops the character index in each line.
Returns: A mapping of file names to lists of line numbers. The file names
have relative paths to the v8 base directory. The lists of line
numbers don't contain duplicate lines and are sorted. | Post-process llvm symbolizer output. | [
"Post",
"-",
"process",
"llvm",
"symbolizer",
"output",
"."
] | def process_symbolizer_output(output, build_dir):
"""Post-process llvm symbolizer output.
Excludes files outside the v8 checkout or given in exclusion list above
from further processing. Drops the character index in each line.
Returns: A mapping of file names to lists of line numbers. The file names
have relative paths to the v8 base directory. The lists of line
numbers don't contain duplicate lines and are sorted.
"""
# Path prefix added by the llvm symbolizer including trailing slash.
output_path_prefix = os.path.join(build_dir, '..', '..', '')
# Drop path prefix when iterating lines. The path is redundant and takes
# too much space. Drop files outside that path, e.g. generated files in
# the build dir and absolute paths to c++ library headers.
def iter_lines():
for line in output.strip().splitlines():
if line.startswith(output_path_prefix):
yield line[len(output_path_prefix):]
# Map file names to sets of instrumented line numbers.
file_map = {}
for line in iter_lines():
# Drop character number, we only care for line numbers. Each line has the
# form: <file name>:<line number>:<character number>.
file_name, number, _ = line.split(':')
file_map.setdefault(file_name, set([])).add(int(number))
# Remove exclusion patterns from file map. It's cheaper to do it after the
# mapping, as there are few excluded files and we don't want to do this
# check for numerous lines in ordinary files.
def keep(file_name):
for e in EXCLUSIONS:
if file_name.startswith(e):
return False
return True
# Return in serializable form and filter.
return {k: sorted(file_map[k]) for k in file_map if keep(k)} | [
"def",
"process_symbolizer_output",
"(",
"output",
",",
"build_dir",
")",
":",
"# Path prefix added by the llvm symbolizer including trailing slash.",
"output_path_prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
",",
"'..'",
",",
"'..'",
",",
"''",
")",
"# Drop path prefix when iterating lines. The path is redundant and takes",
"# too much space. Drop files outside that path, e.g. generated files in",
"# the build dir and absolute paths to c++ library headers.",
"def",
"iter_lines",
"(",
")",
":",
"for",
"line",
"in",
"output",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"output_path_prefix",
")",
":",
"yield",
"line",
"[",
"len",
"(",
"output_path_prefix",
")",
":",
"]",
"# Map file names to sets of instrumented line numbers.",
"file_map",
"=",
"{",
"}",
"for",
"line",
"in",
"iter_lines",
"(",
")",
":",
"# Drop character number, we only care for line numbers. Each line has the",
"# form: <file name>:<line number>:<character number>.",
"file_name",
",",
"number",
",",
"_",
"=",
"line",
".",
"split",
"(",
"':'",
")",
"file_map",
".",
"setdefault",
"(",
"file_name",
",",
"set",
"(",
"[",
"]",
")",
")",
".",
"add",
"(",
"int",
"(",
"number",
")",
")",
"# Remove exclusion patterns from file map. It's cheaper to do it after the",
"# mapping, as there are few excluded files and we don't want to do this",
"# check for numerous lines in ordinary files.",
"def",
"keep",
"(",
"file_name",
")",
":",
"for",
"e",
"in",
"EXCLUSIONS",
":",
"if",
"file_name",
".",
"startswith",
"(",
"e",
")",
":",
"return",
"False",
"return",
"True",
"# Return in serializable form and filter.",
"return",
"{",
"k",
":",
"sorted",
"(",
"file_map",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"file_map",
"if",
"keep",
"(",
"k",
")",
"}"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/tools/sanitizers/sancov_formatter.py#L116-L155 | |
kismetwireless/kismet | a7c0dc270c960fb1f58bd9cec4601c201885fd4e | capture_sdr_rtladsb/KismetCaptureRtladsb/__init__.py | python | KismetRtladsb.adsb_msg_get_me_subme | (self, data) | return (data[4] >> 3, data[4] & 7) | Extract message 17 metype and mesub type
Returns:
(type,subtype) tuple | Extract message 17 metype and mesub type
Returns:
(type,subtype) tuple | [
"Extract",
"message",
"17",
"metype",
"and",
"mesub",
"type",
"Returns",
":",
"(",
"type",
"subtype",
")",
"tuple"
] | def adsb_msg_get_me_subme(self, data):
"""
Extract message 17 metype and mesub type
Returns:
(type,subtype) tuple
"""
return (data[4] >> 3, data[4] & 7) | [
"def",
"adsb_msg_get_me_subme",
"(",
"self",
",",
"data",
")",
":",
"return",
"(",
"data",
"[",
"4",
"]",
">>",
"3",
",",
"data",
"[",
"4",
"]",
"&",
"7",
")"
] | https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtladsb/KismetCaptureRtladsb/__init__.py#L791-L799 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/optimizer/optimizer.py | python | Optimizer.set_wd_mult | (self, args_wd_mult) | Sets an individual weight decay multiplier for each parameter.
By default, if `param_idx2name` was provided in the
constructor, the weight decay multipler is set as 0 for all
parameters whose name don't end with ``_weight`` or
``_gamma``.
.. note:: The default weight decay multiplier for a `Variable`
can be set with its `wd_mult` argument in the constructor.
Parameters
----------
args_wd_mult : dict of string/int to float
For each of its key-value entries, the weight decay multipler for the
parameter specified in the key will be set as the given value.
You can specify the parameter with either its name or its index.
If you use the name, you should pass `sym` in the constructor,
and the name you specified in the key of `args_lr_mult` should match
the name of the parameter in `sym`. If you use the index, it should
correspond to the index of the parameter used in the `update` method.
Specifying a parameter by its index is only supported for backward
compatibility, and we recommend to use the name instead. | Sets an individual weight decay multiplier for each parameter. | [
"Sets",
"an",
"individual",
"weight",
"decay",
"multiplier",
"for",
"each",
"parameter",
"."
] | def set_wd_mult(self, args_wd_mult):
"""Sets an individual weight decay multiplier for each parameter.
By default, if `param_idx2name` was provided in the
constructor, the weight decay multipler is set as 0 for all
parameters whose name don't end with ``_weight`` or
``_gamma``.
.. note:: The default weight decay multiplier for a `Variable`
can be set with its `wd_mult` argument in the constructor.
Parameters
----------
args_wd_mult : dict of string/int to float
For each of its key-value entries, the weight decay multipler for the
parameter specified in the key will be set as the given value.
You can specify the parameter with either its name or its index.
If you use the name, you should pass `sym` in the constructor,
and the name you specified in the key of `args_lr_mult` should match
the name of the parameter in `sym`. If you use the index, it should
correspond to the index of the parameter used in the `update` method.
Specifying a parameter by its index is only supported for backward
compatibility, and we recommend to use the name instead.
"""
self.wd_mult = {}
for n in self.idx2name.values():
if not (n.endswith('_weight') or n.endswith('_gamma')):
self.wd_mult[n] = 0.0
if self.sym_info:
attr, arg_names = self.sym_info
for name in arg_names:
if name in attr and '__wd_mult__' in attr[name]:
self.wd_mult[name] = float(attr[name]['__wd_mult__'])
self.wd_mult.update(args_wd_mult) | [
"def",
"set_wd_mult",
"(",
"self",
",",
"args_wd_mult",
")",
":",
"self",
".",
"wd_mult",
"=",
"{",
"}",
"for",
"n",
"in",
"self",
".",
"idx2name",
".",
"values",
"(",
")",
":",
"if",
"not",
"(",
"n",
".",
"endswith",
"(",
"'_weight'",
")",
"or",
"n",
".",
"endswith",
"(",
"'_gamma'",
")",
")",
":",
"self",
".",
"wd_mult",
"[",
"n",
"]",
"=",
"0.0",
"if",
"self",
".",
"sym_info",
":",
"attr",
",",
"arg_names",
"=",
"self",
".",
"sym_info",
"for",
"name",
"in",
"arg_names",
":",
"if",
"name",
"in",
"attr",
"and",
"'__wd_mult__'",
"in",
"attr",
"[",
"name",
"]",
":",
"self",
".",
"wd_mult",
"[",
"name",
"]",
"=",
"float",
"(",
"attr",
"[",
"name",
"]",
"[",
"'__wd_mult__'",
"]",
")",
"self",
".",
"wd_mult",
".",
"update",
"(",
"args_wd_mult",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/optimizer/optimizer.py#L347-L382 | ||
apache/incubator-weex | 5c25f0b59f7ac90703c363e7261f60bd06356dbe | weex_core/Source/base/android/jniprebuild/jni_generator.py | python | InlHeaderFileGenerator.GetClassPathDefinitions | (self) | return '\n'.join(ret) | Returns the ClassPath constants. | Returns the ClassPath constants. | [
"Returns",
"the",
"ClassPath",
"constants",
"."
] | def GetClassPathDefinitions(self):
"""Returns the ClassPath constants."""
ret = []
template = Template("""\
const char k${JAVA_CLASS}ClassPath[] = "${JNI_CLASS_PATH}";""")
native_classes = self.GetUniqueClasses(self.natives)
called_by_native_classes = self.GetUniqueClasses(self.called_by_natives)
if self.options.native_exports:
all_classes = called_by_native_classes
else:
all_classes = native_classes
all_classes.update(called_by_native_classes)
for clazz in all_classes:
values = {
'JAVA_CLASS': clazz,
'JNI_CLASS_PATH': JniParams.RemapClassName(all_classes[clazz]),
}
ret += [template.substitute(values)]
ret += ''
class_getter_methods = []
if self.options.native_exports:
template = Template("""\
// Leaking this jclass as we cannot use LazyInstance from some threads.
base::subtle::AtomicWord g_${JAVA_CLASS}_clazz __attribute__((unused)) = 0;
#define ${JAVA_CLASS}_clazz(env) \
base::android::LazyGetClass(env, k${JAVA_CLASS}ClassPath, \
&g_${JAVA_CLASS}_clazz)""")
else:
template = Template("""\
// Leaking this jclass as we cannot use LazyInstance from some threads.
jclass g_${JAVA_CLASS}_clazz = NULL;
#define ${JAVA_CLASS}_clazz(env) g_${JAVA_CLASS}_clazz""")
for clazz in called_by_native_classes:
values = {
'JAVA_CLASS': clazz,
}
ret += [template.substitute(values)]
return '\n'.join(ret) | [
"def",
"GetClassPathDefinitions",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"template",
"=",
"Template",
"(",
"\"\"\"\\\nconst char k${JAVA_CLASS}ClassPath[] = \"${JNI_CLASS_PATH}\";\"\"\"",
")",
"native_classes",
"=",
"self",
".",
"GetUniqueClasses",
"(",
"self",
".",
"natives",
")",
"called_by_native_classes",
"=",
"self",
".",
"GetUniqueClasses",
"(",
"self",
".",
"called_by_natives",
")",
"if",
"self",
".",
"options",
".",
"native_exports",
":",
"all_classes",
"=",
"called_by_native_classes",
"else",
":",
"all_classes",
"=",
"native_classes",
"all_classes",
".",
"update",
"(",
"called_by_native_classes",
")",
"for",
"clazz",
"in",
"all_classes",
":",
"values",
"=",
"{",
"'JAVA_CLASS'",
":",
"clazz",
",",
"'JNI_CLASS_PATH'",
":",
"JniParams",
".",
"RemapClassName",
"(",
"all_classes",
"[",
"clazz",
"]",
")",
",",
"}",
"ret",
"+=",
"[",
"template",
".",
"substitute",
"(",
"values",
")",
"]",
"ret",
"+=",
"''",
"class_getter_methods",
"=",
"[",
"]",
"if",
"self",
".",
"options",
".",
"native_exports",
":",
"template",
"=",
"Template",
"(",
"\"\"\"\\\n// Leaking this jclass as we cannot use LazyInstance from some threads.\nbase::subtle::AtomicWord g_${JAVA_CLASS}_clazz __attribute__((unused)) = 0;\n#define ${JAVA_CLASS}_clazz(env) \\\nbase::android::LazyGetClass(env, k${JAVA_CLASS}ClassPath, \\\n&g_${JAVA_CLASS}_clazz)\"\"\"",
")",
"else",
":",
"template",
"=",
"Template",
"(",
"\"\"\"\\\n// Leaking this jclass as we cannot use LazyInstance from some threads.\njclass g_${JAVA_CLASS}_clazz = NULL;\n#define ${JAVA_CLASS}_clazz(env) g_${JAVA_CLASS}_clazz\"\"\"",
")",
"for",
"clazz",
"in",
"called_by_native_classes",
":",
"values",
"=",
"{",
"'JAVA_CLASS'",
":",
"clazz",
",",
"}",
"ret",
"+=",
"[",
"template",
".",
"substitute",
"(",
"values",
")",
"]",
"return",
"'\\n'",
".",
"join",
"(",
"ret",
")"
] | https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/Source/base/android/jniprebuild/jni_generator.py#L1280-L1321 | |
DaFuCoding/MTCNN_Caffe | 09c30c3ff391bd9cb6b249c1910afaf147767ab3 | python/caffe/io.py | python | Transformer.set_raw_scale | (self, in_, scale) | Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient | Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255. | [
"Set",
"the",
"scale",
"of",
"raw",
"features",
"s",
".",
"t",
".",
"the",
"input",
"blob",
"=",
"input",
"*",
"scale",
".",
"While",
"Python",
"represents",
"images",
"in",
"[",
"0",
"1",
"]",
"certain",
"Caffe",
"models",
"like",
"CaffeNet",
"and",
"AlexNet",
"represent",
"images",
"in",
"[",
"0",
"255",
"]",
"so",
"the",
"raw_scale",
"of",
"these",
"models",
"must",
"be",
"255",
"."
] | def set_raw_scale(self, in_, scale):
"""
Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.raw_scale[in_] = scale | [
"def",
"set_raw_scale",
"(",
"self",
",",
"in_",
",",
"scale",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"self",
".",
"raw_scale",
"[",
"in_",
"]",
"=",
"scale"
] | https://github.com/DaFuCoding/MTCNN_Caffe/blob/09c30c3ff391bd9cb6b249c1910afaf147767ab3/python/caffe/io.py#L221-L234 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftutils/groups.py | python | getGroupNames | () | return get_group_names() | Return a list of group names. DEPRECATED. | Return a list of group names. DEPRECATED. | [
"Return",
"a",
"list",
"of",
"group",
"names",
".",
"DEPRECATED",
"."
] | def getGroupNames():
"""Return a list of group names. DEPRECATED."""
utils.use_instead("get_group_names")
return get_group_names() | [
"def",
"getGroupNames",
"(",
")",
":",
"utils",
".",
"use_instead",
"(",
"\"get_group_names\"",
")",
"return",
"get_group_names",
"(",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftutils/groups.py#L107-L110 | |
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/vm/caffe/misc.py | python | set_root_solver | (val) | Set this node to the root.
Parameters
----------
val : boolean
Whether to become the root.
References
----------
The implementation of `set_root_solver(common.hpp, L165)`_. | Set this node to the root. | [
"Set",
"this",
"node",
"to",
"the",
"root",
"."
] | def set_root_solver(val):
"""Set this node to the root.
Parameters
----------
val : boolean
Whether to become the root.
References
----------
The implementation of `set_root_solver(common.hpp, L165)`_.
"""
global _root_solver
_root_solver = val | [
"def",
"set_root_solver",
"(",
"val",
")",
":",
"global",
"_root_solver",
"_root_solver",
"=",
"val"
] | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/caffe/misc.py#L102-L116 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/etree/ElementTree.py | python | Element.iter | (self, tag=None) | Create tree iterator.
The iterator loops over the element and all subelements in document
order, returning all elements with a matching tag.
If the tree structure is modified during iteration, new or removed
elements may or may not be included. To get a stable set, use the
list() function on the iterator, and loop over the resulting list.
*tag* is what tags to look for (default is to return all elements)
Return an iterator containing all the matching elements. | Create tree iterator. | [
"Create",
"tree",
"iterator",
"."
] | def iter(self, tag=None):
"""Create tree iterator.
The iterator loops over the element and all subelements in document
order, returning all elements with a matching tag.
If the tree structure is modified during iteration, new or removed
elements may or may not be included. To get a stable set, use the
list() function on the iterator, and loop over the resulting list.
*tag* is what tags to look for (default is to return all elements)
Return an iterator containing all the matching elements.
"""
if tag == "*":
tag = None
if tag is None or self.tag == tag:
yield self
for e in self._children:
yield from e.iter(tag) | [
"def",
"iter",
"(",
"self",
",",
"tag",
"=",
"None",
")",
":",
"if",
"tag",
"==",
"\"*\"",
":",
"tag",
"=",
"None",
"if",
"tag",
"is",
"None",
"or",
"self",
".",
"tag",
"==",
"tag",
":",
"yield",
"self",
"for",
"e",
"in",
"self",
".",
"_children",
":",
"yield",
"from",
"e",
".",
"iter",
"(",
"tag",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/etree/ElementTree.py#L391-L411 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/rsa/rsa/pkcs1.py | python | _find_method_hash | (method_hash) | Finds the hash method and the hash itself.
:param method_hash: ASN1 code for the hash method concatenated with the
hash itself.
:return: tuple (method, hash) where ``method`` is the used hash method, and
``hash`` is the hash itself.
:raise VerificationFailed: when the hash method cannot be found | Finds the hash method and the hash itself.
:param method_hash: ASN1 code for the hash method concatenated with the
hash itself.
:return: tuple (method, hash) where ``method`` is the used hash method, and
``hash`` is the hash itself.
:raise VerificationFailed: when the hash method cannot be found | [
"Finds",
"the",
"hash",
"method",
"and",
"the",
"hash",
"itself",
".",
":",
"param",
"method_hash",
":",
"ASN1",
"code",
"for",
"the",
"hash",
"method",
"concatenated",
"with",
"the",
"hash",
"itself",
".",
":",
"return",
":",
"tuple",
"(",
"method",
"hash",
")",
"where",
"method",
"is",
"the",
"used",
"hash",
"method",
"and",
"hash",
"is",
"the",
"hash",
"itself",
".",
":",
"raise",
"VerificationFailed",
":",
"when",
"the",
"hash",
"method",
"cannot",
"be",
"found"
] | def _find_method_hash(method_hash):
'''Finds the hash method and the hash itself.
:param method_hash: ASN1 code for the hash method concatenated with the
hash itself.
:return: tuple (method, hash) where ``method`` is the used hash method, and
``hash`` is the hash itself.
:raise VerificationFailed: when the hash method cannot be found
'''
for (hashname, asn1code) in HASH_ASN1.items():
if not method_hash.startswith(asn1code):
continue
return (hashname, method_hash[len(asn1code):])
raise VerificationError('Verification failed') | [
"def",
"_find_method_hash",
"(",
"method_hash",
")",
":",
"for",
"(",
"hashname",
",",
"asn1code",
")",
"in",
"HASH_ASN1",
".",
"items",
"(",
")",
":",
"if",
"not",
"method_hash",
".",
"startswith",
"(",
"asn1code",
")",
":",
"continue",
"return",
"(",
"hashname",
",",
"method_hash",
"[",
"len",
"(",
"asn1code",
")",
":",
"]",
")",
"raise",
"VerificationError",
"(",
"'Verification failed'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/rsa/rsa/pkcs1.py#L354-L373 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | CondCore/Utilities/python/upload_popcon.py | python | ConditionsUploader.signOut | (self) | Signs out the server. | Signs out the server. | [
"Signs",
"out",
"the",
"server",
"."
] | def signOut(self):
'''Signs out the server.
'''
logging.info('%s: Signing out...', self.hostname)
# self.http.query('logout')
self.token = None | [
"def",
"signOut",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'%s: Signing out...'",
",",
"self",
".",
"hostname",
")",
"# self.http.query('logout')",
"self",
".",
"token",
"=",
"None"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/CondCore/Utilities/python/upload_popcon.py#L302-L308 | ||
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/alara.py | python | irradiation_blocks | (material_lib, element_lib, data_library, cooling,
flux_file, irr_time, output="number_density",
truncation=1E-12, impurity=(5E-6, 1E-3),
dump_file="dump_file") | return s | irradiation_blocks(material_lib, element_lib, data_library, cooling,
flux_file, irr_time, output = "number_density",
truncation=1E-12, impurity = (5E-6, 1E-3),
dump_file = "dump_file")
This function returns a string of the irradation-related input blocks. This
function is meant to be used with files created by the mesh_to_geom
function, in order to append the remaining input blocks to form a complete
ALARA input file. Only the simplest irradiation schedule is supported: a
single pulse of time <irr_time>. The notation in this function is consistent
with the ALARA users' guide, found at:
http://svalinn.github.io/ALARA/usersguide/index.html
Parameters
----------
material_lib : str
Path to material library.
element_lib : str
Path to element library.
data_library : str
The data_library card (see ALARA user's guide).
cooling : str or iterable of str
Cooling times for which output is requested. Given in ALARA form (e.g.
"1 h", "0.5 y"). Note that "shutdown" is always implicitly included.
flux_file : str
Path to the "fluxin" file.
irr_time : str
The duration of the single pulse irradiation. Given in the ALARA form
(e.g. "1 h", "0.5 y").
output : str or iterable of str, optional.
The requested output blocks (see ALARA users' guide).
truncation : float, optional
The chain truncation value (see ALARA users' guide).
impurity : tuple of two floats, optional
The impurity parameters (see ALARA users' guide).
dump_file: str, optional
Path to the dump file.
Returns
-------
s : str
Irradition-related ALARA input blocks. | irradiation_blocks(material_lib, element_lib, data_library, cooling,
flux_file, irr_time, output = "number_density",
truncation=1E-12, impurity = (5E-6, 1E-3),
dump_file = "dump_file") | [
"irradiation_blocks",
"(",
"material_lib",
"element_lib",
"data_library",
"cooling",
"flux_file",
"irr_time",
"output",
"=",
"number_density",
"truncation",
"=",
"1E",
"-",
"12",
"impurity",
"=",
"(",
"5E",
"-",
"6",
"1E",
"-",
"3",
")",
"dump_file",
"=",
"dump_file",
")"
] | def irradiation_blocks(material_lib, element_lib, data_library, cooling,
flux_file, irr_time, output="number_density",
truncation=1E-12, impurity=(5E-6, 1E-3),
dump_file="dump_file"):
"""irradiation_blocks(material_lib, element_lib, data_library, cooling,
flux_file, irr_time, output = "number_density",
truncation=1E-12, impurity = (5E-6, 1E-3),
dump_file = "dump_file")
This function returns a string of the irradation-related input blocks. This
function is meant to be used with files created by the mesh_to_geom
function, in order to append the remaining input blocks to form a complete
ALARA input file. Only the simplest irradiation schedule is supported: a
single pulse of time <irr_time>. The notation in this function is consistent
with the ALARA users' guide, found at:
http://svalinn.github.io/ALARA/usersguide/index.html
Parameters
----------
material_lib : str
Path to material library.
element_lib : str
Path to element library.
data_library : str
The data_library card (see ALARA user's guide).
cooling : str or iterable of str
Cooling times for which output is requested. Given in ALARA form (e.g.
"1 h", "0.5 y"). Note that "shutdown" is always implicitly included.
flux_file : str
Path to the "fluxin" file.
irr_time : str
The duration of the single pulse irradiation. Given in the ALARA form
(e.g. "1 h", "0.5 y").
output : str or iterable of str, optional.
The requested output blocks (see ALARA users' guide).
truncation : float, optional
The chain truncation value (see ALARA users' guide).
impurity : tuple of two floats, optional
The impurity parameters (see ALARA users' guide).
dump_file: str, optional
Path to the dump file.
Returns
-------
s : str
Irradition-related ALARA input blocks.
"""
s = u""
# Material, element, and data_library blocks
s += u"material_lib {0}\n".format(material_lib)
s += u"element_lib {0}\n".format(element_lib)
s += u"data_library {0}\n\n".format(data_library)
# Cooling times
s += u"cooling\n"
if isinstance(cooling, collectionsAbc.Iterable) and not isinstance(cooling, basestring):
for c in cooling:
s += u" {0}\n".format(c)
else:
s += u" {0}\n".format(cooling)
s += u"end\n\n"
# Flux block
s += u"flux flux_1 {0} 1.0 0 default\n".format(flux_file)
# Flux schedule
s += (u"schedule simple_schedule\n"
u" {0} flux_1 pulse_once 0 s\nend\n\n".format(irr_time))
s += u"pulsehistory pulse_once\n 1 0.0 s\nend\n\n"
# Output block
s += u"output zone\n units Ci cm3\n"
if isinstance(output, collectionsAbc.Iterable) and not isinstance(output, basestring):
for out in output:
s += u" {0}\n".format(out)
else:
s += u" {0}\n".format(output)
s += u"end\n\n"
# Other parameters
s += u"truncation {0}\n".format(truncation)
s += u"impurity {0} {1}\n".format(impurity[0], impurity[1])
s += u"dump_file {0}\n".format(dump_file)
return s | [
"def",
"irradiation_blocks",
"(",
"material_lib",
",",
"element_lib",
",",
"data_library",
",",
"cooling",
",",
"flux_file",
",",
"irr_time",
",",
"output",
"=",
"\"number_density\"",
",",
"truncation",
"=",
"1E-12",
",",
"impurity",
"=",
"(",
"5E-6",
",",
"1E-3",
")",
",",
"dump_file",
"=",
"\"dump_file\"",
")",
":",
"s",
"=",
"u\"\"",
"# Material, element, and data_library blocks",
"s",
"+=",
"u\"material_lib {0}\\n\"",
".",
"format",
"(",
"material_lib",
")",
"s",
"+=",
"u\"element_lib {0}\\n\"",
".",
"format",
"(",
"element_lib",
")",
"s",
"+=",
"u\"data_library {0}\\n\\n\"",
".",
"format",
"(",
"data_library",
")",
"# Cooling times",
"s",
"+=",
"u\"cooling\\n\"",
"if",
"isinstance",
"(",
"cooling",
",",
"collectionsAbc",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"cooling",
",",
"basestring",
")",
":",
"for",
"c",
"in",
"cooling",
":",
"s",
"+=",
"u\" {0}\\n\"",
".",
"format",
"(",
"c",
")",
"else",
":",
"s",
"+=",
"u\" {0}\\n\"",
".",
"format",
"(",
"cooling",
")",
"s",
"+=",
"u\"end\\n\\n\"",
"# Flux block",
"s",
"+=",
"u\"flux flux_1 {0} 1.0 0 default\\n\"",
".",
"format",
"(",
"flux_file",
")",
"# Flux schedule",
"s",
"+=",
"(",
"u\"schedule simple_schedule\\n\"",
"u\" {0} flux_1 pulse_once 0 s\\nend\\n\\n\"",
".",
"format",
"(",
"irr_time",
")",
")",
"s",
"+=",
"u\"pulsehistory pulse_once\\n 1 0.0 s\\nend\\n\\n\"",
"# Output block",
"s",
"+=",
"u\"output zone\\n units Ci cm3\\n\"",
"if",
"isinstance",
"(",
"output",
",",
"collectionsAbc",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"output",
",",
"basestring",
")",
":",
"for",
"out",
"in",
"output",
":",
"s",
"+=",
"u\" {0}\\n\"",
".",
"format",
"(",
"out",
")",
"else",
":",
"s",
"+=",
"u\" {0}\\n\"",
".",
"format",
"(",
"output",
")",
"s",
"+=",
"u\"end\\n\\n\"",
"# Other parameters",
"s",
"+=",
"u\"truncation {0}\\n\"",
".",
"format",
"(",
"truncation",
")",
"s",
"+=",
"u\"impurity {0} {1}\\n\"",
".",
"format",
"(",
"impurity",
"[",
"0",
"]",
",",
"impurity",
"[",
"1",
"]",
")",
"s",
"+=",
"u\"dump_file {0}\\n\"",
".",
"format",
"(",
"dump_file",
")",
"return",
"s"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/alara.py#L713-L803 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py | python | synopsis | (filename, cache={}) | return result | Get the one-line summary out of a module file. | Get the one-line summary out of a module file. | [
"Get",
"the",
"one",
"-",
"line",
"summary",
"out",
"of",
"a",
"module",
"file",
"."
] | def synopsis(filename, cache={}):
"""Get the one-line summary out of a module file."""
mtime = os.stat(filename).st_mtime
lastupdate, result = cache.get(filename, (0, None))
if lastupdate < mtime:
info = inspect.getmoduleinfo(filename)
try:
file = open(filename)
except IOError:
# module can't be opened, so skip it
return None
if info and 'b' in info[2]: # binary modules have to be imported
try: module = imp.load_module('__temp__', file, filename, info[1:])
except: return None
result = (module.__doc__ or '').splitlines()[0]
del sys.modules['__temp__']
else: # text modules can be directly examined
result = source_synopsis(file)
file.close()
cache[filename] = (mtime, result)
return result | [
"def",
"synopsis",
"(",
"filename",
",",
"cache",
"=",
"{",
"}",
")",
":",
"mtime",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_mtime",
"lastupdate",
",",
"result",
"=",
"cache",
".",
"get",
"(",
"filename",
",",
"(",
"0",
",",
"None",
")",
")",
"if",
"lastupdate",
"<",
"mtime",
":",
"info",
"=",
"inspect",
".",
"getmoduleinfo",
"(",
"filename",
")",
"try",
":",
"file",
"=",
"open",
"(",
"filename",
")",
"except",
"IOError",
":",
"# module can't be opened, so skip it",
"return",
"None",
"if",
"info",
"and",
"'b'",
"in",
"info",
"[",
"2",
"]",
":",
"# binary modules have to be imported",
"try",
":",
"module",
"=",
"imp",
".",
"load_module",
"(",
"'__temp__'",
",",
"file",
",",
"filename",
",",
"info",
"[",
"1",
":",
"]",
")",
"except",
":",
"return",
"None",
"result",
"=",
"(",
"module",
".",
"__doc__",
"or",
"''",
")",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"del",
"sys",
".",
"modules",
"[",
"'__temp__'",
"]",
"else",
":",
"# text modules can be directly examined",
"result",
"=",
"source_synopsis",
"(",
"file",
")",
"file",
".",
"close",
"(",
")",
"cache",
"[",
"filename",
"]",
"=",
"(",
"mtime",
",",
"result",
")",
"return",
"result"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py#L212-L232 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/Resources/ST1.14/Tools/sentrytribe.py | python | rsa_decrypt | (data) | return p.encrypt(data, 1)[0] | Encrypt data with private key | Encrypt data with private key | [
"Encrypt",
"data",
"with",
"private",
"key"
] | def rsa_decrypt(data):
"""
Encrypt data with private key
"""
p = RSA.construct((private_modulus, private_pub_exponent, private_priv_exponent))
return p.encrypt(data, 1)[0] | [
"def",
"rsa_decrypt",
"(",
"data",
")",
":",
"p",
"=",
"RSA",
".",
"construct",
"(",
"(",
"private_modulus",
",",
"private_pub_exponent",
",",
"private_priv_exponent",
")",
")",
"return",
"p",
".",
"encrypt",
"(",
"data",
",",
"1",
")",
"[",
"0",
"]"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/Resources/ST1.14/Tools/sentrytribe.py#L62-L67 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/terminal/pt_inputhooks/osx.py | python | _utf8 | (s) | return s | ensure utf8 bytes | ensure utf8 bytes | [
"ensure",
"utf8",
"bytes"
] | def _utf8(s):
"""ensure utf8 bytes"""
if not isinstance(s, bytes):
s = s.encode('utf8')
return s | [
"def",
"_utf8",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"'utf8'",
")",
"return",
"s"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/terminal/pt_inputhooks/osx.py#L23-L27 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py | python | DifferentialEvolutionSolver.convergence | (self) | return (np.std(self.population_energies) /
np.abs(np.mean(self.population_energies) + _MACHEPS)) | The standard deviation of the population energies divided by their
mean. | The standard deviation of the population energies divided by their
mean. | [
"The",
"standard",
"deviation",
"of",
"the",
"population",
"energies",
"divided",
"by",
"their",
"mean",
"."
] | def convergence(self):
"""
The standard deviation of the population energies divided by their
mean.
"""
if np.any(np.isinf(self.population_energies)):
return np.inf
return (np.std(self.population_energies) /
np.abs(np.mean(self.population_energies) + _MACHEPS)) | [
"def",
"convergence",
"(",
"self",
")",
":",
"if",
"np",
".",
"any",
"(",
"np",
".",
"isinf",
"(",
"self",
".",
"population_energies",
")",
")",
":",
"return",
"np",
".",
"inf",
"return",
"(",
"np",
".",
"std",
"(",
"self",
".",
"population_energies",
")",
"/",
"np",
".",
"abs",
"(",
"np",
".",
"mean",
"(",
"self",
".",
"population_energies",
")",
"+",
"_MACHEPS",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py#L631-L639 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/distutils/exec_command.py | python | find_executable | (exe, path=None, _cache={}) | return None | Return full path of a executable or None.
Symbolic links are not followed. | Return full path of a executable or None. | [
"Return",
"full",
"path",
"of",
"a",
"executable",
"or",
"None",
"."
] | def find_executable(exe, path=None, _cache={}):
"""Return full path of a executable or None.
Symbolic links are not followed.
"""
key = exe, path
try:
return _cache[key]
except KeyError:
pass
log.debug('find_executable(%r)' % exe)
orig_exe = exe
if path is None:
path = os.environ.get('PATH', os.defpath)
if os.name=='posix':
realpath = os.path.realpath
else:
realpath = lambda a:a
if exe.startswith('"'):
exe = exe[1:-1]
suffixes = ['']
if os.name in ['nt', 'dos', 'os2']:
fn, ext = os.path.splitext(exe)
extra_suffixes = ['.exe', '.com', '.bat']
if ext.lower() not in extra_suffixes:
suffixes = extra_suffixes
if os.path.isabs(exe):
paths = ['']
else:
paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]
for path in paths:
fn = os.path.join(path, exe)
for s in suffixes:
f_ext = fn+s
if not os.path.islink(f_ext):
f_ext = realpath(f_ext)
if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):
log.info('Found executable %s' % f_ext)
_cache[key] = f_ext
return f_ext
log.warn('Could not locate executable %s' % orig_exe)
return None | [
"def",
"find_executable",
"(",
"exe",
",",
"path",
"=",
"None",
",",
"_cache",
"=",
"{",
"}",
")",
":",
"key",
"=",
"exe",
",",
"path",
"try",
":",
"return",
"_cache",
"[",
"key",
"]",
"except",
"KeyError",
":",
"pass",
"log",
".",
"debug",
"(",
"'find_executable(%r)'",
"%",
"exe",
")",
"orig_exe",
"=",
"exe",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"os",
".",
"defpath",
")",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"realpath",
"=",
"os",
".",
"path",
".",
"realpath",
"else",
":",
"realpath",
"=",
"lambda",
"a",
":",
"a",
"if",
"exe",
".",
"startswith",
"(",
"'\"'",
")",
":",
"exe",
"=",
"exe",
"[",
"1",
":",
"-",
"1",
"]",
"suffixes",
"=",
"[",
"''",
"]",
"if",
"os",
".",
"name",
"in",
"[",
"'nt'",
",",
"'dos'",
",",
"'os2'",
"]",
":",
"fn",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"exe",
")",
"extra_suffixes",
"=",
"[",
"'.exe'",
",",
"'.com'",
",",
"'.bat'",
"]",
"if",
"ext",
".",
"lower",
"(",
")",
"not",
"in",
"extra_suffixes",
":",
"suffixes",
"=",
"extra_suffixes",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"exe",
")",
":",
"paths",
"=",
"[",
"''",
"]",
"else",
":",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"p",
")",
"for",
"p",
"in",
"path",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"]",
"for",
"path",
"in",
"paths",
":",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"exe",
")",
"for",
"s",
"in",
"suffixes",
":",
"f_ext",
"=",
"fn",
"+",
"s",
"if",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"f_ext",
")",
":",
"f_ext",
"=",
"realpath",
"(",
"f_ext",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f_ext",
")",
"and",
"os",
".",
"access",
"(",
"f_ext",
",",
"os",
".",
"X_OK",
")",
":",
"log",
".",
"info",
"(",
"'Found executable %s'",
"%",
"f_ext",
")",
"_cache",
"[",
"key",
"]",
"=",
"f_ext",
"return",
"f_ext",
"log",
".",
"warn",
"(",
"'Could not locate executable %s'",
"%",
"orig_exe",
")",
"return",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/exec_command.py#L121-L168 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TFile.DelWc | (*args) | return _snap.TFile_DelWc(*args) | DelWc(TStr WcStr, bool const & RecurseDirP=False)
Parameters:
WcStr: TStr const &
RecurseDirP: bool const &
DelWc(TStr WcStr)
Parameters:
WcStr: TStr const & | DelWc(TStr WcStr, bool const & RecurseDirP=False) | [
"DelWc",
"(",
"TStr",
"WcStr",
"bool",
"const",
"&",
"RecurseDirP",
"=",
"False",
")"
] | def DelWc(*args):
"""
DelWc(TStr WcStr, bool const & RecurseDirP=False)
Parameters:
WcStr: TStr const &
RecurseDirP: bool const &
DelWc(TStr WcStr)
Parameters:
WcStr: TStr const &
"""
return _snap.TFile_DelWc(*args) | [
"def",
"DelWc",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TFile_DelWc",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L3293-L3307 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/postgis/connector.py | python | PostGisDBConnector.renameTable | (self, table, new_table) | Renames a table in database | Renames a table in database | [
"Renames",
"a",
"table",
"in",
"database"
] | def renameTable(self, table, new_table):
"""Renames a table in database """
schema, tablename = self.getSchemaTableName(table)
if new_table == tablename:
return
sql = u"ALTER TABLE %s RENAME TO %s" % (self.quoteId(table), self.quoteId(new_table))
self._executeSql(sql)
# update geometry_columns if PostGIS is enabled
if self.has_geometry_columns and not self.is_geometry_columns_view:
schema_where = u" AND f_table_schema=%s " % self.quoteString(schema) if schema is not None else ""
sql = u"UPDATE geometry_columns SET f_table_name=%s WHERE f_table_name=%s %s" % (
self.quoteString(new_table), self.quoteString(tablename), schema_where)
self._executeSql(sql) | [
"def",
"renameTable",
"(",
"self",
",",
"table",
",",
"new_table",
")",
":",
"schema",
",",
"tablename",
"=",
"self",
".",
"getSchemaTableName",
"(",
"table",
")",
"if",
"new_table",
"==",
"tablename",
":",
"return",
"sql",
"=",
"u\"ALTER TABLE %s RENAME TO %s\"",
"%",
"(",
"self",
".",
"quoteId",
"(",
"table",
")",
",",
"self",
".",
"quoteId",
"(",
"new_table",
")",
")",
"self",
".",
"_executeSql",
"(",
"sql",
")",
"# update geometry_columns if PostGIS is enabled",
"if",
"self",
".",
"has_geometry_columns",
"and",
"not",
"self",
".",
"is_geometry_columns_view",
":",
"schema_where",
"=",
"u\" AND f_table_schema=%s \"",
"%",
"self",
".",
"quoteString",
"(",
"schema",
")",
"if",
"schema",
"is",
"not",
"None",
"else",
"\"\"",
"sql",
"=",
"u\"UPDATE geometry_columns SET f_table_name=%s WHERE f_table_name=%s %s\"",
"%",
"(",
"self",
".",
"quoteString",
"(",
"new_table",
")",
",",
"self",
".",
"quoteString",
"(",
"tablename",
")",
",",
"schema_where",
")",
"self",
".",
"_executeSql",
"(",
"sql",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/postgis/connector.py#L920-L934 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | Simulator.getTime | (self) | return _robotsim.Simulator_getTime(self) | getTime(Simulator self) -> double
Returns the simulation time. | getTime(Simulator self) -> double | [
"getTime",
"(",
"Simulator",
"self",
")",
"-",
">",
"double"
] | def getTime(self):
"""
getTime(Simulator self) -> double
Returns the simulation time.
"""
return _robotsim.Simulator_getTime(self) | [
"def",
"getTime",
"(",
"self",
")",
":",
"return",
"_robotsim",
".",
"Simulator_getTime",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L8277-L8286 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | TreeCtrl.GetItemBackgroundColour | (*args, **kwargs) | return _controls_.TreeCtrl_GetItemBackgroundColour(*args, **kwargs) | GetItemBackgroundColour(self, TreeItemId item) -> Colour | GetItemBackgroundColour(self, TreeItemId item) -> Colour | [
"GetItemBackgroundColour",
"(",
"self",
"TreeItemId",
"item",
")",
"-",
">",
"Colour"
] | def GetItemBackgroundColour(*args, **kwargs):
"""GetItemBackgroundColour(self, TreeItemId item) -> Colour"""
return _controls_.TreeCtrl_GetItemBackgroundColour(*args, **kwargs) | [
"def",
"GetItemBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_GetItemBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5281-L5283 | |
takemaru/graphillion | 51879f92bb96b53ef8f914ef37a05252ce383617 | graphillion/graphset.py | python | GraphSet.__gt__ | (self, other) | return self._ss > other._ss | Test if `self` is a true superset of `other`.
This method returns False when `self` == `other`, unlike
issuperset.
Examples:
>>> gs > gs
False
Returns:
True or False.
See Also:
issubset(), issuperset(), isdisjoint() | Test if `self` is a true superset of `other`. | [
"Test",
"if",
"self",
"is",
"a",
"true",
"superset",
"of",
"other",
"."
] | def __gt__(self, other):
"""Test if `self` is a true superset of `other`.
This method returns False when `self` == `other`, unlike
issuperset.
Examples:
>>> gs > gs
False
Returns:
True or False.
See Also:
issubset(), issuperset(), isdisjoint()
"""
return self._ss > other._ss | [
"def",
"__gt__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"_ss",
">",
"other",
".",
"_ss"
] | https://github.com/takemaru/graphillion/blob/51879f92bb96b53ef8f914ef37a05252ce383617/graphillion/graphset.py#L546-L562 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/cli/curses_ui.py | python | CursesUI._screen_new_output_pad | (self, rows, cols) | return curses.newpad(rows, cols) | Generate a new pad on the screen.
Args:
rows: (int) Number of rows the pad will have: not limited to screen size.
cols: (int) Number of columns the pad will have: not limited to screen
size.
Returns:
A curses textpad object. | Generate a new pad on the screen. | [
"Generate",
"a",
"new",
"pad",
"on",
"the",
"screen",
"."
] | def _screen_new_output_pad(self, rows, cols):
"""Generate a new pad on the screen.
Args:
rows: (int) Number of rows the pad will have: not limited to screen size.
cols: (int) Number of columns the pad will have: not limited to screen
size.
Returns:
A curses textpad object.
"""
return curses.newpad(rows, cols) | [
"def",
"_screen_new_output_pad",
"(",
"self",
",",
"rows",
",",
"cols",
")",
":",
"return",
"curses",
".",
"newpad",
"(",
"rows",
",",
"cols",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/cli/curses_ui.py#L991-L1003 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/ao/quantization/observer.py | python | HistogramObserver._compute_quantization_error | (self, next_start_bin: int, next_end_bin: int) | return norm.sum().item() | r"""
Compute the quantization error if we use start_bin to end_bin as the
min and max to do the quantization. | r"""
Compute the quantization error if we use start_bin to end_bin as the
min and max to do the quantization. | [
"r",
"Compute",
"the",
"quantization",
"error",
"if",
"we",
"use",
"start_bin",
"to",
"end_bin",
"as",
"the",
"min",
"and",
"max",
"to",
"do",
"the",
"quantization",
"."
] | def _compute_quantization_error(self, next_start_bin: int, next_end_bin: int):
r"""
Compute the quantization error if we use start_bin to end_bin as the
min and max to do the quantization.
"""
bin_width = (self.max_val.item() - self.min_val.item()) / self.bins
dst_bin_width = bin_width * (next_end_bin - next_start_bin + 1) / self.dst_nbins
if dst_bin_width == 0.0:
return 0.0
src_bin = torch.arange(self.bins, device=self.histogram.device)
# distances from the beginning of first dst_bin to the beginning and
# end of src_bin
src_bin_begin = (src_bin - next_start_bin) * bin_width
src_bin_end = src_bin_begin + bin_width
# which dst_bins the beginning and end of src_bin belong to?
dst_bin_of_begin = torch.clamp(
torch.div(src_bin_begin, dst_bin_width, rounding_mode='floor'), 0, self.dst_nbins - 1
)
dst_bin_of_begin_center = (dst_bin_of_begin + 0.5) * dst_bin_width
dst_bin_of_end = torch.clamp(
torch.div(src_bin_end, dst_bin_width, rounding_mode='floor'), 0, self.dst_nbins - 1
)
dst_bin_of_end_center = (dst_bin_of_end + 0.5) * dst_bin_width
density = self.histogram / bin_width
norm = torch.zeros(self.bins, device=self.histogram.device)
delta_begin = src_bin_begin - dst_bin_of_begin_center
delta_end = dst_bin_width / 2
norm += self._get_norm(delta_begin,
torch.ones(self.bins, device=self.histogram.device) * delta_end,
density)
norm += (dst_bin_of_end - dst_bin_of_begin - 1) * self._get_norm(
torch.tensor(-dst_bin_width / 2), torch.tensor(dst_bin_width / 2), density
)
dst_bin_of_end_center = dst_bin_of_end * dst_bin_width + dst_bin_width / 2
delta_begin = -dst_bin_width / 2
delta_end = src_bin_end - dst_bin_of_end_center
norm += self._get_norm(torch.tensor(delta_begin), delta_end, density)
return norm.sum().item() | [
"def",
"_compute_quantization_error",
"(",
"self",
",",
"next_start_bin",
":",
"int",
",",
"next_end_bin",
":",
"int",
")",
":",
"bin_width",
"=",
"(",
"self",
".",
"max_val",
".",
"item",
"(",
")",
"-",
"self",
".",
"min_val",
".",
"item",
"(",
")",
")",
"/",
"self",
".",
"bins",
"dst_bin_width",
"=",
"bin_width",
"*",
"(",
"next_end_bin",
"-",
"next_start_bin",
"+",
"1",
")",
"/",
"self",
".",
"dst_nbins",
"if",
"dst_bin_width",
"==",
"0.0",
":",
"return",
"0.0",
"src_bin",
"=",
"torch",
".",
"arange",
"(",
"self",
".",
"bins",
",",
"device",
"=",
"self",
".",
"histogram",
".",
"device",
")",
"# distances from the beginning of first dst_bin to the beginning and",
"# end of src_bin",
"src_bin_begin",
"=",
"(",
"src_bin",
"-",
"next_start_bin",
")",
"*",
"bin_width",
"src_bin_end",
"=",
"src_bin_begin",
"+",
"bin_width",
"# which dst_bins the beginning and end of src_bin belong to?",
"dst_bin_of_begin",
"=",
"torch",
".",
"clamp",
"(",
"torch",
".",
"div",
"(",
"src_bin_begin",
",",
"dst_bin_width",
",",
"rounding_mode",
"=",
"'floor'",
")",
",",
"0",
",",
"self",
".",
"dst_nbins",
"-",
"1",
")",
"dst_bin_of_begin_center",
"=",
"(",
"dst_bin_of_begin",
"+",
"0.5",
")",
"*",
"dst_bin_width",
"dst_bin_of_end",
"=",
"torch",
".",
"clamp",
"(",
"torch",
".",
"div",
"(",
"src_bin_end",
",",
"dst_bin_width",
",",
"rounding_mode",
"=",
"'floor'",
")",
",",
"0",
",",
"self",
".",
"dst_nbins",
"-",
"1",
")",
"dst_bin_of_end_center",
"=",
"(",
"dst_bin_of_end",
"+",
"0.5",
")",
"*",
"dst_bin_width",
"density",
"=",
"self",
".",
"histogram",
"/",
"bin_width",
"norm",
"=",
"torch",
".",
"zeros",
"(",
"self",
".",
"bins",
",",
"device",
"=",
"self",
".",
"histogram",
".",
"device",
")",
"delta_begin",
"=",
"src_bin_begin",
"-",
"dst_bin_of_begin_center",
"delta_end",
"=",
"dst_bin_width",
"/",
"2",
"norm",
"+=",
"self",
".",
"_get_norm",
"(",
"delta_begin",
",",
"torch",
".",
"ones",
"(",
"self",
".",
"bins",
",",
"device",
"=",
"self",
".",
"histogram",
".",
"device",
")",
"*",
"delta_end",
",",
"density",
")",
"norm",
"+=",
"(",
"dst_bin_of_end",
"-",
"dst_bin_of_begin",
"-",
"1",
")",
"*",
"self",
".",
"_get_norm",
"(",
"torch",
".",
"tensor",
"(",
"-",
"dst_bin_width",
"/",
"2",
")",
",",
"torch",
".",
"tensor",
"(",
"dst_bin_width",
"/",
"2",
")",
",",
"density",
")",
"dst_bin_of_end_center",
"=",
"dst_bin_of_end",
"*",
"dst_bin_width",
"+",
"dst_bin_width",
"/",
"2",
"delta_begin",
"=",
"-",
"dst_bin_width",
"/",
"2",
"delta_end",
"=",
"src_bin_end",
"-",
"dst_bin_of_end_center",
"norm",
"+=",
"self",
".",
"_get_norm",
"(",
"torch",
".",
"tensor",
"(",
"delta_begin",
")",
",",
"delta_end",
",",
"density",
")",
"return",
"norm",
".",
"sum",
"(",
")",
".",
"item",
"(",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/observer.py#L884-L932 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_misc/docgen.py | python | Document._write_arrayelement | (self, elem, sep, format_default=None, is_math=False) | Write to document the formated characters dependend on type | Write to document the formated characters dependend on type | [
"Write",
"to",
"document",
"the",
"formated",
"characters",
"dependend",
"on",
"type"
] | def _write_arrayelement(self, elem, sep, format_default=None, is_math=False):
"""
Write to document the formated characters dependend on type
"""
# print '_write_arrayelement'
# print ' elem,format_default',elem,type(elem),type(elem)==np.float64,format_default
if is_math:
mathsep = ""
else:
mathsep = "$" # create in-line mat env
if is_arraytype(elem):
self.f.write(mathsep)
if is_arraytype(elem[0]):
self.matrix(elem, is_math=False) # write entire matrix
else:
self.rowvec(elem, is_math=False) # write entire matrix
self.f.write(mathsep+sep)
elif format_default != None: # scalar with default format
self.f.write((format_default+sep) % (elem))
elif is_integer(elem):
format = "%d"
self.f.write((mathsep+format+mathsep+sep) % (elem))
elif is_float(elem):
format = "%.2f"
self.f.write((mathsep+format+mathsep+sep) % (elem))
else: # probably a string, just as is
self.f.write(elem+sep) | [
"def",
"_write_arrayelement",
"(",
"self",
",",
"elem",
",",
"sep",
",",
"format_default",
"=",
"None",
",",
"is_math",
"=",
"False",
")",
":",
"# print '_write_arrayelement'",
"# print ' elem,format_default',elem,type(elem),type(elem)==np.float64,format_default",
"if",
"is_math",
":",
"mathsep",
"=",
"\"\"",
"else",
":",
"mathsep",
"=",
"\"$\"",
"# create in-line mat env",
"if",
"is_arraytype",
"(",
"elem",
")",
":",
"self",
".",
"f",
".",
"write",
"(",
"mathsep",
")",
"if",
"is_arraytype",
"(",
"elem",
"[",
"0",
"]",
")",
":",
"self",
".",
"matrix",
"(",
"elem",
",",
"is_math",
"=",
"False",
")",
"# write entire matrix",
"else",
":",
"self",
".",
"rowvec",
"(",
"elem",
",",
"is_math",
"=",
"False",
")",
"# write entire matrix",
"self",
".",
"f",
".",
"write",
"(",
"mathsep",
"+",
"sep",
")",
"elif",
"format_default",
"!=",
"None",
":",
"# scalar with default format",
"self",
".",
"f",
".",
"write",
"(",
"(",
"format_default",
"+",
"sep",
")",
"%",
"(",
"elem",
")",
")",
"elif",
"is_integer",
"(",
"elem",
")",
":",
"format",
"=",
"\"%d\"",
"self",
".",
"f",
".",
"write",
"(",
"(",
"mathsep",
"+",
"format",
"+",
"mathsep",
"+",
"sep",
")",
"%",
"(",
"elem",
")",
")",
"elif",
"is_float",
"(",
"elem",
")",
":",
"format",
"=",
"\"%.2f\"",
"self",
".",
"f",
".",
"write",
"(",
"(",
"mathsep",
"+",
"format",
"+",
"mathsep",
"+",
"sep",
")",
"%",
"(",
"elem",
")",
")",
"else",
":",
"# probably a string, just as is",
"self",
".",
"f",
".",
"write",
"(",
"elem",
"+",
"sep",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_misc/docgen.py#L362-L393 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/sandwich_prefetch.py | python | PrefetchBenchmarkBuilder.PopulateLoadBenchmark | (self, subresource_discoverer,
transformer_list_name, transformer_list) | Populate benchmarking tasks from its setup tasks.
Args:
subresource_discoverer: Name of a subresources discoverer.
transformer_list_name: A string describing the transformers, will be used
in Task names (prefer names without spaces and special characters).
transformer_list: An ordered list of function that takes an instance of
SandwichRunner as parameter, would be applied immediately before
SandwichRunner.Run() in the given order.
Here is the full dependency of the added tree for the returned task:
<transformer_list_name>/<subresource_discoverer>-metrics.csv
depends on: <transformer_list_name>/<subresource_discoverer>-run/
depends on: common/<subresource_discoverer>-cache.zip
depends on: common/<subresource_discoverer>-setup.json
depends on: common/patched-cache-validation.json | Populate benchmarking tasks from its setup tasks. | [
"Populate",
"benchmarking",
"tasks",
"from",
"its",
"setup",
"tasks",
"."
] | def PopulateLoadBenchmark(self, subresource_discoverer,
transformer_list_name, transformer_list):
"""Populate benchmarking tasks from its setup tasks.
Args:
subresource_discoverer: Name of a subresources discoverer.
transformer_list_name: A string describing the transformers, will be used
in Task names (prefer names without spaces and special characters).
transformer_list: An ordered list of function that takes an instance of
SandwichRunner as parameter, would be applied immediately before
SandwichRunner.Run() in the given order.
Here is the full dependency of the added tree for the returned task:
<transformer_list_name>/<subresource_discoverer>-metrics.csv
depends on: <transformer_list_name>/<subresource_discoverer>-run/
depends on: common/<subresource_discoverer>-cache.zip
depends on: common/<subresource_discoverer>-setup.json
depends on: common/patched-cache-validation.json
"""
additional_column_names = [
'url',
'repeat_id',
'subresource_discoverer',
'cache_recording.subresource_count',
'cache_recording.cached_subresource_count_theoretic',
'cache_recording.cached_subresource_count',
'benchmark.subresource_count',
'benchmark.served_from_cache_count_theoretic',
'benchmark.served_from_cache_count',
'benchmark.served_from_network_bytes',
'benchmark.served_from_cache_bytes']
assert subresource_discoverer in SUBRESOURCE_DISCOVERERS
assert 'common' not in SUBRESOURCE_DISCOVERERS
shared_task_prefix = os.path.join('common', subresource_discoverer)
task_prefix = os.path.join(transformer_list_name, subresource_discoverer)
@self.RegisterTask(shared_task_prefix + '-setup.json', merge=True,
dependencies=[self._cache_validation_task])
def SetupBenchmark():
whitelisted_urls = _ExtractDiscoverableUrls(
original_headers_path=self._original_headers_path,
loading_trace_path=self._trace_from_grabbing_reference_cache,
subresource_discoverer=subresource_discoverer)
common_util.EnsureParentDirectoryExists(SetupBenchmark.path)
with open(SetupBenchmark.path, 'w') as output:
json.dump({
'cache_whitelist': [url for url in whitelisted_urls],
'subresource_discoverer': subresource_discoverer,
}, output)
@self.RegisterTask(shared_task_prefix + '-cache.zip', merge=True,
dependencies=[SetupBenchmark])
def BuildBenchmarkCacheArchive():
benchmark_setup = json.load(open(SetupBenchmark.path))
chrome_cache.ApplyUrlWhitelistToCacheArchive(
cache_archive_path=self._cache_path,
whitelisted_urls=benchmark_setup['cache_whitelist'],
output_cache_archive_path=BuildBenchmarkCacheArchive.path)
@self.RegisterTask(task_prefix + '-run/',
dependencies=[BuildBenchmarkCacheArchive])
def RunBenchmark():
runner = self._common_builder.CreateSandwichRunner()
for transformer in transformer_list:
transformer(runner)
runner.wpr_archive_path = self._common_builder.original_wpr_task.path
runner.wpr_out_log_path = os.path.join(
RunBenchmark.path, sandwich_runner.WPR_LOG_FILENAME)
runner.cache_archive_path = BuildBenchmarkCacheArchive.path
runner.cache_operation = sandwich_runner.CacheOperation.PUSH
runner.output_dir = RunBenchmark.path
runner.Run()
@self.RegisterTask(task_prefix + '-metrics.csv',
dependencies=[RunBenchmark])
def ProcessRunOutputDir():
benchmark_setup = json.load(open(SetupBenchmark.path))
cache_validation_result = json.load(
open(self._cache_validation_task.path))
run_metrics_list = _ProcessRunOutputDir(
cache_validation_result, benchmark_setup, RunBenchmark.path)
with open(ProcessRunOutputDir.path, 'w') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=(additional_column_names +
sandwich_metrics.COMMON_CSV_COLUMN_NAMES))
writer.writeheader()
for trace_metrics in run_metrics_list:
writer.writerow(trace_metrics)
self._common_builder.default_final_tasks.append(ProcessRunOutputDir) | [
"def",
"PopulateLoadBenchmark",
"(",
"self",
",",
"subresource_discoverer",
",",
"transformer_list_name",
",",
"transformer_list",
")",
":",
"additional_column_names",
"=",
"[",
"'url'",
",",
"'repeat_id'",
",",
"'subresource_discoverer'",
",",
"'cache_recording.subresource_count'",
",",
"'cache_recording.cached_subresource_count_theoretic'",
",",
"'cache_recording.cached_subresource_count'",
",",
"'benchmark.subresource_count'",
",",
"'benchmark.served_from_cache_count_theoretic'",
",",
"'benchmark.served_from_cache_count'",
",",
"'benchmark.served_from_network_bytes'",
",",
"'benchmark.served_from_cache_bytes'",
"]",
"assert",
"subresource_discoverer",
"in",
"SUBRESOURCE_DISCOVERERS",
"assert",
"'common'",
"not",
"in",
"SUBRESOURCE_DISCOVERERS",
"shared_task_prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'common'",
",",
"subresource_discoverer",
")",
"task_prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"transformer_list_name",
",",
"subresource_discoverer",
")",
"@",
"self",
".",
"RegisterTask",
"(",
"shared_task_prefix",
"+",
"'-setup.json'",
",",
"merge",
"=",
"True",
",",
"dependencies",
"=",
"[",
"self",
".",
"_cache_validation_task",
"]",
")",
"def",
"SetupBenchmark",
"(",
")",
":",
"whitelisted_urls",
"=",
"_ExtractDiscoverableUrls",
"(",
"original_headers_path",
"=",
"self",
".",
"_original_headers_path",
",",
"loading_trace_path",
"=",
"self",
".",
"_trace_from_grabbing_reference_cache",
",",
"subresource_discoverer",
"=",
"subresource_discoverer",
")",
"common_util",
".",
"EnsureParentDirectoryExists",
"(",
"SetupBenchmark",
".",
"path",
")",
"with",
"open",
"(",
"SetupBenchmark",
".",
"path",
",",
"'w'",
")",
"as",
"output",
":",
"json",
".",
"dump",
"(",
"{",
"'cache_whitelist'",
":",
"[",
"url",
"for",
"url",
"in",
"whitelisted_urls",
"]",
",",
"'subresource_discoverer'",
":",
"subresource_discoverer",
",",
"}",
",",
"output",
")",
"@",
"self",
".",
"RegisterTask",
"(",
"shared_task_prefix",
"+",
"'-cache.zip'",
",",
"merge",
"=",
"True",
",",
"dependencies",
"=",
"[",
"SetupBenchmark",
"]",
")",
"def",
"BuildBenchmarkCacheArchive",
"(",
")",
":",
"benchmark_setup",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"SetupBenchmark",
".",
"path",
")",
")",
"chrome_cache",
".",
"ApplyUrlWhitelistToCacheArchive",
"(",
"cache_archive_path",
"=",
"self",
".",
"_cache_path",
",",
"whitelisted_urls",
"=",
"benchmark_setup",
"[",
"'cache_whitelist'",
"]",
",",
"output_cache_archive_path",
"=",
"BuildBenchmarkCacheArchive",
".",
"path",
")",
"@",
"self",
".",
"RegisterTask",
"(",
"task_prefix",
"+",
"'-run/'",
",",
"dependencies",
"=",
"[",
"BuildBenchmarkCacheArchive",
"]",
")",
"def",
"RunBenchmark",
"(",
")",
":",
"runner",
"=",
"self",
".",
"_common_builder",
".",
"CreateSandwichRunner",
"(",
")",
"for",
"transformer",
"in",
"transformer_list",
":",
"transformer",
"(",
"runner",
")",
"runner",
".",
"wpr_archive_path",
"=",
"self",
".",
"_common_builder",
".",
"original_wpr_task",
".",
"path",
"runner",
".",
"wpr_out_log_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"RunBenchmark",
".",
"path",
",",
"sandwich_runner",
".",
"WPR_LOG_FILENAME",
")",
"runner",
".",
"cache_archive_path",
"=",
"BuildBenchmarkCacheArchive",
".",
"path",
"runner",
".",
"cache_operation",
"=",
"sandwich_runner",
".",
"CacheOperation",
".",
"PUSH",
"runner",
".",
"output_dir",
"=",
"RunBenchmark",
".",
"path",
"runner",
".",
"Run",
"(",
")",
"@",
"self",
".",
"RegisterTask",
"(",
"task_prefix",
"+",
"'-metrics.csv'",
",",
"dependencies",
"=",
"[",
"RunBenchmark",
"]",
")",
"def",
"ProcessRunOutputDir",
"(",
")",
":",
"benchmark_setup",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"SetupBenchmark",
".",
"path",
")",
")",
"cache_validation_result",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"self",
".",
"_cache_validation_task",
".",
"path",
")",
")",
"run_metrics_list",
"=",
"_ProcessRunOutputDir",
"(",
"cache_validation_result",
",",
"benchmark_setup",
",",
"RunBenchmark",
".",
"path",
")",
"with",
"open",
"(",
"ProcessRunOutputDir",
".",
"path",
",",
"'w'",
")",
"as",
"csv_file",
":",
"writer",
"=",
"csv",
".",
"DictWriter",
"(",
"csv_file",
",",
"fieldnames",
"=",
"(",
"additional_column_names",
"+",
"sandwich_metrics",
".",
"COMMON_CSV_COLUMN_NAMES",
")",
")",
"writer",
".",
"writeheader",
"(",
")",
"for",
"trace_metrics",
"in",
"run_metrics_list",
":",
"writer",
".",
"writerow",
"(",
"trace_metrics",
")",
"self",
".",
"_common_builder",
".",
"default_final_tasks",
".",
"append",
"(",
"ProcessRunOutputDir",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/sandwich_prefetch.py#L587-L678 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/internals/concat.py | python | combine_concat_plans | (plans, concat_axis) | Combine multiple concatenation plans into one.
existing_plan is updated in-place. | Combine multiple concatenation plans into one. | [
"Combine",
"multiple",
"concatenation",
"plans",
"into",
"one",
"."
] | def combine_concat_plans(plans, concat_axis):
"""
Combine multiple concatenation plans into one.
existing_plan is updated in-place.
"""
if len(plans) == 1:
for p in plans[0]:
yield p[0], [p[1]]
elif concat_axis == 0:
offset = 0
for plan in plans:
last_plc = None
for plc, unit in plan:
yield plc.add(offset), [unit]
last_plc = plc
if last_plc is not None:
offset += last_plc.as_slice.stop
else:
num_ended = [0]
def _next_or_none(seq):
retval = next(seq, None)
if retval is None:
num_ended[0] += 1
return retval
plans = list(map(iter, plans))
next_items = list(map(_next_or_none, plans))
while num_ended[0] != len(next_items):
if num_ended[0] > 0:
raise ValueError("Plan shapes are not aligned")
placements, units = zip(*next_items)
lengths = list(map(len, placements))
min_len, max_len = min(lengths), max(lengths)
if min_len == max_len:
yield placements[0], units
next_items[:] = map(_next_or_none, plans)
else:
yielded_placement = None
yielded_units = [None] * len(next_items)
for i, (plc, unit) in enumerate(next_items):
yielded_units[i] = unit
if len(plc) > min_len:
# trim_join_unit updates unit in place, so only
# placement needs to be sliced to skip min_len.
next_items[i] = (plc[min_len:],
trim_join_unit(unit, min_len))
else:
yielded_placement = plc
next_items[i] = _next_or_none(plans[i])
yield yielded_placement, yielded_units | [
"def",
"combine_concat_plans",
"(",
"plans",
",",
"concat_axis",
")",
":",
"if",
"len",
"(",
"plans",
")",
"==",
"1",
":",
"for",
"p",
"in",
"plans",
"[",
"0",
"]",
":",
"yield",
"p",
"[",
"0",
"]",
",",
"[",
"p",
"[",
"1",
"]",
"]",
"elif",
"concat_axis",
"==",
"0",
":",
"offset",
"=",
"0",
"for",
"plan",
"in",
"plans",
":",
"last_plc",
"=",
"None",
"for",
"plc",
",",
"unit",
"in",
"plan",
":",
"yield",
"plc",
".",
"add",
"(",
"offset",
")",
",",
"[",
"unit",
"]",
"last_plc",
"=",
"plc",
"if",
"last_plc",
"is",
"not",
"None",
":",
"offset",
"+=",
"last_plc",
".",
"as_slice",
".",
"stop",
"else",
":",
"num_ended",
"=",
"[",
"0",
"]",
"def",
"_next_or_none",
"(",
"seq",
")",
":",
"retval",
"=",
"next",
"(",
"seq",
",",
"None",
")",
"if",
"retval",
"is",
"None",
":",
"num_ended",
"[",
"0",
"]",
"+=",
"1",
"return",
"retval",
"plans",
"=",
"list",
"(",
"map",
"(",
"iter",
",",
"plans",
")",
")",
"next_items",
"=",
"list",
"(",
"map",
"(",
"_next_or_none",
",",
"plans",
")",
")",
"while",
"num_ended",
"[",
"0",
"]",
"!=",
"len",
"(",
"next_items",
")",
":",
"if",
"num_ended",
"[",
"0",
"]",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"Plan shapes are not aligned\"",
")",
"placements",
",",
"units",
"=",
"zip",
"(",
"*",
"next_items",
")",
"lengths",
"=",
"list",
"(",
"map",
"(",
"len",
",",
"placements",
")",
")",
"min_len",
",",
"max_len",
"=",
"min",
"(",
"lengths",
")",
",",
"max",
"(",
"lengths",
")",
"if",
"min_len",
"==",
"max_len",
":",
"yield",
"placements",
"[",
"0",
"]",
",",
"units",
"next_items",
"[",
":",
"]",
"=",
"map",
"(",
"_next_or_none",
",",
"plans",
")",
"else",
":",
"yielded_placement",
"=",
"None",
"yielded_units",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"next_items",
")",
"for",
"i",
",",
"(",
"plc",
",",
"unit",
")",
"in",
"enumerate",
"(",
"next_items",
")",
":",
"yielded_units",
"[",
"i",
"]",
"=",
"unit",
"if",
"len",
"(",
"plc",
")",
">",
"min_len",
":",
"# trim_join_unit updates unit in place, so only",
"# placement needs to be sliced to skip min_len.",
"next_items",
"[",
"i",
"]",
"=",
"(",
"plc",
"[",
"min_len",
":",
"]",
",",
"trim_join_unit",
"(",
"unit",
",",
"min_len",
")",
")",
"else",
":",
"yielded_placement",
"=",
"plc",
"next_items",
"[",
"i",
"]",
"=",
"_next_or_none",
"(",
"plans",
"[",
"i",
"]",
")",
"yield",
"yielded_placement",
",",
"yielded_units"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/internals/concat.py#L425-L485 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | src/mem/slicc/parser.py | python | SLICC.p_decl__machine1 | (self, p) | decl : MACHINE '(' enumeration pairs ')' ':' obj_decls '{' decls '} | decl : MACHINE '(' enumeration pairs ')' ':' obj_decls '{' decls '} | [
"decl",
":",
"MACHINE",
"(",
"enumeration",
"pairs",
")",
":",
"obj_decls",
"{",
"decls",
"}"
] | def p_decl__machine1(self, p):
"decl : MACHINE '(' enumeration pairs ')' ':' obj_decls '{' decls '}'"
p[0] = ast.MachineAST(self, p[3], p[4], p[7], p[9]) | [
"def",
"p_decl__machine1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"MachineAST",
"(",
"self",
",",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"4",
"]",
",",
"p",
"[",
"7",
"]",
",",
"p",
"[",
"9",
"]",
")"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L280-L282 | ||
crosslife/OpenBird | 9e0198a1a2295f03fa1e8676e216e22c9c7d380b | cocos2d/tools/bindings-generator/clang/cindex.py | python | Cursor.objc_type_encoding | (self) | return self._objc_type_encoding | Return the Objective-C type encoding as a str. | Return the Objective-C type encoding as a str. | [
"Return",
"the",
"Objective",
"-",
"C",
"type",
"encoding",
"as",
"a",
"str",
"."
] | def objc_type_encoding(self):
"""Return the Objective-C type encoding as a str."""
if not hasattr(self, '_objc_type_encoding'):
self._objc_type_encoding = \
conf.lib.clang_getDeclObjCTypeEncoding(self)
return self._objc_type_encoding | [
"def",
"objc_type_encoding",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_objc_type_encoding'",
")",
":",
"self",
".",
"_objc_type_encoding",
"=",
"conf",
".",
"lib",
".",
"clang_getDeclObjCTypeEncoding",
"(",
"self",
")",
"return",
"self",
".",
"_objc_type_encoding"
] | https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L1383-L1389 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/buttonpanel.py | python | ButtonInfo.AddStatus | (self, name="Custom", bmp=wx.NullBitmap) | Add a programmer-defined status in addition to the 5 default status:
- Normal;
- Disabled;
- Hover;
- Pressed;
- Toggled.
:param string `name`: the new status name;
:param Bitmap `bmp`: the bitmap associated with the new status. | Add a programmer-defined status in addition to the 5 default status: | [
"Add",
"a",
"programmer",
"-",
"defined",
"status",
"in",
"addition",
"to",
"the",
"5",
"default",
"status",
":"
] | def AddStatus(self, name="Custom", bmp=wx.NullBitmap):
"""
Add a programmer-defined status in addition to the 5 default status:
- Normal;
- Disabled;
- Hover;
- Pressed;
- Toggled.
:param string `name`: the new status name;
:param Bitmap `bmp`: the bitmap associated with the new status.
"""
self._bitmaps.update({name: bmp}) | [
"def",
"AddStatus",
"(",
"self",
",",
"name",
"=",
"\"Custom\"",
",",
"bmp",
"=",
"wx",
".",
"NullBitmap",
")",
":",
"self",
".",
"_bitmaps",
".",
"update",
"(",
"{",
"name",
":",
"bmp",
"}",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L1649-L1663 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiManager.OnTabBeginDrag | (self, event) | Handles the ``EVT_AUINOTEBOOK_BEGIN_DRAG`` event.
:param `event`: a :class:`~lib.agw.aui.auibook.AuiNotebookEvent` event to be processed. | Handles the ``EVT_AUINOTEBOOK_BEGIN_DRAG`` event. | [
"Handles",
"the",
"EVT_AUINOTEBOOK_BEGIN_DRAG",
"event",
"."
] | def OnTabBeginDrag(self, event):
"""
Handles the ``EVT_AUINOTEBOOK_BEGIN_DRAG`` event.
:param `event`: a :class:`~lib.agw.aui.auibook.AuiNotebookEvent` event to be processed.
"""
if self._masterManager:
self._masterManager.OnTabBeginDrag(event)
else:
paneInfo = self.PaneFromTabEvent(event)
if paneInfo.IsOk():
# It's one of ours!
self._action = actionDragFloatingPane
mouse = wx.GetMousePosition()
# set initial float position - may have to think about this
# offset a bit more later ...
self._action_offset = wx.Point(20, 10)
self._toolbar_action_offset = wx.Point(20, 10)
paneInfo.floating_pos = mouse - self._action_offset
paneInfo.dock_pos = AUI_DOCK_NONE
paneInfo.notebook_id = -1
tab = event.GetEventObject()
if tab.HasCapture():
tab.ReleaseMouse()
# float the window
if paneInfo.IsMaximized():
self.RestorePane(paneInfo)
paneInfo.Float()
self.Update()
self._action_window = paneInfo.window
self._frame.CaptureMouse()
event.SetDispatched(True)
else:
# not our window
event.Skip() | [
"def",
"OnTabBeginDrag",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"_masterManager",
":",
"self",
".",
"_masterManager",
".",
"OnTabBeginDrag",
"(",
"event",
")",
"else",
":",
"paneInfo",
"=",
"self",
".",
"PaneFromTabEvent",
"(",
"event",
")",
"if",
"paneInfo",
".",
"IsOk",
"(",
")",
":",
"# It's one of ours!",
"self",
".",
"_action",
"=",
"actionDragFloatingPane",
"mouse",
"=",
"wx",
".",
"GetMousePosition",
"(",
")",
"# set initial float position - may have to think about this",
"# offset a bit more later ...",
"self",
".",
"_action_offset",
"=",
"wx",
".",
"Point",
"(",
"20",
",",
"10",
")",
"self",
".",
"_toolbar_action_offset",
"=",
"wx",
".",
"Point",
"(",
"20",
",",
"10",
")",
"paneInfo",
".",
"floating_pos",
"=",
"mouse",
"-",
"self",
".",
"_action_offset",
"paneInfo",
".",
"dock_pos",
"=",
"AUI_DOCK_NONE",
"paneInfo",
".",
"notebook_id",
"=",
"-",
"1",
"tab",
"=",
"event",
".",
"GetEventObject",
"(",
")",
"if",
"tab",
".",
"HasCapture",
"(",
")",
":",
"tab",
".",
"ReleaseMouse",
"(",
")",
"# float the window",
"if",
"paneInfo",
".",
"IsMaximized",
"(",
")",
":",
"self",
".",
"RestorePane",
"(",
"paneInfo",
")",
"paneInfo",
".",
"Float",
"(",
")",
"self",
".",
"Update",
"(",
")",
"self",
".",
"_action_window",
"=",
"paneInfo",
".",
"window",
"self",
".",
"_frame",
".",
"CaptureMouse",
"(",
")",
"event",
".",
"SetDispatched",
"(",
"True",
")",
"else",
":",
"# not our window",
"event",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L7317-L7364 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozbuild/frontend/context.py | python | Context._factory | (self, key) | Function called when requesting a missing key. | Function called when requesting a missing key. | [
"Function",
"called",
"when",
"requesting",
"a",
"missing",
"key",
"."
] | def _factory(self, key):
"""Function called when requesting a missing key."""
defaults = self._allowed_variables.get(key)
if not defaults:
raise KeyError('global_ns', 'get_unknown', key)
# If the default is specifically a lambda (or, rather, any function
# --but not a class that can be called), then it is actually a rule to
# generate the default that should be used.
default = defaults[0]
if issubclass(default, ContextDerivedValue):
return default(self)
else:
return default() | [
"def",
"_factory",
"(",
"self",
",",
"key",
")",
":",
"defaults",
"=",
"self",
".",
"_allowed_variables",
".",
"get",
"(",
"key",
")",
"if",
"not",
"defaults",
":",
"raise",
"KeyError",
"(",
"'global_ns'",
",",
"'get_unknown'",
",",
"key",
")",
"# If the default is specifically a lambda (or, rather, any function",
"# --but not a class that can be called), then it is actually a rule to",
"# generate the default that should be used.",
"default",
"=",
"defaults",
"[",
"0",
"]",
"if",
"issubclass",
"(",
"default",
",",
"ContextDerivedValue",
")",
":",
"return",
"default",
"(",
"self",
")",
"else",
":",
"return",
"default",
"(",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/frontend/context.py#L109-L123 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/zipfile.py | python | ZipFile.close | (self) | Close the file, and for mode 'w', 'x' and 'a' write the ending
records. | Close the file, and for mode 'w', 'x' and 'a' write the ending
records. | [
"Close",
"the",
"file",
"and",
"for",
"mode",
"w",
"x",
"and",
"a",
"write",
"the",
"ending",
"records",
"."
] | def close(self):
"""Close the file, and for mode 'w', 'x' and 'a' write the ending
records."""
if self.fp is None:
return
if self._writing:
raise ValueError("Can't close the ZIP file while there is "
"an open writing handle on it. "
"Close the writing handle before closing the zip.")
try:
if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
self._write_end_record()
finally:
fp = self.fp
self.fp = None
self._fpclose(fp) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"fp",
"is",
"None",
":",
"return",
"if",
"self",
".",
"_writing",
":",
"raise",
"ValueError",
"(",
"\"Can't close the ZIP file while there is \"",
"\"an open writing handle on it. \"",
"\"Close the writing handle before closing the zip.\"",
")",
"try",
":",
"if",
"self",
".",
"mode",
"in",
"(",
"'w'",
",",
"'x'",
",",
"'a'",
")",
"and",
"self",
".",
"_didModify",
":",
"# write ending records",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_seekable",
":",
"self",
".",
"fp",
".",
"seek",
"(",
"self",
".",
"start_dir",
")",
"self",
".",
"_write_end_record",
"(",
")",
"finally",
":",
"fp",
"=",
"self",
".",
"fp",
"self",
".",
"fp",
"=",
"None",
"self",
".",
"_fpclose",
"(",
"fp",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/zipfile.py#L1809-L1829 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ebmlib/_dirmon.py | python | WatcherThread.AddWatchDirectory | (self, dpath) | return True | Add a directory to the watch list
@param dpath: directory path (unicode)
@return: bool - True means watch was added, False means unable to list directory | Add a directory to the watch list
@param dpath: directory path (unicode)
@return: bool - True means watch was added, False means unable to list directory | [
"Add",
"a",
"directory",
"to",
"the",
"watch",
"list",
"@param",
"dpath",
":",
"directory",
"path",
"(",
"unicode",
")",
"@return",
":",
"bool",
"-",
"True",
"means",
"watch",
"was",
"added",
"False",
"means",
"unable",
"to",
"list",
"directory"
] | def AddWatchDirectory(self, dpath):
"""Add a directory to the watch list
@param dpath: directory path (unicode)
@return: bool - True means watch was added, False means unable to list directory
"""
assert os.path.isdir(dpath)
dobj = fileutil.Directory(dpath)
self._changePending = True
with self._lock:
if dobj not in self._dirs and os.access(dobj.Path, os.R_OK):
# Get current snapshot of the directory
try:
dobj = fileutil.GetDirectoryObject(dpath, False, True)
except OSError:
self._changePending = False
return False
self._dirs.append(dobj)
with self._listEmptyCond:
self._listEmptyCond.notify()
self._changePending = False
return True | [
"def",
"AddWatchDirectory",
"(",
"self",
",",
"dpath",
")",
":",
"assert",
"os",
".",
"path",
".",
"isdir",
"(",
"dpath",
")",
"dobj",
"=",
"fileutil",
".",
"Directory",
"(",
"dpath",
")",
"self",
".",
"_changePending",
"=",
"True",
"with",
"self",
".",
"_lock",
":",
"if",
"dobj",
"not",
"in",
"self",
".",
"_dirs",
"and",
"os",
".",
"access",
"(",
"dobj",
".",
"Path",
",",
"os",
".",
"R_OK",
")",
":",
"# Get current snapshot of the directory",
"try",
":",
"dobj",
"=",
"fileutil",
".",
"GetDirectoryObject",
"(",
"dpath",
",",
"False",
",",
"True",
")",
"except",
"OSError",
":",
"self",
".",
"_changePending",
"=",
"False",
"return",
"False",
"self",
".",
"_dirs",
".",
"append",
"(",
"dobj",
")",
"with",
"self",
".",
"_listEmptyCond",
":",
"self",
".",
"_listEmptyCond",
".",
"notify",
"(",
")",
"self",
".",
"_changePending",
"=",
"False",
"return",
"True"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/_dirmon.py#L250-L271 | |
lmb-freiburg/flownet2 | b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc | python/caffe/io.py | python | Transformer.preprocess | (self, in_, data) | return caffe_in | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature | [
"Format",
"input",
"for",
"Caffe",
":",
"-",
"convert",
"to",
"single",
"-",
"resize",
"to",
"input",
"dimensions",
"(",
"preserving",
"number",
"of",
"channels",
")",
"-",
"transpose",
"dimensions",
"to",
"K",
"x",
"H",
"x",
"W",
"-",
"reorder",
"channels",
"(",
"for",
"instance",
"color",
"to",
"BGR",
")",
"-",
"scale",
"raw",
"input",
"(",
"e",
".",
"g",
".",
"from",
"[",
"0",
"1",
"]",
"to",
"[",
"0",
"255",
"]",
"for",
"ImageNet",
"models",
")",
"-",
"subtract",
"mean",
"-",
"scale",
"feature"
] | def preprocess(self, in_, data):
"""
Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net
"""
self.__check_input(in_)
caffe_in = data.astype(np.float32, copy=False)
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
in_dims = self.inputs[in_][2:]
if caffe_in.shape[:2] != in_dims:
caffe_in = resize_image(caffe_in, in_dims)
if transpose is not None:
caffe_in = caffe_in.transpose(transpose)
if channel_swap is not None:
caffe_in = caffe_in[channel_swap, :, :]
if raw_scale is not None:
caffe_in *= raw_scale
if mean is not None:
caffe_in -= mean
if input_scale is not None:
caffe_in *= input_scale
return caffe_in | [
"def",
"preprocess",
"(",
"self",
",",
"in_",
",",
"data",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"caffe_in",
"=",
"data",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"copy",
"=",
"False",
")",
"transpose",
"=",
"self",
".",
"transpose",
".",
"get",
"(",
"in_",
")",
"channel_swap",
"=",
"self",
".",
"channel_swap",
".",
"get",
"(",
"in_",
")",
"raw_scale",
"=",
"self",
".",
"raw_scale",
".",
"get",
"(",
"in_",
")",
"mean",
"=",
"self",
".",
"mean",
".",
"get",
"(",
"in_",
")",
"input_scale",
"=",
"self",
".",
"input_scale",
".",
"get",
"(",
"in_",
")",
"in_dims",
"=",
"self",
".",
"inputs",
"[",
"in_",
"]",
"[",
"2",
":",
"]",
"if",
"caffe_in",
".",
"shape",
"[",
":",
"2",
"]",
"!=",
"in_dims",
":",
"caffe_in",
"=",
"resize_image",
"(",
"caffe_in",
",",
"in_dims",
")",
"if",
"transpose",
"is",
"not",
"None",
":",
"caffe_in",
"=",
"caffe_in",
".",
"transpose",
"(",
"transpose",
")",
"if",
"channel_swap",
"is",
"not",
"None",
":",
"caffe_in",
"=",
"caffe_in",
"[",
"channel_swap",
",",
":",
",",
":",
"]",
"if",
"raw_scale",
"is",
"not",
"None",
":",
"caffe_in",
"*=",
"raw_scale",
"if",
"mean",
"is",
"not",
"None",
":",
"caffe_in",
"-=",
"mean",
"if",
"input_scale",
"is",
"not",
"None",
":",
"caffe_in",
"*=",
"input_scale",
"return",
"caffe_in"
] | https://github.com/lmb-freiburg/flownet2/blob/b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc/python/caffe/io.py#L122-L162 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py | python | TFAsymmetryFittingModel._update_fit_function_parameters_for_simultaneous_fit | (self, dataset_names: list, parameter_values: list) | Updates the function parameters for the given dataset names if in simultaneous fit mode. | Updates the function parameters for the given dataset names if in simultaneous fit mode. | [
"Updates",
"the",
"function",
"parameters",
"for",
"the",
"given",
"dataset",
"names",
"if",
"in",
"simultaneous",
"fit",
"mode",
"."
] | def _update_fit_function_parameters_for_simultaneous_fit(self, dataset_names: list, parameter_values: list) -> None:
"""Updates the function parameters for the given dataset names if in simultaneous fit mode."""
super()._update_fit_function_parameters_for_simultaneous_fit(dataset_names, parameter_values)
if self.fitting_context.tf_asymmetry_mode:
self._update_tf_fit_function_parameters_for_simultaneous_fit(dataset_names, parameter_values) | [
"def",
"_update_fit_function_parameters_for_simultaneous_fit",
"(",
"self",
",",
"dataset_names",
":",
"list",
",",
"parameter_values",
":",
"list",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"_update_fit_function_parameters_for_simultaneous_fit",
"(",
"dataset_names",
",",
"parameter_values",
")",
"if",
"self",
".",
"fitting_context",
".",
"tf_asymmetry_mode",
":",
"self",
".",
"_update_tf_fit_function_parameters_for_simultaneous_fit",
"(",
"dataset_names",
",",
"parameter_values",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py#L782-L787 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py | python | Minitaur.GetTrueMotorVelocities | (self) | return motor_velocities | Get the velocity of all eight motors.
Returns:
Velocities of all eight motors. | Get the velocity of all eight motors. | [
"Get",
"the",
"velocity",
"of",
"all",
"eight",
"motors",
"."
] | def GetTrueMotorVelocities(self):
"""Get the velocity of all eight motors.
Returns:
Velocities of all eight motors.
"""
motor_velocities = [
self._pybullet_client.getJointState(self.quadruped, motor_id)[1]
for motor_id in self._motor_id_list
]
motor_velocities = np.multiply(motor_velocities, self._motor_direction)
return motor_velocities | [
"def",
"GetTrueMotorVelocities",
"(",
"self",
")",
":",
"motor_velocities",
"=",
"[",
"self",
".",
"_pybullet_client",
".",
"getJointState",
"(",
"self",
".",
"quadruped",
",",
"motor_id",
")",
"[",
"1",
"]",
"for",
"motor_id",
"in",
"self",
".",
"_motor_id_list",
"]",
"motor_velocities",
"=",
"np",
".",
"multiply",
"(",
"motor_velocities",
",",
"self",
".",
"_motor_direction",
")",
"return",
"motor_velocities"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py#L479-L490 | |
Komnomnomnom/swigibpy | cfd307fdbfaffabc69a2dc037538d7e34a8b8daf | swigibpy.py | python | EClientSocketBase.reqGlobalCancel | (self) | return _swigibpy.EClientSocketBase_reqGlobalCancel(self) | reqGlobalCancel(EClientSocketBase self) | reqGlobalCancel(EClientSocketBase self) | [
"reqGlobalCancel",
"(",
"EClientSocketBase",
"self",
")"
] | def reqGlobalCancel(self):
"""reqGlobalCancel(EClientSocketBase self)"""
return _swigibpy.EClientSocketBase_reqGlobalCancel(self) | [
"def",
"reqGlobalCancel",
"(",
"self",
")",
":",
"return",
"_swigibpy",
".",
"EClientSocketBase_reqGlobalCancel",
"(",
"self",
")"
] | https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1627-L1629 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/config.py | python | get_memory_growth | (device) | return context.context().get_memory_growth(device) | Get if memory growth is enabled for a `PhysicalDevice`.
If memory growth is enabled for a `PhysicalDevice`, the runtime initialization
will not allocate all memory on the device.
For example:
>>> physical_devices = tf.config.list_physical_devices('GPU')
>>> try:
... tf.config.experimental.set_memory_growth(physical_devices[0], True)
... assert tf.config.experimental.get_memory_growth(physical_devices[0])
... except:
... # Invalid device or cannot modify virtual devices once initialized.
... pass
Args:
device: `PhysicalDevice` to query
Returns:
A boolean indicating the memory growth setting for the `PhysicalDevice`.
Raises:
ValueError: Invalid `PhysicalDevice` specified. | Get if memory growth is enabled for a `PhysicalDevice`. | [
"Get",
"if",
"memory",
"growth",
"is",
"enabled",
"for",
"a",
"PhysicalDevice",
"."
] | def get_memory_growth(device):
"""Get if memory growth is enabled for a `PhysicalDevice`.
If memory growth is enabled for a `PhysicalDevice`, the runtime initialization
will not allocate all memory on the device.
For example:
>>> physical_devices = tf.config.list_physical_devices('GPU')
>>> try:
... tf.config.experimental.set_memory_growth(physical_devices[0], True)
... assert tf.config.experimental.get_memory_growth(physical_devices[0])
... except:
... # Invalid device or cannot modify virtual devices once initialized.
... pass
Args:
device: `PhysicalDevice` to query
Returns:
A boolean indicating the memory growth setting for the `PhysicalDevice`.
Raises:
ValueError: Invalid `PhysicalDevice` specified.
"""
return context.context().get_memory_growth(device) | [
"def",
"get_memory_growth",
"(",
"device",
")",
":",
"return",
"context",
".",
"context",
"(",
")",
".",
"get_memory_growth",
"(",
"device",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/config.py#L660-L685 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/load.py | python | load_internal | (export_dir, tags=None, loader_cls=Loader) | return root | Loader implementation. | Loader implementation. | [
"Loader",
"implementation",
"."
] | def load_internal(export_dir, tags=None, loader_cls=Loader):
"""Loader implementation."""
if tags is not None and not isinstance(tags, set):
# Supports e.g. tags=SERVING and tags=[SERVING]. Sets aren't considered
# sequences for nest.flatten, so we put those through as-is.
tags = nest.flatten(tags)
saved_model_proto = loader_impl.parse_saved_model(export_dir)
if (len(saved_model_proto.meta_graphs) == 1
and saved_model_proto.meta_graphs[0].HasField("object_graph_def")):
meta_graph_def = saved_model_proto.meta_graphs[0]
if (tags is not None
and set(tags) != set(meta_graph_def.meta_info_def.tags)):
raise ValueError(
("The SavedModel at {} has one MetaGraph with tags {}, but got an "
"incompatible argument tags={} to tf.saved_model.load. You may omit "
"it, pass 'None', or pass matching tags.")
.format(export_dir, meta_graph_def.meta_info_def.tags, tags))
object_graph_proto = meta_graph_def.object_graph_def
with ops.init_scope():
loader = loader_cls(object_graph_proto,
saved_model_proto,
export_dir)
root = loader.get(0)
root.tensorflow_version = meta_graph_def.meta_info_def.tensorflow_version
root.tensorflow_git_version = (
meta_graph_def.meta_info_def.tensorflow_git_version)
else:
with ops.init_scope():
root = load_v1_in_v2.load(export_dir, tags)
return root | [
"def",
"load_internal",
"(",
"export_dir",
",",
"tags",
"=",
"None",
",",
"loader_cls",
"=",
"Loader",
")",
":",
"if",
"tags",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"tags",
",",
"set",
")",
":",
"# Supports e.g. tags=SERVING and tags=[SERVING]. Sets aren't considered",
"# sequences for nest.flatten, so we put those through as-is.",
"tags",
"=",
"nest",
".",
"flatten",
"(",
"tags",
")",
"saved_model_proto",
"=",
"loader_impl",
".",
"parse_saved_model",
"(",
"export_dir",
")",
"if",
"(",
"len",
"(",
"saved_model_proto",
".",
"meta_graphs",
")",
"==",
"1",
"and",
"saved_model_proto",
".",
"meta_graphs",
"[",
"0",
"]",
".",
"HasField",
"(",
"\"object_graph_def\"",
")",
")",
":",
"meta_graph_def",
"=",
"saved_model_proto",
".",
"meta_graphs",
"[",
"0",
"]",
"if",
"(",
"tags",
"is",
"not",
"None",
"and",
"set",
"(",
"tags",
")",
"!=",
"set",
"(",
"meta_graph_def",
".",
"meta_info_def",
".",
"tags",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"\"The SavedModel at {} has one MetaGraph with tags {}, but got an \"",
"\"incompatible argument tags={} to tf.saved_model.load. You may omit \"",
"\"it, pass 'None', or pass matching tags.\"",
")",
".",
"format",
"(",
"export_dir",
",",
"meta_graph_def",
".",
"meta_info_def",
".",
"tags",
",",
"tags",
")",
")",
"object_graph_proto",
"=",
"meta_graph_def",
".",
"object_graph_def",
"with",
"ops",
".",
"init_scope",
"(",
")",
":",
"loader",
"=",
"loader_cls",
"(",
"object_graph_proto",
",",
"saved_model_proto",
",",
"export_dir",
")",
"root",
"=",
"loader",
".",
"get",
"(",
"0",
")",
"root",
".",
"tensorflow_version",
"=",
"meta_graph_def",
".",
"meta_info_def",
".",
"tensorflow_version",
"root",
".",
"tensorflow_git_version",
"=",
"(",
"meta_graph_def",
".",
"meta_info_def",
".",
"tensorflow_git_version",
")",
"else",
":",
"with",
"ops",
".",
"init_scope",
"(",
")",
":",
"root",
"=",
"load_v1_in_v2",
".",
"load",
"(",
"export_dir",
",",
"tags",
")",
"return",
"root"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/load.py#L522-L551 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/boto3/ec2/createtags.py | python | inject_create_tags | (event_name, class_attributes, **kwargs) | This injects a custom create_tags method onto the ec2 service resource
This is needed because the resource model is not able to express
creating multiple tag resources based on the fact you can apply a set
of tags to multiple ec2 resources. | This injects a custom create_tags method onto the ec2 service resource | [
"This",
"injects",
"a",
"custom",
"create_tags",
"method",
"onto",
"the",
"ec2",
"service",
"resource"
] | def inject_create_tags(event_name, class_attributes, **kwargs):
"""This injects a custom create_tags method onto the ec2 service resource
This is needed because the resource model is not able to express
creating multiple tag resources based on the fact you can apply a set
of tags to multiple ec2 resources.
"""
class_attributes['create_tags'] = create_tags | [
"def",
"inject_create_tags",
"(",
"event_name",
",",
"class_attributes",
",",
"*",
"*",
"kwargs",
")",
":",
"class_attributes",
"[",
"'create_tags'",
"]",
"=",
"create_tags"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/boto3/ec2/createtags.py#L15-L22 | ||
zeroc-ice/ice | 6df7df6039674d58fb5ab9a08e46f28591a210f7 | python/python/Ice/__init__.py | python | Application.__init__ | (self, signalPolicy=0) | The constructor accepts an optional argument indicating
whether to handle signals. The value should be either
Application.HandleSignals (the default) or
Application.NoSignalHandling. | The constructor accepts an optional argument indicating
whether to handle signals. The value should be either
Application.HandleSignals (the default) or
Application.NoSignalHandling. | [
"The",
"constructor",
"accepts",
"an",
"optional",
"argument",
"indicating",
"whether",
"to",
"handle",
"signals",
".",
"The",
"value",
"should",
"be",
"either",
"Application",
".",
"HandleSignals",
"(",
"the",
"default",
")",
"or",
"Application",
".",
"NoSignalHandling",
"."
] | def __init__(self, signalPolicy=0): # HandleSignals=0
'''The constructor accepts an optional argument indicating
whether to handle signals. The value should be either
Application.HandleSignals (the default) or
Application.NoSignalHandling.
'''
if type(self) == Application:
raise RuntimeError("Ice.Application is an abstract class")
Application._signalPolicy = signalPolicy | [
"def",
"__init__",
"(",
"self",
",",
"signalPolicy",
"=",
"0",
")",
":",
"# HandleSignals=0",
"if",
"type",
"(",
"self",
")",
"==",
"Application",
":",
"raise",
"RuntimeError",
"(",
"\"Ice.Application is an abstract class\"",
")",
"Application",
".",
"_signalPolicy",
"=",
"signalPolicy"
] | https://github.com/zeroc-ice/ice/blob/6df7df6039674d58fb5ab9a08e46f28591a210f7/python/python/Ice/__init__.py#L1463-L1471 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.SetSelAlpha | (*args, **kwargs) | return _stc.StyledTextCtrl_SetSelAlpha(*args, **kwargs) | SetSelAlpha(self, int alpha)
Set the alpha of the selection. | SetSelAlpha(self, int alpha) | [
"SetSelAlpha",
"(",
"self",
"int",
"alpha",
")"
] | def SetSelAlpha(*args, **kwargs):
"""
SetSelAlpha(self, int alpha)
Set the alpha of the selection.
"""
return _stc.StyledTextCtrl_SetSelAlpha(*args, **kwargs) | [
"def",
"SetSelAlpha",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetSelAlpha",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L2747-L2753 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/linalg/matfuncs.py | python | coshm | (A) | return _maybe_real(A, 0.5 * (expm(A) + expm(-A))) | Compute the hyperbolic matrix cosine.
This routine uses expm to compute the matrix exponentials.
Parameters
----------
A : (N, N) array_like
Input array.
Returns
-------
coshm : (N, N) ndarray
Hyperbolic matrix cosine of `A`
Examples
--------
>>> from scipy.linalg import tanhm, sinhm, coshm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> c = coshm(a)
>>> c
array([[ 11.24592233, 38.76236492],
[ 12.92078831, 50.00828725]])
Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
>>> t = tanhm(a)
>>> s = sinhm(a)
>>> t - s.dot(np.linalg.inv(c))
array([[ 2.72004641e-15, 4.55191440e-15],
[ 0.00000000e+00, -5.55111512e-16]]) | Compute the hyperbolic matrix cosine. | [
"Compute",
"the",
"hyperbolic",
"matrix",
"cosine",
"."
] | def coshm(A):
"""
Compute the hyperbolic matrix cosine.
This routine uses expm to compute the matrix exponentials.
Parameters
----------
A : (N, N) array_like
Input array.
Returns
-------
coshm : (N, N) ndarray
Hyperbolic matrix cosine of `A`
Examples
--------
>>> from scipy.linalg import tanhm, sinhm, coshm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> c = coshm(a)
>>> c
array([[ 11.24592233, 38.76236492],
[ 12.92078831, 50.00828725]])
Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
>>> t = tanhm(a)
>>> s = sinhm(a)
>>> t - s.dot(np.linalg.inv(c))
array([[ 2.72004641e-15, 4.55191440e-15],
[ 0.00000000e+00, -5.55111512e-16]])
"""
A = _asarray_square(A)
return _maybe_real(A, 0.5 * (expm(A) + expm(-A))) | [
"def",
"coshm",
"(",
"A",
")",
":",
"A",
"=",
"_asarray_square",
"(",
"A",
")",
"return",
"_maybe_real",
"(",
"A",
",",
"0.5",
"*",
"(",
"expm",
"(",
"A",
")",
"+",
"expm",
"(",
"-",
"A",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/matfuncs.py#L445-L480 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py | python | Separator.__init__ | (self, master=None, **kw) | Construct a Ttk Separator with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
orient | Construct a Ttk Separator with parent master. | [
"Construct",
"a",
"Ttk",
"Separator",
"with",
"parent",
"master",
"."
] | def __init__(self, master=None, **kw):
"""Construct a Ttk Separator with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
orient
"""
Widget.__init__(self, master, "ttk::separator", kw) | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"Widget",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"\"ttk::separator\"",
",",
"kw",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py#L1119-L1130 | ||
google/filament | d21f092645b8e1e312307cbf89f1484891347c63 | third_party/spirv-tools/utils/check_copyright.py | python | skip | (line) | return stripped == '' or stripped.startswith('#!') | Returns true if line is all whitespace or shebang. | Returns true if line is all whitespace or shebang. | [
"Returns",
"true",
"if",
"line",
"is",
"all",
"whitespace",
"or",
"shebang",
"."
] | def skip(line):
"""Returns true if line is all whitespace or shebang."""
stripped = line.lstrip()
return stripped == '' or stripped.startswith('#!') | [
"def",
"skip",
"(",
"line",
")",
":",
"stripped",
"=",
"line",
".",
"lstrip",
"(",
")",
"return",
"stripped",
"==",
"''",
"or",
"stripped",
".",
"startswith",
"(",
"'#!'",
")"
] | https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/spirv-tools/utils/check_copyright.py#L96-L99 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/dtypes/common.py | python | get_dtype | (arr_or_dtype) | return pandas_dtype(arr_or_dtype) | Get the dtype instance associated with an array
or dtype object.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype object whose dtype we want to extract.
Returns
-------
obj_dtype : The extract dtype instance from the
passed in array or dtype object.
Raises
------
TypeError : The passed in object is None. | Get the dtype instance associated with an array
or dtype object. | [
"Get",
"the",
"dtype",
"instance",
"associated",
"with",
"an",
"array",
"or",
"dtype",
"object",
"."
] | def get_dtype(arr_or_dtype) -> DtypeObj:
"""
Get the dtype instance associated with an array
or dtype object.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype object whose dtype we want to extract.
Returns
-------
obj_dtype : The extract dtype instance from the
passed in array or dtype object.
Raises
------
TypeError : The passed in object is None.
"""
if arr_or_dtype is None:
raise TypeError("Cannot deduce dtype from null object")
# fastpath
elif isinstance(arr_or_dtype, np.dtype):
return arr_or_dtype
elif isinstance(arr_or_dtype, type):
return np.dtype(arr_or_dtype)
# if we have an array-like
elif hasattr(arr_or_dtype, "dtype"):
arr_or_dtype = arr_or_dtype.dtype
return pandas_dtype(arr_or_dtype) | [
"def",
"get_dtype",
"(",
"arr_or_dtype",
")",
"->",
"DtypeObj",
":",
"if",
"arr_or_dtype",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Cannot deduce dtype from null object\"",
")",
"# fastpath",
"elif",
"isinstance",
"(",
"arr_or_dtype",
",",
"np",
".",
"dtype",
")",
":",
"return",
"arr_or_dtype",
"elif",
"isinstance",
"(",
"arr_or_dtype",
",",
"type",
")",
":",
"return",
"np",
".",
"dtype",
"(",
"arr_or_dtype",
")",
"# if we have an array-like",
"elif",
"hasattr",
"(",
"arr_or_dtype",
",",
"\"dtype\"",
")",
":",
"arr_or_dtype",
"=",
"arr_or_dtype",
".",
"dtype",
"return",
"pandas_dtype",
"(",
"arr_or_dtype",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/common.py#L1543-L1575 | |
eerolanguage/clang | 91360bee004a1cbdb95fe5eb605ef243152da41b | bindings/python/clang/cindex.py | python | CursorKind.is_statement | (self) | return conf.lib.clang_isStatement(self) | Test if this is a statement kind. | Test if this is a statement kind. | [
"Test",
"if",
"this",
"is",
"a",
"statement",
"kind",
"."
] | def is_statement(self):
"""Test if this is a statement kind."""
return conf.lib.clang_isStatement(self) | [
"def",
"is_statement",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isStatement",
"(",
"self",
")"
] | https://github.com/eerolanguage/clang/blob/91360bee004a1cbdb95fe5eb605ef243152da41b/bindings/python/clang/cindex.py#L554-L556 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py | python | HTMLDoc.docmodule | (self, object, name=None, mod=None, *ignored) | return result | Produce HTML documentation for a module object. | Produce HTML documentation for a module object. | [
"Produce",
"HTML",
"documentation",
"for",
"a",
"module",
"object",
"."
] | def docmodule(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a module object."""
name = object.__name__ # ignore the passed-in name
try:
all = object.__all__
except AttributeError:
all = None
parts = split(name, '.')
links = []
for i in range(len(parts)-1):
links.append(
'<a href="%s.html"><font color="#ffffff">%s</font></a>' %
(join(parts[:i+1], '.'), parts[i]))
linkedname = join(links + parts[-1:], '.')
head = '<big><big><strong>%s</strong></big></big>' % linkedname
try:
path = inspect.getabsfile(object)
url = path
if sys.platform == 'win32':
import nturl2path
url = nturl2path.pathname2url(path)
filelink = '<a href="file:%s">%s</a>' % (url, path)
except TypeError:
filelink = '(built-in)'
info = []
if hasattr(object, '__version__'):
version = str(object.__version__)
if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
version = strip(version[11:-1])
info.append('version %s' % self.escape(version))
if hasattr(object, '__date__'):
info.append(self.escape(str(object.__date__)))
if info:
head = head + ' (%s)' % join(info, ', ')
docloc = self.getdocloc(object)
if docloc is not None:
docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
else:
docloc = ''
result = self.heading(
head, '#ffffff', '#7799ee',
'<a href=".">index</a><br>' + filelink + docloc)
modules = inspect.getmembers(object, inspect.ismodule)
classes, cdict = [], {}
for key, value in inspect.getmembers(object, inspect.isclass):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
(inspect.getmodule(value) or object) is object):
if visiblename(key, all, object):
classes.append((key, value))
cdict[key] = cdict[value] = '#' + key
for key, value in classes:
for base in value.__bases__:
key, modname = base.__name__, base.__module__
module = sys.modules.get(modname)
if modname != name and module and hasattr(module, key):
if getattr(module, key) is base:
if not key in cdict:
cdict[key] = cdict[base] = modname + '.html#' + key
funcs, fdict = [], {}
for key, value in inspect.getmembers(object, inspect.isroutine):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
inspect.isbuiltin(value) or inspect.getmodule(value) is object):
if visiblename(key, all, object):
funcs.append((key, value))
fdict[key] = '#-' + key
if inspect.isfunction(value): fdict[value] = fdict[key]
data = []
for key, value in inspect.getmembers(object, isdata):
if visiblename(key, all, object):
data.append((key, value))
doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
doc = doc and '<tt>%s</tt>' % doc
result = result + '<p>%s</p>\n' % doc
if hasattr(object, '__path__'):
modpkgs = []
for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
modpkgs.append((modname, name, ispkg, 0))
modpkgs.sort()
contents = self.multicolumn(modpkgs, self.modpkglink)
result = result + self.bigsection(
'Package Contents', '#ffffff', '#aa55cc', contents)
elif modules:
contents = self.multicolumn(
modules, lambda key_value, s=self: s.modulelink(key_value[1]))
result = result + self.bigsection(
'Modules', '#ffffff', '#aa55cc', contents)
if classes:
classlist = map(lambda key_value: key_value[1], classes)
contents = [
self.formattree(inspect.getclasstree(classlist, 1), name)]
for key, value in classes:
contents.append(self.document(value, key, name, fdict, cdict))
result = result + self.bigsection(
'Classes', '#ffffff', '#ee77aa', join(contents))
if funcs:
contents = []
for key, value in funcs:
contents.append(self.document(value, key, name, fdict, cdict))
result = result + self.bigsection(
'Functions', '#ffffff', '#eeaa77', join(contents))
if data:
contents = []
for key, value in data:
contents.append(self.document(value, key))
result = result + self.bigsection(
'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
if hasattr(object, '__author__'):
contents = self.markup(str(object.__author__), self.preformat)
result = result + self.bigsection(
'Author', '#ffffff', '#7799ee', contents)
if hasattr(object, '__credits__'):
contents = self.markup(str(object.__credits__), self.preformat)
result = result + self.bigsection(
'Credits', '#ffffff', '#7799ee', contents)
return result | [
"def",
"docmodule",
"(",
"self",
",",
"object",
",",
"name",
"=",
"None",
",",
"mod",
"=",
"None",
",",
"*",
"ignored",
")",
":",
"name",
"=",
"object",
".",
"__name__",
"# ignore the passed-in name",
"try",
":",
"all",
"=",
"object",
".",
"__all__",
"except",
"AttributeError",
":",
"all",
"=",
"None",
"parts",
"=",
"split",
"(",
"name",
",",
"'.'",
")",
"links",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"parts",
")",
"-",
"1",
")",
":",
"links",
".",
"append",
"(",
"'<a href=\"%s.html\"><font color=\"#ffffff\">%s</font></a>'",
"%",
"(",
"join",
"(",
"parts",
"[",
":",
"i",
"+",
"1",
"]",
",",
"'.'",
")",
",",
"parts",
"[",
"i",
"]",
")",
")",
"linkedname",
"=",
"join",
"(",
"links",
"+",
"parts",
"[",
"-",
"1",
":",
"]",
",",
"'.'",
")",
"head",
"=",
"'<big><big><strong>%s</strong></big></big>'",
"%",
"linkedname",
"try",
":",
"path",
"=",
"inspect",
".",
"getabsfile",
"(",
"object",
")",
"url",
"=",
"path",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"import",
"nturl2path",
"url",
"=",
"nturl2path",
".",
"pathname2url",
"(",
"path",
")",
"filelink",
"=",
"'<a href=\"file:%s\">%s</a>'",
"%",
"(",
"url",
",",
"path",
")",
"except",
"TypeError",
":",
"filelink",
"=",
"'(built-in)'",
"info",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"object",
",",
"'__version__'",
")",
":",
"version",
"=",
"str",
"(",
"object",
".",
"__version__",
")",
"if",
"version",
"[",
":",
"11",
"]",
"==",
"'$'",
"+",
"'Revision: '",
"and",
"version",
"[",
"-",
"1",
":",
"]",
"==",
"'$'",
":",
"version",
"=",
"strip",
"(",
"version",
"[",
"11",
":",
"-",
"1",
"]",
")",
"info",
".",
"append",
"(",
"'version %s'",
"%",
"self",
".",
"escape",
"(",
"version",
")",
")",
"if",
"hasattr",
"(",
"object",
",",
"'__date__'",
")",
":",
"info",
".",
"append",
"(",
"self",
".",
"escape",
"(",
"str",
"(",
"object",
".",
"__date__",
")",
")",
")",
"if",
"info",
":",
"head",
"=",
"head",
"+",
"' (%s)'",
"%",
"join",
"(",
"info",
",",
"', '",
")",
"docloc",
"=",
"self",
".",
"getdocloc",
"(",
"object",
")",
"if",
"docloc",
"is",
"not",
"None",
":",
"docloc",
"=",
"'<br><a href=\"%(docloc)s\">Module Docs</a>'",
"%",
"locals",
"(",
")",
"else",
":",
"docloc",
"=",
"''",
"result",
"=",
"self",
".",
"heading",
"(",
"head",
",",
"'#ffffff'",
",",
"'#7799ee'",
",",
"'<a href=\".\">index</a><br>'",
"+",
"filelink",
"+",
"docloc",
")",
"modules",
"=",
"inspect",
".",
"getmembers",
"(",
"object",
",",
"inspect",
".",
"ismodule",
")",
"classes",
",",
"cdict",
"=",
"[",
"]",
",",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"inspect",
".",
"getmembers",
"(",
"object",
",",
"inspect",
".",
"isclass",
")",
":",
"# if __all__ exists, believe it. Otherwise use old heuristic.",
"if",
"(",
"all",
"is",
"not",
"None",
"or",
"(",
"inspect",
".",
"getmodule",
"(",
"value",
")",
"or",
"object",
")",
"is",
"object",
")",
":",
"if",
"visiblename",
"(",
"key",
",",
"all",
",",
"object",
")",
":",
"classes",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"cdict",
"[",
"key",
"]",
"=",
"cdict",
"[",
"value",
"]",
"=",
"'#'",
"+",
"key",
"for",
"key",
",",
"value",
"in",
"classes",
":",
"for",
"base",
"in",
"value",
".",
"__bases__",
":",
"key",
",",
"modname",
"=",
"base",
".",
"__name__",
",",
"base",
".",
"__module__",
"module",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"modname",
")",
"if",
"modname",
"!=",
"name",
"and",
"module",
"and",
"hasattr",
"(",
"module",
",",
"key",
")",
":",
"if",
"getattr",
"(",
"module",
",",
"key",
")",
"is",
"base",
":",
"if",
"not",
"key",
"in",
"cdict",
":",
"cdict",
"[",
"key",
"]",
"=",
"cdict",
"[",
"base",
"]",
"=",
"modname",
"+",
"'.html#'",
"+",
"key",
"funcs",
",",
"fdict",
"=",
"[",
"]",
",",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"inspect",
".",
"getmembers",
"(",
"object",
",",
"inspect",
".",
"isroutine",
")",
":",
"# if __all__ exists, believe it. Otherwise use old heuristic.",
"if",
"(",
"all",
"is",
"not",
"None",
"or",
"inspect",
".",
"isbuiltin",
"(",
"value",
")",
"or",
"inspect",
".",
"getmodule",
"(",
"value",
")",
"is",
"object",
")",
":",
"if",
"visiblename",
"(",
"key",
",",
"all",
",",
"object",
")",
":",
"funcs",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"fdict",
"[",
"key",
"]",
"=",
"'#-'",
"+",
"key",
"if",
"inspect",
".",
"isfunction",
"(",
"value",
")",
":",
"fdict",
"[",
"value",
"]",
"=",
"fdict",
"[",
"key",
"]",
"data",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"inspect",
".",
"getmembers",
"(",
"object",
",",
"isdata",
")",
":",
"if",
"visiblename",
"(",
"key",
",",
"all",
",",
"object",
")",
":",
"data",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"doc",
"=",
"self",
".",
"markup",
"(",
"getdoc",
"(",
"object",
")",
",",
"self",
".",
"preformat",
",",
"fdict",
",",
"cdict",
")",
"doc",
"=",
"doc",
"and",
"'<tt>%s</tt>'",
"%",
"doc",
"result",
"=",
"result",
"+",
"'<p>%s</p>\\n'",
"%",
"doc",
"if",
"hasattr",
"(",
"object",
",",
"'__path__'",
")",
":",
"modpkgs",
"=",
"[",
"]",
"for",
"importer",
",",
"modname",
",",
"ispkg",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"object",
".",
"__path__",
")",
":",
"modpkgs",
".",
"append",
"(",
"(",
"modname",
",",
"name",
",",
"ispkg",
",",
"0",
")",
")",
"modpkgs",
".",
"sort",
"(",
")",
"contents",
"=",
"self",
".",
"multicolumn",
"(",
"modpkgs",
",",
"self",
".",
"modpkglink",
")",
"result",
"=",
"result",
"+",
"self",
".",
"bigsection",
"(",
"'Package Contents'",
",",
"'#ffffff'",
",",
"'#aa55cc'",
",",
"contents",
")",
"elif",
"modules",
":",
"contents",
"=",
"self",
".",
"multicolumn",
"(",
"modules",
",",
"lambda",
"key_value",
",",
"s",
"=",
"self",
":",
"s",
".",
"modulelink",
"(",
"key_value",
"[",
"1",
"]",
")",
")",
"result",
"=",
"result",
"+",
"self",
".",
"bigsection",
"(",
"'Modules'",
",",
"'#ffffff'",
",",
"'#aa55cc'",
",",
"contents",
")",
"if",
"classes",
":",
"classlist",
"=",
"map",
"(",
"lambda",
"key_value",
":",
"key_value",
"[",
"1",
"]",
",",
"classes",
")",
"contents",
"=",
"[",
"self",
".",
"formattree",
"(",
"inspect",
".",
"getclasstree",
"(",
"classlist",
",",
"1",
")",
",",
"name",
")",
"]",
"for",
"key",
",",
"value",
"in",
"classes",
":",
"contents",
".",
"append",
"(",
"self",
".",
"document",
"(",
"value",
",",
"key",
",",
"name",
",",
"fdict",
",",
"cdict",
")",
")",
"result",
"=",
"result",
"+",
"self",
".",
"bigsection",
"(",
"'Classes'",
",",
"'#ffffff'",
",",
"'#ee77aa'",
",",
"join",
"(",
"contents",
")",
")",
"if",
"funcs",
":",
"contents",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"funcs",
":",
"contents",
".",
"append",
"(",
"self",
".",
"document",
"(",
"value",
",",
"key",
",",
"name",
",",
"fdict",
",",
"cdict",
")",
")",
"result",
"=",
"result",
"+",
"self",
".",
"bigsection",
"(",
"'Functions'",
",",
"'#ffffff'",
",",
"'#eeaa77'",
",",
"join",
"(",
"contents",
")",
")",
"if",
"data",
":",
"contents",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"data",
":",
"contents",
".",
"append",
"(",
"self",
".",
"document",
"(",
"value",
",",
"key",
")",
")",
"result",
"=",
"result",
"+",
"self",
".",
"bigsection",
"(",
"'Data'",
",",
"'#ffffff'",
",",
"'#55aa55'",
",",
"join",
"(",
"contents",
",",
"'<br>\\n'",
")",
")",
"if",
"hasattr",
"(",
"object",
",",
"'__author__'",
")",
":",
"contents",
"=",
"self",
".",
"markup",
"(",
"str",
"(",
"object",
".",
"__author__",
")",
",",
"self",
".",
"preformat",
")",
"result",
"=",
"result",
"+",
"self",
".",
"bigsection",
"(",
"'Author'",
",",
"'#ffffff'",
",",
"'#7799ee'",
",",
"contents",
")",
"if",
"hasattr",
"(",
"object",
",",
"'__credits__'",
")",
":",
"contents",
"=",
"self",
".",
"markup",
"(",
"str",
"(",
"object",
".",
"__credits__",
")",
",",
"self",
".",
"preformat",
")",
"result",
"=",
"result",
"+",
"self",
".",
"bigsection",
"(",
"'Credits'",
",",
"'#ffffff'",
",",
"'#7799ee'",
",",
"contents",
")",
"return",
"result"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py#L583-L705 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py | python | QueueBase.enqueue | (self, vals, name=None) | Enqueues one element to this queue.
If the queue is full when this operation executes, it will block
until the element has been enqueued.
At runtime, this operation may raise an error if the queue is
[closed](#QueueBase.close) before or during its execution. If the
queue is closed before this operation runs,
`tf.errors.AbortedError` will be raised. If this operation is
blocked, and either (i) the queue is closed by a close operation
with `cancel_pending_enqueues=True`, or (ii) the session is
[closed](../../api_docs/python/client.md#Session.close),
`tf.errors.CancelledError` will be raised.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary containing
the values to enqueue.
name: A name for the operation (optional).
Returns:
The operation that enqueues a new tuple of tensors to the queue. | Enqueues one element to this queue. | [
"Enqueues",
"one",
"element",
"to",
"this",
"queue",
"."
] | def enqueue(self, vals, name=None):
"""Enqueues one element to this queue.
If the queue is full when this operation executes, it will block
until the element has been enqueued.
At runtime, this operation may raise an error if the queue is
[closed](#QueueBase.close) before or during its execution. If the
queue is closed before this operation runs,
`tf.errors.AbortedError` will be raised. If this operation is
blocked, and either (i) the queue is closed by a close operation
with `cancel_pending_enqueues=True`, or (ii) the session is
[closed](../../api_docs/python/client.md#Session.close),
`tf.errors.CancelledError` will be raised.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary containing
the values to enqueue.
name: A name for the operation (optional).
Returns:
The operation that enqueues a new tuple of tensors to the queue.
"""
with ops.op_scope(self._scope_vals(vals), name,
"%s_enqueue" % self._name) as scope:
vals = self._check_enqueue_dtypes(vals)
# NOTE(mrry): Not using a shape function because we need access to
# the `QueueBase` object.
for val, shape in zip(vals, self._shapes):
val.get_shape().assert_is_compatible_with(shape)
return gen_data_flow_ops._queue_enqueue(self._queue_ref, vals, name=scope) | [
"def",
"enqueue",
"(",
"self",
",",
"vals",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"self",
".",
"_scope_vals",
"(",
"vals",
")",
",",
"name",
",",
"\"%s_enqueue\"",
"%",
"self",
".",
"_name",
")",
"as",
"scope",
":",
"vals",
"=",
"self",
".",
"_check_enqueue_dtypes",
"(",
"vals",
")",
"# NOTE(mrry): Not using a shape function because we need access to",
"# the `QueueBase` object.",
"for",
"val",
",",
"shape",
"in",
"zip",
"(",
"vals",
",",
"self",
".",
"_shapes",
")",
":",
"val",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"shape",
")",
"return",
"gen_data_flow_ops",
".",
"_queue_enqueue",
"(",
"self",
".",
"_queue_ref",
",",
"vals",
",",
"name",
"=",
"scope",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py#L274-L306 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unicode.py | python | _unicode_title | (data, length, res, maxchars) | return k | This is a translation of the function that titles a unicode string. | This is a translation of the function that titles a unicode string. | [
"This",
"is",
"a",
"translation",
"of",
"the",
"function",
"that",
"titles",
"a",
"unicode",
"string",
"."
] | def _unicode_title(data, length, res, maxchars):
"""This is a translation of the function that titles a unicode string."""
k = 0
previous_cased = False
mapped = np.empty(3, dtype=_Py_UCS4)
for idx in range(length):
mapped.fill(0)
code_point = _get_code_point(data, idx)
if previous_cased:
n_res = _lower_ucs4(code_point, data, length, idx, mapped)
else:
n_res = _PyUnicode_ToTitleFull(_Py_UCS4(code_point), mapped)
for m in mapped[:n_res]:
maxchar, = maxchars
maxchars[0] = max(maxchar, m)
_set_code_point(res, k, m)
k += 1
previous_cased = _PyUnicode_IsCased(_Py_UCS4(code_point))
return k | [
"def",
"_unicode_title",
"(",
"data",
",",
"length",
",",
"res",
",",
"maxchars",
")",
":",
"k",
"=",
"0",
"previous_cased",
"=",
"False",
"mapped",
"=",
"np",
".",
"empty",
"(",
"3",
",",
"dtype",
"=",
"_Py_UCS4",
")",
"for",
"idx",
"in",
"range",
"(",
"length",
")",
":",
"mapped",
".",
"fill",
"(",
"0",
")",
"code_point",
"=",
"_get_code_point",
"(",
"data",
",",
"idx",
")",
"if",
"previous_cased",
":",
"n_res",
"=",
"_lower_ucs4",
"(",
"code_point",
",",
"data",
",",
"length",
",",
"idx",
",",
"mapped",
")",
"else",
":",
"n_res",
"=",
"_PyUnicode_ToTitleFull",
"(",
"_Py_UCS4",
"(",
"code_point",
")",
",",
"mapped",
")",
"for",
"m",
"in",
"mapped",
"[",
":",
"n_res",
"]",
":",
"maxchar",
",",
"=",
"maxchars",
"maxchars",
"[",
"0",
"]",
"=",
"max",
"(",
"maxchar",
",",
"m",
")",
"_set_code_point",
"(",
"res",
",",
"k",
",",
"m",
")",
"k",
"+=",
"1",
"previous_cased",
"=",
"_PyUnicode_IsCased",
"(",
"_Py_UCS4",
"(",
"code_point",
")",
")",
"return",
"k"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unicode.py#L2177-L2195 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/_xml.py | python | SyntaxData.GetKeywords | (self) | return [(5, XML_KEYWORDS + u" " + sgml)] | Returns Specified Keywords List | Returns Specified Keywords List | [
"Returns",
"Specified",
"Keywords",
"List"
] | def GetKeywords(self):
"""Returns Specified Keywords List """
sgml = _html.KeywordString(synglob.ID_LANG_SGML)
return [(5, XML_KEYWORDS + u" " + sgml)] | [
"def",
"GetKeywords",
"(",
"self",
")",
":",
"sgml",
"=",
"_html",
".",
"KeywordString",
"(",
"synglob",
".",
"ID_LANG_SGML",
")",
"return",
"[",
"(",
"5",
",",
"XML_KEYWORDS",
"+",
"u\" \"",
"+",
"sgml",
")",
"]"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_xml.py#L48-L51 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/fields.py | python | RequestField._render_parts | (self, header_parts) | return u"; ".join(parts) | Helper function to format and quote a single header.
Useful for single headers that are composed of multiple items. E.g.,
'Content-Disposition' fields.
:param header_parts:
A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
as `k1="v1"; k2="v2"; ...`. | Helper function to format and quote a single header. | [
"Helper",
"function",
"to",
"format",
"and",
"quote",
"a",
"single",
"header",
"."
] | def _render_parts(self, header_parts):
"""
Helper function to format and quote a single header.
Useful for single headers that are composed of multiple items. E.g.,
'Content-Disposition' fields.
:param header_parts:
A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
as `k1="v1"; k2="v2"; ...`.
"""
parts = []
iterable = header_parts
if isinstance(header_parts, dict):
iterable = header_parts.items()
for name, value in iterable:
if value is not None:
parts.append(self._render_part(name, value))
return u"; ".join(parts) | [
"def",
"_render_parts",
"(",
"self",
",",
"header_parts",
")",
":",
"parts",
"=",
"[",
"]",
"iterable",
"=",
"header_parts",
"if",
"isinstance",
"(",
"header_parts",
",",
"dict",
")",
":",
"iterable",
"=",
"header_parts",
".",
"items",
"(",
")",
"for",
"name",
",",
"value",
"in",
"iterable",
":",
"if",
"value",
"is",
"not",
"None",
":",
"parts",
".",
"append",
"(",
"self",
".",
"_render_part",
"(",
"name",
",",
"value",
")",
")",
"return",
"u\"; \"",
".",
"join",
"(",
"parts",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/fields.py#L207-L227 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/resampler/python/ops/resampler_ops.py | python | resampler | (data, warp, name="resampler") | Resamples input data at user defined coordinates.
The resampler currently only supports bilinear interpolation of 2D data.
Args:
data: Tensor of shape `[batch_size, data_height, data_width,
data_num_channels]` containing 2D data that will be resampled.
warp: Tensor of minimum rank 2 containing the coordinates at which
resampling will be performed. Since only bilinear interpolation is
currently supported, the last dimension of the `warp` tensor must be 2,
representing the (x, y) coordinate where x is the index for width and y is
the index for height.
name: Optional name of the op.
Returns:
Tensor of resampled values from `data`. The output tensor shape is
determined by the shape of the warp tensor. For example, if `data` is of
shape `[batch_size, data_height, data_width, data_num_channels]` and warp of
shape `[batch_size, dim_0, ... , dim_n, 2]` the output will be of shape
`[batch_size, dim_0, ... , dim_n, data_num_channels]`.
Raises:
ImportError: if the wrapper generated during compilation is not present when
the function is called. | Resamples input data at user defined coordinates. | [
"Resamples",
"input",
"data",
"at",
"user",
"defined",
"coordinates",
"."
] | def resampler(data, warp, name="resampler"):
"""Resamples input data at user defined coordinates.
The resampler currently only supports bilinear interpolation of 2D data.
Args:
data: Tensor of shape `[batch_size, data_height, data_width,
data_num_channels]` containing 2D data that will be resampled.
warp: Tensor of minimum rank 2 containing the coordinates at which
resampling will be performed. Since only bilinear interpolation is
currently supported, the last dimension of the `warp` tensor must be 2,
representing the (x, y) coordinate where x is the index for width and y is
the index for height.
name: Optional name of the op.
Returns:
Tensor of resampled values from `data`. The output tensor shape is
determined by the shape of the warp tensor. For example, if `data` is of
shape `[batch_size, data_height, data_width, data_num_channels]` and warp of
shape `[batch_size, dim_0, ... , dim_n, 2]` the output will be of shape
`[batch_size, dim_0, ... , dim_n, data_num_channels]`.
Raises:
ImportError: if the wrapper generated during compilation is not present when
the function is called.
"""
with ops.name_scope(name, "resampler", [data, warp]):
data_tensor = ops.convert_to_tensor(data, name="data")
warp_tensor = ops.convert_to_tensor(warp, name="warp")
return gen_resampler_ops.resampler(data_tensor, warp_tensor) | [
"def",
"resampler",
"(",
"data",
",",
"warp",
",",
"name",
"=",
"\"resampler\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"resampler\"",
",",
"[",
"data",
",",
"warp",
"]",
")",
":",
"data_tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"data",
",",
"name",
"=",
"\"data\"",
")",
"warp_tensor",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"warp",
",",
"name",
"=",
"\"warp\"",
")",
"return",
"gen_resampler_ops",
".",
"resampler",
"(",
"data_tensor",
",",
"warp_tensor",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/resampler/python/ops/resampler_ops.py#L32-L61 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/data_flow_ops.py | python | QueueBase.shapes | (self) | return self._shapes | The list of shapes for each component of a queue element. | The list of shapes for each component of a queue element. | [
"The",
"list",
"of",
"shapes",
"for",
"each",
"component",
"of",
"a",
"queue",
"element",
"."
] | def shapes(self):
"""The list of shapes for each component of a queue element."""
return self._shapes | [
"def",
"shapes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_shapes"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/data_flow_ops.py#L219-L221 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/fnmatch.py | python | translate | (pat) | return res + '\Z(?ms)' | Translate a shell PATTERN to a regular expression.
There is no way to quote meta-characters. | Translate a shell PATTERN to a regular expression. | [
"Translate",
"a",
"shell",
"PATTERN",
"to",
"a",
"regular",
"expression",
"."
] | def translate(pat):
"""Translate a shell PATTERN to a regular expression.
There is no way to quote meta-characters.
"""
i, n = 0, len(pat)
res = ''
while i < n:
c = pat[i]
i = i+1
if c == '*':
res = res + '.*'
elif c == '?':
res = res + '.'
elif c == '[':
j = i
if j < n and pat[j] == '!':
j = j+1
if j < n and pat[j] == ']':
j = j+1
while j < n and pat[j] != ']':
j = j+1
if j >= n:
res = res + '\\['
else:
stuff = pat[i:j].replace('\\','\\\\')
i = j+1
if stuff[0] == '!':
stuff = '^' + stuff[1:]
elif stuff[0] == '^':
stuff = '\\' + stuff
res = '%s[%s]' % (res, stuff)
else:
res = res + re.escape(c)
return res + '\Z(?ms)' | [
"def",
"translate",
"(",
"pat",
")",
":",
"i",
",",
"n",
"=",
"0",
",",
"len",
"(",
"pat",
")",
"res",
"=",
"''",
"while",
"i",
"<",
"n",
":",
"c",
"=",
"pat",
"[",
"i",
"]",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
"==",
"'*'",
":",
"res",
"=",
"res",
"+",
"'.*'",
"elif",
"c",
"==",
"'?'",
":",
"res",
"=",
"res",
"+",
"'.'",
"elif",
"c",
"==",
"'['",
":",
"j",
"=",
"i",
"if",
"j",
"<",
"n",
"and",
"pat",
"[",
"j",
"]",
"==",
"'!'",
":",
"j",
"=",
"j",
"+",
"1",
"if",
"j",
"<",
"n",
"and",
"pat",
"[",
"j",
"]",
"==",
"']'",
":",
"j",
"=",
"j",
"+",
"1",
"while",
"j",
"<",
"n",
"and",
"pat",
"[",
"j",
"]",
"!=",
"']'",
":",
"j",
"=",
"j",
"+",
"1",
"if",
"j",
">=",
"n",
":",
"res",
"=",
"res",
"+",
"'\\\\['",
"else",
":",
"stuff",
"=",
"pat",
"[",
"i",
":",
"j",
"]",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
"i",
"=",
"j",
"+",
"1",
"if",
"stuff",
"[",
"0",
"]",
"==",
"'!'",
":",
"stuff",
"=",
"'^'",
"+",
"stuff",
"[",
"1",
":",
"]",
"elif",
"stuff",
"[",
"0",
"]",
"==",
"'^'",
":",
"stuff",
"=",
"'\\\\'",
"+",
"stuff",
"res",
"=",
"'%s[%s]'",
"%",
"(",
"res",
",",
"stuff",
")",
"else",
":",
"res",
"=",
"res",
"+",
"re",
".",
"escape",
"(",
"c",
")",
"return",
"res",
"+",
"'\\Z(?ms)'"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/fnmatch.py#L81-L116 | |
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | CT Liver Segmentation Software/metrics.py | python | sensitivity | (result, reference) | return recall(result, reference) | Sensitivity.
Same as :func:`recall`, see there for a detailed description.
See also
--------
:func:`specificity` | Sensitivity.
Same as :func:`recall`, see there for a detailed description. | [
"Sensitivity",
".",
"Same",
"as",
":",
"func",
":",
"recall",
"see",
"there",
"for",
"a",
"detailed",
"description",
"."
] | def sensitivity(result, reference):
"""
Sensitivity.
Same as :func:`recall`, see there for a detailed description.
See also
--------
:func:`specificity`
"""
return recall(result, reference) | [
"def",
"sensitivity",
"(",
"result",
",",
"reference",
")",
":",
"return",
"recall",
"(",
"result",
",",
"reference",
")"
] | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/CT Liver Segmentation Software/metrics.py#L212-L221 | |
h2oai/datatable | 753197c3f76041dd6468e0f6a9708af92d80f6aa | ci/xbuild/extension.py | python | Extension.nworkers | (self) | return self._nworkers | The number of worker processes to use for compiling the
source files. Defaults to the 80% of the number of cores. | The number of worker processes to use for compiling the
source files. Defaults to the 80% of the number of cores. | [
"The",
"number",
"of",
"worker",
"processes",
"to",
"use",
"for",
"compiling",
"the",
"source",
"files",
".",
"Defaults",
"to",
"the",
"80%",
"of",
"the",
"number",
"of",
"cores",
"."
] | def nworkers(self):
"""
The number of worker processes to use for compiling the
source files. Defaults to the 80% of the number of cores.
"""
if self._nworkers is None:
self.nworkers = "auto"
return self._nworkers | [
"def",
"nworkers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_nworkers",
"is",
"None",
":",
"self",
".",
"nworkers",
"=",
"\"auto\"",
"return",
"self",
".",
"_nworkers"
] | https://github.com/h2oai/datatable/blob/753197c3f76041dd6468e0f6a9708af92d80f6aa/ci/xbuild/extension.py#L287-L294 | |
makerbase-mks/MKS-SBASE | 76c9f4b2391f3d48c17f5fb066a2cbe0895b9f1b | Firmware/Marlin-bugfix-2.0.x/buildroot/share/scripts/createTemperatureLookupMarlin.py | python | main | (argv) | Default values | Default values | [
"Default",
"values"
] | def main(argv):
"Default values"
t1 = 25 # low temperature in Kelvin (25 degC)
r1 = 100000 # resistance at low temperature (10 kOhm)
t2 = 150 # middle temperature in Kelvin (150 degC)
r2 = 1641.9 # resistance at middle temperature (1.6 KOhm)
t3 = 250 # high temperature in Kelvin (250 degC)
r3 = 226.15 # resistance at high temperature (226.15 Ohm)
rp = 4700; # pull-up resistor (4.7 kOhm)
num_temps = 36; # number of entries for look-up table
try:
opts, args = getopt.getopt(argv, "h", ["help", "rp=", "t1=", "t2=", "t3=", "num-temps="])
except getopt.GetoptError as err:
print(str(err))
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt == "--rp":
rp = int(arg)
elif opt == "--t1":
arg = arg.split(':')
t1 = float(arg[0])
r1 = float(arg[1])
elif opt == "--t2":
arg = arg.split(':')
t2 = float(arg[0])
r2 = float(arg[1])
elif opt == "--t3":
arg = arg.split(':')
t3 = float(arg[0])
r3 = float(arg[1])
elif opt == "--num-temps":
num_temps = int(arg)
t = Thermistor(rp, t1, r1, t2, r2, t3, r3)
increment = int((ARES-1)/(num_temps-1));
step = (TMIN-TMAX) / (num_temps-1)
low_bound = t.temp(ARES-1);
up_bound = t.temp(1);
min_temp = int(TMIN if TMIN > low_bound else low_bound)
max_temp = int(TMAX if TMAX < up_bound else up_bound)
temps = list(range(max_temp, TMIN+step, step));
print("// Thermistor lookup table for Marlin")
print("// ./createTemperatureLookupMarlin.py --rp=%s --t1=%s:%s --t2=%s:%s --t3=%s:%s --num-temps=%s" % (rp, t1, r1, t2, r2, t3, r3, num_temps))
print("// Steinhart-Hart Coefficients: a=%.15g, b=%.15g, c=%.15g " % (t.c1, t.c2, t.c3))
print("// Theoretical limits of thermistor: %.2f to %.2f degC" % (low_bound, up_bound))
print()
print("const short temptable[][2] PROGMEM = {")
for temp in temps:
adc = t.adc(temp)
print(" { OV(%7.2f), %4s }%s // v=%.3f\tr=%.3f\tres=%.3f degC/count" % (adc , temp, \
',' if temp != temps[-1] else ' ', \
t.voltage(adc), \
t.resist( adc), \
t.resol( adc) \
))
print("};") | [
"def",
"main",
"(",
"argv",
")",
":",
"t1",
"=",
"25",
"# low temperature in Kelvin (25 degC)",
"r1",
"=",
"100000",
"# resistance at low temperature (10 kOhm)",
"t2",
"=",
"150",
"# middle temperature in Kelvin (150 degC)",
"r2",
"=",
"1641.9",
"# resistance at middle temperature (1.6 KOhm)",
"t3",
"=",
"250",
"# high temperature in Kelvin (250 degC)",
"r3",
"=",
"226.15",
"# resistance at high temperature (226.15 Ohm)",
"rp",
"=",
"4700",
"# pull-up resistor (4.7 kOhm)",
"num_temps",
"=",
"36",
"# number of entries for look-up table",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"argv",
",",
"\"h\"",
",",
"[",
"\"help\"",
",",
"\"rp=\"",
",",
"\"t1=\"",
",",
"\"t2=\"",
",",
"\"t3=\"",
",",
"\"num-temps=\"",
"]",
")",
"except",
"getopt",
".",
"GetoptError",
"as",
"err",
":",
"print",
"(",
"str",
"(",
"err",
")",
")",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"for",
"opt",
",",
"arg",
"in",
"opts",
":",
"if",
"opt",
"in",
"(",
"\"-h\"",
",",
"\"--help\"",
")",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
")",
"elif",
"opt",
"==",
"\"--rp\"",
":",
"rp",
"=",
"int",
"(",
"arg",
")",
"elif",
"opt",
"==",
"\"--t1\"",
":",
"arg",
"=",
"arg",
".",
"split",
"(",
"':'",
")",
"t1",
"=",
"float",
"(",
"arg",
"[",
"0",
"]",
")",
"r1",
"=",
"float",
"(",
"arg",
"[",
"1",
"]",
")",
"elif",
"opt",
"==",
"\"--t2\"",
":",
"arg",
"=",
"arg",
".",
"split",
"(",
"':'",
")",
"t2",
"=",
"float",
"(",
"arg",
"[",
"0",
"]",
")",
"r2",
"=",
"float",
"(",
"arg",
"[",
"1",
"]",
")",
"elif",
"opt",
"==",
"\"--t3\"",
":",
"arg",
"=",
"arg",
".",
"split",
"(",
"':'",
")",
"t3",
"=",
"float",
"(",
"arg",
"[",
"0",
"]",
")",
"r3",
"=",
"float",
"(",
"arg",
"[",
"1",
"]",
")",
"elif",
"opt",
"==",
"\"--num-temps\"",
":",
"num_temps",
"=",
"int",
"(",
"arg",
")",
"t",
"=",
"Thermistor",
"(",
"rp",
",",
"t1",
",",
"r1",
",",
"t2",
",",
"r2",
",",
"t3",
",",
"r3",
")",
"increment",
"=",
"int",
"(",
"(",
"ARES",
"-",
"1",
")",
"/",
"(",
"num_temps",
"-",
"1",
")",
")",
"step",
"=",
"(",
"TMIN",
"-",
"TMAX",
")",
"/",
"(",
"num_temps",
"-",
"1",
")",
"low_bound",
"=",
"t",
".",
"temp",
"(",
"ARES",
"-",
"1",
")",
"up_bound",
"=",
"t",
".",
"temp",
"(",
"1",
")",
"min_temp",
"=",
"int",
"(",
"TMIN",
"if",
"TMIN",
">",
"low_bound",
"else",
"low_bound",
")",
"max_temp",
"=",
"int",
"(",
"TMAX",
"if",
"TMAX",
"<",
"up_bound",
"else",
"up_bound",
")",
"temps",
"=",
"list",
"(",
"range",
"(",
"max_temp",
",",
"TMIN",
"+",
"step",
",",
"step",
")",
")",
"print",
"(",
"\"// Thermistor lookup table for Marlin\"",
")",
"print",
"(",
"\"// ./createTemperatureLookupMarlin.py --rp=%s --t1=%s:%s --t2=%s:%s --t3=%s:%s --num-temps=%s\"",
"%",
"(",
"rp",
",",
"t1",
",",
"r1",
",",
"t2",
",",
"r2",
",",
"t3",
",",
"r3",
",",
"num_temps",
")",
")",
"print",
"(",
"\"// Steinhart-Hart Coefficients: a=%.15g, b=%.15g, c=%.15g \"",
"%",
"(",
"t",
".",
"c1",
",",
"t",
".",
"c2",
",",
"t",
".",
"c3",
")",
")",
"print",
"(",
"\"// Theoretical limits of thermistor: %.2f to %.2f degC\"",
"%",
"(",
"low_bound",
",",
"up_bound",
")",
")",
"print",
"(",
")",
"print",
"(",
"\"const short temptable[][2] PROGMEM = {\"",
")",
"for",
"temp",
"in",
"temps",
":",
"adc",
"=",
"t",
".",
"adc",
"(",
"temp",
")",
"print",
"(",
"\" { OV(%7.2f), %4s }%s // v=%.3f\\tr=%.3f\\tres=%.3f degC/count\"",
"%",
"(",
"adc",
",",
"temp",
",",
"','",
"if",
"temp",
"!=",
"temps",
"[",
"-",
"1",
"]",
"else",
"' '",
",",
"t",
".",
"voltage",
"(",
"adc",
")",
",",
"t",
".",
"resist",
"(",
"adc",
")",
",",
"t",
".",
"resol",
"(",
"adc",
")",
")",
")",
"print",
"(",
"\"};\"",
")"
] | https://github.com/makerbase-mks/MKS-SBASE/blob/76c9f4b2391f3d48c17f5fb066a2cbe0895b9f1b/Firmware/Marlin-bugfix-2.0.x/buildroot/share/scripts/createTemperatureLookupMarlin.py#L89-L152 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/isolate/trace_inputs.py | python | extract_directories | (files, root) | return sorted(files) | Detects if all the files in a directory were loaded and if so, replace the
individual files by the directory entry. | Detects if all the files in a directory were loaded and if so, replace the
individual files by the directory entry. | [
"Detects",
"if",
"all",
"the",
"files",
"in",
"a",
"directory",
"were",
"loaded",
"and",
"if",
"so",
"replace",
"the",
"individual",
"files",
"by",
"the",
"directory",
"entry",
"."
] | def extract_directories(files, root):
"""Detects if all the files in a directory were loaded and if so, replace the
individual files by the directory entry.
"""
directories = set(os.path.dirname(f) for f in files)
files = set(files)
for directory in sorted(directories, reverse=True):
actual = set(
os.path.join(directory, f) for f in
os.listdir(os.path.join(root, directory))
if not f.endswith(('.svn', '.pyc'))
)
if not (actual - files):
files -= actual
files.add(directory + os.path.sep)
return sorted(files) | [
"def",
"extract_directories",
"(",
"files",
",",
"root",
")",
":",
"directories",
"=",
"set",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"f",
")",
"for",
"f",
"in",
"files",
")",
"files",
"=",
"set",
"(",
"files",
")",
"for",
"directory",
"in",
"sorted",
"(",
"directories",
",",
"reverse",
"=",
"True",
")",
":",
"actual",
"=",
"set",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"f",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"directory",
")",
")",
"if",
"not",
"f",
".",
"endswith",
"(",
"(",
"'.svn'",
",",
"'.pyc'",
")",
")",
")",
"if",
"not",
"(",
"actual",
"-",
"files",
")",
":",
"files",
"-=",
"actual",
"files",
".",
"add",
"(",
"directory",
"+",
"os",
".",
"path",
".",
"sep",
")",
"return",
"sorted",
"(",
"files",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/isolate/trace_inputs.py#L1168-L1183 | |
WeitaoVan/L-GM-loss | 598582f0631bac876b3eeb8d6c4cd1d780269e03 | python/caffe/net_spec.py | python | to_proto | (*tops) | return net | Generate a NetParameter that contains all layers needed to compute
all arguments. | Generate a NetParameter that contains all layers needed to compute
all arguments. | [
"Generate",
"a",
"NetParameter",
"that",
"contains",
"all",
"layers",
"needed",
"to",
"compute",
"all",
"arguments",
"."
] | def to_proto(*tops):
"""Generate a NetParameter that contains all layers needed to compute
all arguments."""
layers = OrderedDict()
autonames = Counter()
for top in tops:
top.fn._to_proto(layers, {}, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net | [
"def",
"to_proto",
"(",
"*",
"tops",
")",
":",
"layers",
"=",
"OrderedDict",
"(",
")",
"autonames",
"=",
"Counter",
"(",
")",
"for",
"top",
"in",
"tops",
":",
"top",
".",
"fn",
".",
"_to_proto",
"(",
"layers",
",",
"{",
"}",
",",
"autonames",
")",
"net",
"=",
"caffe_pb2",
".",
"NetParameter",
"(",
")",
"net",
".",
"layer",
".",
"extend",
"(",
"layers",
".",
"values",
"(",
")",
")",
"return",
"net"
] | https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/python/caffe/net_spec.py#L43-L53 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | clang/bindings/python/clang/cindex.py | python | Type.is_const_qualified | (self) | return conf.lib.clang_isConstQualifiedType(self) | Determine whether a Type has the "const" qualifier set.
This does not look through typedefs that may have added "const"
at a different level. | Determine whether a Type has the "const" qualifier set. | [
"Determine",
"whether",
"a",
"Type",
"has",
"the",
"const",
"qualifier",
"set",
"."
] | def is_const_qualified(self):
"""Determine whether a Type has the "const" qualifier set.
This does not look through typedefs that may have added "const"
at a different level.
"""
return conf.lib.clang_isConstQualifiedType(self) | [
"def",
"is_const_qualified",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isConstQualifiedType",
"(",
"self",
")"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/bindings/python/clang/cindex.py#L2297-L2303 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Position.__eq__ | (*args, **kwargs) | return _core_.Position___eq__(*args, **kwargs) | __eq__(self, PyObject other) -> bool
Test for equality of wx.Position objects. | __eq__(self, PyObject other) -> bool | [
"__eq__",
"(",
"self",
"PyObject",
"other",
")",
"-",
">",
"bool"
] | def __eq__(*args, **kwargs):
"""
__eq__(self, PyObject other) -> bool
Test for equality of wx.Position objects.
"""
return _core_.Position___eq__(*args, **kwargs) | [
"def",
"__eq__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Position___eq__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L2110-L2116 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/shuffler.py | python | _merge_map | (key, values, partial) | A map function used in merge phase.
Stores (key, values) into KeyValues proto and yields its serialization.
Args:
key: values key.
values: values themselves.
partial: True if more values for this key will follow. False otherwise.
Yields:
The proto. | A map function used in merge phase. | [
"A",
"map",
"function",
"used",
"in",
"merge",
"phase",
"."
] | def _merge_map(key, values, partial):
"""A map function used in merge phase.
Stores (key, values) into KeyValues proto and yields its serialization.
Args:
key: values key.
values: values themselves.
partial: True if more values for this key will follow. False otherwise.
Yields:
The proto.
"""
proto = kv_pb.KeyValues()
proto.set_key(key)
proto.value_list().extend(values)
yield proto.Encode() | [
"def",
"_merge_map",
"(",
"key",
",",
"values",
",",
"partial",
")",
":",
"proto",
"=",
"kv_pb",
".",
"KeyValues",
"(",
")",
"proto",
".",
"set_key",
"(",
"key",
")",
"proto",
".",
"value_list",
"(",
")",
".",
"extend",
"(",
"values",
")",
"yield",
"proto",
".",
"Encode",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/shuffler.py#L561-L577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.