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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lemenkov/libyuv | 5b3351bd07e83f9f9a4cb6629561331ecdb7c546 | tools_libyuv/autoroller/roll_deps.py | python | ReadRemoteCrFile | (path_below_src, revision) | return _ReadGitilesContent(CHROMIUM_FILE_TEMPLATE % (revision,
path_below_src)) | Reads a remote Chromium file of a specific revision. Returns a string. | Reads a remote Chromium file of a specific revision. Returns a string. | [
"Reads",
"a",
"remote",
"Chromium",
"file",
"of",
"a",
"specific",
"revision",
".",
"Returns",
"a",
"string",
"."
] | def ReadRemoteCrFile(path_below_src, revision):
"""Reads a remote Chromium file of a specific revision. Returns a string."""
return _ReadGitilesContent(CHROMIUM_FILE_TEMPLATE % (revision,
path_below_src)) | [
"def",
"ReadRemoteCrFile",
"(",
"path_below_src",
",",
"revision",
")",
":",
"return",
"_ReadGitilesContent",
"(",
"CHROMIUM_FILE_TEMPLATE",
"%",
"(",
"revision",
",",
"path_below_src",
")",
")"
] | https://github.com/lemenkov/libyuv/blob/5b3351bd07e83f9f9a4cb6629561331ecdb7c546/tools_libyuv/autoroller/roll_deps.py#L160-L163 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/oracle/connector.py | python | OracleDBConnector.deleteTableIndex | (self, table, name) | Deletes an index on a table. | Deletes an index on a table. | [
"Deletes",
"an",
"index",
"on",
"a",
"table",
"."
] | def deleteTableIndex(self, table, name):
"""Deletes an index on a table."""
schema, tablename = self.getSchemaTableName(table)
sql = u"DROP INDEX {}".format(self.quoteId((schema, name)))
self._execute_and_commit(sql) | [
"def",
"deleteTableIndex",
"(",
"self",
",",
"table",
",",
"name",
")",
":",
"schema",
",",
"tablename",
"=",
"self",
".",
"getSchemaTableName",
"(",
"table",
")",
"sql",
"=",
"u\"DROP INDEX {}\"",
".",
"format",
"(",
"self",
".",
"quoteId",
"(",
"(",
"schema",
",",
"name",
")",
")",
")",
"self",
".",
"_execute_and_commit",
"(",
"sql",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/oracle/connector.py#L1603-L1607 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/__init__.py | python | get_parser_class | (parser_name) | return module.Parser | Return the Parser class from the `parser_name` module. | Return the Parser class from the `parser_name` module. | [
"Return",
"the",
"Parser",
"class",
"from",
"the",
"parser_name",
"module",
"."
] | def get_parser_class(parser_name):
"""Return the Parser class from the `parser_name` module."""
parser_name = parser_name.lower()
if parser_name in _parser_aliases:
parser_name = _parser_aliases[parser_name]
try:
module = __import__(parser_name, globals(), locals(), level=1)
except ImportError:
module = __import__(parser_name, globals(), locals(), level=0)
return module.Parser | [
"def",
"get_parser_class",
"(",
"parser_name",
")",
":",
"parser_name",
"=",
"parser_name",
".",
"lower",
"(",
")",
"if",
"parser_name",
"in",
"_parser_aliases",
":",
"parser_name",
"=",
"_parser_aliases",
"[",
"parser_name",
"]",
"try",
":",
"module",
"=",
"__import__",
"(",
"parser_name",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
",",
"level",
"=",
"1",
")",
"except",
"ImportError",
":",
"module",
"=",
"__import__",
"(",
"parser_name",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
",",
"level",
"=",
"0",
")",
"return",
"module",
".",
"Parser"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/__init__.py#L44-L53 | |
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/google/protobuf/reflection.py | python | _ExtensionDict._SubmessageByteSizeBecameDirty | (self) | Called whenever a submessage's cached byte size becomes invalid
(goes from being "clean" to being "dirty"). Called by _ExtensionListener. | Called whenever a submessage's cached byte size becomes invalid
(goes from being "clean" to being "dirty"). Called by _ExtensionListener. | [
"Called",
"whenever",
"a",
"submessage",
"s",
"cached",
"byte",
"size",
"becomes",
"invalid",
"(",
"goes",
"from",
"being",
"clean",
"to",
"being",
"dirty",
")",
".",
"Called",
"by",
"_ExtensionListener",
"."
] | def _SubmessageByteSizeBecameDirty(self):
"""Called whenever a submessage's cached byte size becomes invalid
(goes from being "clean" to being "dirty"). Called by _ExtensionListener.
"""
self._extended_message._MarkByteSizeDirty() | [
"def",
"_SubmessageByteSizeBecameDirty",
"(",
"self",
")",
":",
"self",
".",
"_extended_message",
".",
"_MarkByteSizeDirty",
"(",
")"
] | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/reflection.py#L1571-L1575 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextPrinting.PrintFile | (*args, **kwargs) | return _richtext.RichTextPrinting_PrintFile(*args, **kwargs) | PrintFile(self, String richTextFile) -> bool | PrintFile(self, String richTextFile) -> bool | [
"PrintFile",
"(",
"self",
"String",
"richTextFile",
")",
"-",
">",
"bool"
] | def PrintFile(*args, **kwargs):
"""PrintFile(self, String richTextFile) -> bool"""
return _richtext.RichTextPrinting_PrintFile(*args, **kwargs) | [
"def",
"PrintFile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextPrinting_PrintFile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L4500-L4502 | |
openweave/openweave-core | 11ceb6b7efd39fe05de7f79229247a5774d56766 | src/device-manager/python/openweave/WeaveCoreBluetoothMgr.py | python | CoreBluetoothManager.scan | (self, line) | API to initiatae BLE scanning for -t user_timeout seconds. | API to initiatae BLE scanning for -t user_timeout seconds. | [
"API",
"to",
"initiatae",
"BLE",
"scanning",
"for",
"-",
"t",
"user_timeout",
"seconds",
"."
] | def scan(self, line):
""" API to initiatae BLE scanning for -t user_timeout seconds."""
args = self.ParseInputLine(line, "scan")
if not args:
return
self.scan_quiet = args[1]
self.bg_peripheral_name = None
del self.peripheral_list[:]
self.peripheral_list = []
# Filter on the service UUID Array or None to accept all scan results.
self.manager.scanForPeripheralsWithServices_options_([weave_service_short, weave_service, chromecast_setup_service_short, chromecast_setup_service], None)
#self.manager.scanForPeripheralsWithServices_options_(None, None)
self.runLoopUntil(("scan", time.time(), args[0], args[2]))
self.manager.stopScan()
self.logger.info("scanning stopped") | [
"def",
"scan",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"ParseInputLine",
"(",
"line",
",",
"\"scan\"",
")",
"if",
"not",
"args",
":",
"return",
"self",
".",
"scan_quiet",
"=",
"args",
"[",
"1",
"]",
"self",
".",
"bg_peripheral_name",
"=",
"None",
"del",
"self",
".",
"peripheral_list",
"[",
":",
"]",
"self",
".",
"peripheral_list",
"=",
"[",
"]",
"# Filter on the service UUID Array or None to accept all scan results.",
"self",
".",
"manager",
".",
"scanForPeripheralsWithServices_options_",
"(",
"[",
"weave_service_short",
",",
"weave_service",
",",
"chromecast_setup_service_short",
",",
"chromecast_setup_service",
"]",
",",
"None",
")",
"#self.manager.scanForPeripheralsWithServices_options_(None, None)",
"self",
".",
"runLoopUntil",
"(",
"(",
"\"scan\"",
",",
"time",
".",
"time",
"(",
")",
",",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"2",
"]",
")",
")",
"self",
".",
"manager",
".",
"stopScan",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"scanning stopped\"",
")"
] | https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/openweave/WeaveCoreBluetoothMgr.py#L381-L399 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/utils.py | python | parse_dict_header | (value) | return result | Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict` | Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict: | [
"Parse",
"lists",
"of",
"key",
"value",
"pairs",
"as",
"described",
"by",
"RFC",
"2068",
"Section",
"2",
"and",
"convert",
"them",
"into",
"a",
"python",
"dict",
":"
] | def parse_dict_header(value):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict`
"""
result = {}
for item in _parse_list_header(value):
if '=' not in item:
result[item] = None
continue
name, value = item.split('=', 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result | [
"def",
"parse_dict_header",
"(",
"value",
")",
":",
"result",
"=",
"{",
"}",
"for",
"item",
"in",
"_parse_list_header",
"(",
"value",
")",
":",
"if",
"'='",
"not",
"in",
"item",
":",
"result",
"[",
"item",
"]",
"=",
"None",
"continue",
"name",
",",
"value",
"=",
"item",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"value",
"[",
":",
"1",
"]",
"==",
"value",
"[",
"-",
"1",
":",
"]",
"==",
"'\"'",
":",
"value",
"=",
"unquote_header_value",
"(",
"value",
"[",
"1",
":",
"-",
"1",
"]",
")",
"result",
"[",
"name",
"]",
"=",
"value",
"return",
"result"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/utils.py#L202-L232 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py | python | _check_multiple_of | (value, multiple_of) | Checks that value `value` is a non-zero multiple of `multiple_of`.
Args:
value: an int32 scalar Tensor.
multiple_of: an int or int32 scalar Tensor.
Returns:
new_value: an int32 scalar Tensor matching `value`, but which includes an
assertion that `value` is a multiple of `multiple_of`. | Checks that value `value` is a non-zero multiple of `multiple_of`. | [
"Checks",
"that",
"value",
"value",
"is",
"a",
"non",
"-",
"zero",
"multiple",
"of",
"multiple_of",
"."
] | def _check_multiple_of(value, multiple_of):
"""Checks that value `value` is a non-zero multiple of `multiple_of`.
Args:
value: an int32 scalar Tensor.
multiple_of: an int or int32 scalar Tensor.
Returns:
new_value: an int32 scalar Tensor matching `value`, but which includes an
assertion that `value` is a multiple of `multiple_of`.
"""
assert isinstance(value, ops.Tensor)
with ops.control_dependencies([
control_flow_ops.Assert(
math_ops.logical_and(
math_ops.equal(math_ops.mod(value, multiple_of), 0),
math_ops.not_equal(value, 0)), [
string_ops.string_join([
"Tensor %s should be a multiple of: " % value.name,
string_ops.as_string(multiple_of), ", but saw value: ",
string_ops.as_string(value),
". Consider setting pad=True."
])
])
]):
new_value = array_ops.identity(value, name="multiple_of_checked")
return new_value | [
"def",
"_check_multiple_of",
"(",
"value",
",",
"multiple_of",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"ops",
".",
"Tensor",
")",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"control_flow_ops",
".",
"Assert",
"(",
"math_ops",
".",
"logical_and",
"(",
"math_ops",
".",
"equal",
"(",
"math_ops",
".",
"mod",
"(",
"value",
",",
"multiple_of",
")",
",",
"0",
")",
",",
"math_ops",
".",
"not_equal",
"(",
"value",
",",
"0",
")",
")",
",",
"[",
"string_ops",
".",
"string_join",
"(",
"[",
"\"Tensor %s should be a multiple of: \"",
"%",
"value",
".",
"name",
",",
"string_ops",
".",
"as_string",
"(",
"multiple_of",
")",
",",
"\", but saw value: \"",
",",
"string_ops",
".",
"as_string",
"(",
"value",
")",
",",
"\". Consider setting pad=True.\"",
"]",
")",
"]",
")",
"]",
")",
":",
"new_value",
"=",
"array_ops",
".",
"identity",
"(",
"value",
",",
"name",
"=",
"\"multiple_of_checked\"",
")",
"return",
"new_value"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L110-L136 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/summary/impl/reservoir.py | python | Reservoir.FilterItems | (self, filterFn, key=None) | Filter items within a Reservoir, using a filtering function.
Args:
filterFn: A function that returns True for the items to be kept.
key: An optional bucket key to filter. If not specified, will filter all
all buckets.
Returns:
The number of items removed. | Filter items within a Reservoir, using a filtering function. | [
"Filter",
"items",
"within",
"a",
"Reservoir",
"using",
"a",
"filtering",
"function",
"."
] | def FilterItems(self, filterFn, key=None):
"""Filter items within a Reservoir, using a filtering function.
Args:
filterFn: A function that returns True for the items to be kept.
key: An optional bucket key to filter. If not specified, will filter all
all buckets.
Returns:
The number of items removed.
"""
with self._mutex:
if key:
if key in self._buckets:
return self._buckets[key].FilterItems(filterFn)
else:
return 0
else:
return sum(bucket.FilterItems(filterFn)
for bucket in self._buckets.values()) | [
"def",
"FilterItems",
"(",
"self",
",",
"filterFn",
",",
"key",
"=",
"None",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"key",
":",
"if",
"key",
"in",
"self",
".",
"_buckets",
":",
"return",
"self",
".",
"_buckets",
"[",
"key",
"]",
".",
"FilterItems",
"(",
"filterFn",
")",
"else",
":",
"return",
"0",
"else",
":",
"return",
"sum",
"(",
"bucket",
".",
"FilterItems",
"(",
"filterFn",
")",
"for",
"bucket",
"in",
"self",
".",
"_buckets",
".",
"values",
"(",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/summary/impl/reservoir.py#L120-L139 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewTreeCtrl.InsertItem | (*args, **kwargs) | return _dataview.DataViewTreeCtrl_InsertItem(*args, **kwargs) | InsertItem(self, DataViewItem parent, DataViewItem previous, String text,
int icon=-1, wxClientData data=None) -> DataViewItem | InsertItem(self, DataViewItem parent, DataViewItem previous, String text,
int icon=-1, wxClientData data=None) -> DataViewItem | [
"InsertItem",
"(",
"self",
"DataViewItem",
"parent",
"DataViewItem",
"previous",
"String",
"text",
"int",
"icon",
"=",
"-",
"1",
"wxClientData",
"data",
"=",
"None",
")",
"-",
">",
"DataViewItem"
] | def InsertItem(*args, **kwargs):
"""
InsertItem(self, DataViewItem parent, DataViewItem previous, String text,
int icon=-1, wxClientData data=None) -> DataViewItem
"""
return _dataview.DataViewTreeCtrl_InsertItem(*args, **kwargs) | [
"def",
"InsertItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewTreeCtrl_InsertItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L2497-L2502 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/buttonpanel.py | python | ButtonPanel.RepaintOldSelection | (self) | Repaints the old selected/hovered button. | Repaints the old selected/hovered button. | [
"Repaints",
"the",
"old",
"selected",
"/",
"hovered",
"button",
"."
] | def RepaintOldSelection(self):
""" Repaints the old selected/hovered button. """
current = self._currentButton
if current == -1:
return
btn = self._vButtons[current]
if not btn.IsEnabled():
return
btn.SetStatus("Normal") | [
"def",
"RepaintOldSelection",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"_currentButton",
"if",
"current",
"==",
"-",
"1",
":",
"return",
"btn",
"=",
"self",
".",
"_vButtons",
"[",
"current",
"]",
"if",
"not",
"btn",
".",
"IsEnabled",
"(",
")",
":",
"return",
"btn",
".",
"SetStatus",
"(",
"\"Normal\"",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L2653-L2665 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/distutils/exec_command.py | python | _exec_command | (command, use_shell=None, use_tee = None, **env) | return proc.returncode, text | Internal workhorse for exec_command(). | Internal workhorse for exec_command(). | [
"Internal",
"workhorse",
"for",
"exec_command",
"()",
"."
] | def _exec_command(command, use_shell=None, use_tee = None, **env):
"""
Internal workhorse for exec_command().
"""
if use_shell is None:
use_shell = os.name=='posix'
if use_tee is None:
use_tee = os.name=='posix'
if os.name == 'posix' and use_shell:
# On POSIX, subprocess always uses /bin/sh, override
sh = os.environ.get('SHELL', '/bin/sh')
if is_sequence(command):
command = [sh, '-c', ' '.join(command)]
else:
command = [sh, '-c', command]
use_shell = False
elif os.name == 'nt' and is_sequence(command):
# On Windows, join the string for CreateProcess() ourselves as
# subprocess does it a bit differently
command = ' '.join(_quote_arg(arg) for arg in command)
# Inherit environment by default
env = env or None
try:
# universal_newlines is set to False so that communicate()
# will return bytes. We need to decode the output ourselves
# so that Python will not raise a UnicodeDecodeError when
# it encounters an invalid character; rather, we simply replace it
proc = subprocess.Popen(command, shell=use_shell, env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=False)
except EnvironmentError:
# Return 127, as os.spawn*() and /bin/sh do
return 127, ''
text, err = proc.communicate()
mylocale = locale.getpreferredencoding(False)
if mylocale is None:
mylocale = 'ascii'
text = text.decode(mylocale, errors='replace')
text = text.replace('\r\n', '\n')
# Another historical oddity
if text[-1:] == '\n':
text = text[:-1]
if use_tee and text:
print(text)
return proc.returncode, text | [
"def",
"_exec_command",
"(",
"command",
",",
"use_shell",
"=",
"None",
",",
"use_tee",
"=",
"None",
",",
"*",
"*",
"env",
")",
":",
"if",
"use_shell",
"is",
"None",
":",
"use_shell",
"=",
"os",
".",
"name",
"==",
"'posix'",
"if",
"use_tee",
"is",
"None",
":",
"use_tee",
"=",
"os",
".",
"name",
"==",
"'posix'",
"if",
"os",
".",
"name",
"==",
"'posix'",
"and",
"use_shell",
":",
"# On POSIX, subprocess always uses /bin/sh, override",
"sh",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SHELL'",
",",
"'/bin/sh'",
")",
"if",
"is_sequence",
"(",
"command",
")",
":",
"command",
"=",
"[",
"sh",
",",
"'-c'",
",",
"' '",
".",
"join",
"(",
"command",
")",
"]",
"else",
":",
"command",
"=",
"[",
"sh",
",",
"'-c'",
",",
"command",
"]",
"use_shell",
"=",
"False",
"elif",
"os",
".",
"name",
"==",
"'nt'",
"and",
"is_sequence",
"(",
"command",
")",
":",
"# On Windows, join the string for CreateProcess() ourselves as",
"# subprocess does it a bit differently",
"command",
"=",
"' '",
".",
"join",
"(",
"_quote_arg",
"(",
"arg",
")",
"for",
"arg",
"in",
"command",
")",
"# Inherit environment by default",
"env",
"=",
"env",
"or",
"None",
"try",
":",
"# universal_newlines is set to False so that communicate()",
"# will return bytes. We need to decode the output ourselves",
"# so that Python will not raise a UnicodeDecodeError when",
"# it encounters an invalid character; rather, we simply replace it",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"shell",
"=",
"use_shell",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"universal_newlines",
"=",
"False",
")",
"except",
"EnvironmentError",
":",
"# Return 127, as os.spawn*() and /bin/sh do",
"return",
"127",
",",
"''",
"text",
",",
"err",
"=",
"proc",
".",
"communicate",
"(",
")",
"mylocale",
"=",
"locale",
".",
"getpreferredencoding",
"(",
"False",
")",
"if",
"mylocale",
"is",
"None",
":",
"mylocale",
"=",
"'ascii'",
"text",
"=",
"text",
".",
"decode",
"(",
"mylocale",
",",
"errors",
"=",
"'replace'",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
"# Another historical oddity",
"if",
"text",
"[",
"-",
"1",
":",
"]",
"==",
"'\\n'",
":",
"text",
"=",
"text",
"[",
":",
"-",
"1",
"]",
"if",
"use_tee",
"and",
"text",
":",
"print",
"(",
"text",
")",
"return",
"proc",
".",
"returncode",
",",
"text"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/exec_command.py#L253-L303 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.AutoCompGetDropRestOfWord | (*args, **kwargs) | return _stc.StyledTextCtrl_AutoCompGetDropRestOfWord(*args, **kwargs) | AutoCompGetDropRestOfWord(self) -> bool
Retrieve whether or not autocompletion deletes any word characters
after the inserted text upon completion. | AutoCompGetDropRestOfWord(self) -> bool | [
"AutoCompGetDropRestOfWord",
"(",
"self",
")",
"-",
">",
"bool"
] | def AutoCompGetDropRestOfWord(*args, **kwargs):
"""
AutoCompGetDropRestOfWord(self) -> bool
Retrieve whether or not autocompletion deletes any word characters
after the inserted text upon completion.
"""
return _stc.StyledTextCtrl_AutoCompGetDropRestOfWord(*args, **kwargs) | [
"def",
"AutoCompGetDropRestOfWord",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_AutoCompGetDropRestOfWord",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L3194-L3201 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_theme.py | python | BitmapProvider.__GetCurrentProvider | (self) | return None | Gets the provider of the current theme resources
@return: ThemeI object | Gets the provider of the current theme resources
@return: ThemeI object | [
"Gets",
"the",
"provider",
"of",
"the",
"current",
"theme",
"resources",
"@return",
":",
"ThemeI",
"object"
] | def __GetCurrentProvider(self):
"""Gets the provider of the current theme resources
@return: ThemeI object
"""
theme = Profile_Get('ICONS', 'str', u'')
for prov in self.observers:
if theme == prov.GetName():
return prov
# Case if a theme was deleted while it was the active theme
if theme.lower() != u'default':
Profile_Set('ICONS', u'Default')
return None | [
"def",
"__GetCurrentProvider",
"(",
"self",
")",
":",
"theme",
"=",
"Profile_Get",
"(",
"'ICONS'",
",",
"'str'",
",",
"u''",
")",
"for",
"prov",
"in",
"self",
".",
"observers",
":",
"if",
"theme",
"==",
"prov",
".",
"GetName",
"(",
")",
":",
"return",
"prov",
"# Case if a theme was deleted while it was the active theme",
"if",
"theme",
".",
"lower",
"(",
")",
"!=",
"u'default'",
":",
"Profile_Set",
"(",
"'ICONS'",
",",
"u'Default'",
")",
"return",
"None"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_theme.py#L118-L132 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | ReadClockResponse.fromTpm | (buf) | return buf.createObj(ReadClockResponse) | Returns new ReadClockResponse object constructed from its marshaled
representation in the given TpmBuffer buffer | Returns new ReadClockResponse object constructed from its marshaled
representation in the given TpmBuffer buffer | [
"Returns",
"new",
"ReadClockResponse",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new ReadClockResponse object constructed from its marshaled
representation in the given TpmBuffer buffer
"""
return buf.createObj(ReadClockResponse) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"ReadClockResponse",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16322-L16326 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_k_neighbors_classifier.py | python | supports_output_scores | (model) | return False | KNeighborsClassifier models do not support output scores. | KNeighborsClassifier models do not support output scores. | [
"KNeighborsClassifier",
"models",
"do",
"not",
"support",
"output",
"scores",
"."
] | def supports_output_scores(model):
"""KNeighborsClassifier models do not support output scores."""
return False | [
"def",
"supports_output_scores",
"(",
"model",
")",
":",
"return",
"False"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_k_neighbors_classifier.py#L59-L61 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | PhotoImage.subsample | (self,x,y='') | return destImage | Return a new PhotoImage based on the same image as this widget
but use only every Xth or Yth pixel. | Return a new PhotoImage based on the same image as this widget
but use only every Xth or Yth pixel. | [
"Return",
"a",
"new",
"PhotoImage",
"based",
"on",
"the",
"same",
"image",
"as",
"this",
"widget",
"but",
"use",
"only",
"every",
"Xth",
"or",
"Yth",
"pixel",
"."
] | def subsample(self,x,y=''):
"""Return a new PhotoImage based on the same image as this widget
but use only every Xth or Yth pixel."""
destImage = PhotoImage()
if y=='': y=x
self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
return destImage | [
"def",
"subsample",
"(",
"self",
",",
"x",
",",
"y",
"=",
"''",
")",
":",
"destImage",
"=",
"PhotoImage",
"(",
")",
"if",
"y",
"==",
"''",
":",
"y",
"=",
"x",
"self",
".",
"tk",
".",
"call",
"(",
"destImage",
",",
"'copy'",
",",
"self",
".",
"name",
",",
"'-subsample'",
",",
"x",
",",
"y",
")",
"return",
"destImage"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3329-L3335 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py | python | Circles.pick | (self, p, detectwidth=0.1) | return self._ids[dx*dx+dy*dy < (radii*radii)] | Returns a binary vector which is True values for circles that have been selected
by point p.
In particular, an element is selected if point p is within the circle | Returns a binary vector which is True values for circles that have been selected
by point p. | [
"Returns",
"a",
"binary",
"vector",
"which",
"is",
"True",
"values",
"for",
"circles",
"that",
"have",
"been",
"selected",
"by",
"point",
"p",
"."
] | def pick(self, p, detectwidth=0.1):
"""
Returns a binary vector which is True values for circles that have been selected
by point p.
In particular, an element is selected if point p is within the circle
"""
if len(self) == 0:
return np.array([], np.int)
#centers = self.centers.value
centers = self.get_centers_array()
radii = self.get_radii_array()+0.5*detectwidth
dx = centers[:, 0]-p[0]
dy = centers[:, 1]-p[1]
return self._ids[dx*dx+dy*dy < (radii*radii)] | [
"def",
"pick",
"(",
"self",
",",
"p",
",",
"detectwidth",
"=",
"0.1",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
",",
"np",
".",
"int",
")",
"#centers = self.centers.value",
"centers",
"=",
"self",
".",
"get_centers_array",
"(",
")",
"radii",
"=",
"self",
".",
"get_radii_array",
"(",
")",
"+",
"0.5",
"*",
"detectwidth",
"dx",
"=",
"centers",
"[",
":",
",",
"0",
"]",
"-",
"p",
"[",
"0",
"]",
"dy",
"=",
"centers",
"[",
":",
",",
"1",
"]",
"-",
"p",
"[",
"1",
"]",
"return",
"self",
".",
"_ids",
"[",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
"<",
"(",
"radii",
"*",
"radii",
")",
"]"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/ogleditor.py#L3706-L3721 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/linear_model/_theil_sen.py | python | TheilSenRegressor.fit | (self, X, y) | return self | Fit linear model.
Parameters
----------
X : numpy array of shape [n_samples, n_features]
Training data
y : numpy array of shape [n_samples]
Target values
Returns
-------
self : returns an instance of self. | Fit linear model. | [
"Fit",
"linear",
"model",
"."
] | def fit(self, X, y):
"""Fit linear model.
Parameters
----------
X : numpy array of shape [n_samples, n_features]
Training data
y : numpy array of shape [n_samples]
Target values
Returns
-------
self : returns an instance of self.
"""
random_state = check_random_state(self.random_state)
X, y = check_X_y(X, y, y_numeric=True)
n_samples, n_features = X.shape
n_subsamples, self.n_subpopulation_ = self._check_subparams(n_samples,
n_features)
self.breakdown_ = _breakdown_point(n_samples, n_subsamples)
if self.verbose:
print("Breakdown point: {0}".format(self.breakdown_))
print("Number of samples: {0}".format(n_samples))
tol_outliers = int(self.breakdown_ * n_samples)
print("Tolerable outliers: {0}".format(tol_outliers))
print("Number of subpopulations: {0}".format(
self.n_subpopulation_))
# Determine indices of subpopulation
if np.rint(binom(n_samples, n_subsamples)) <= self.max_subpopulation:
indices = list(combinations(range(n_samples), n_subsamples))
else:
indices = [random_state.choice(n_samples, size=n_subsamples,
replace=False)
for _ in range(self.n_subpopulation_)]
n_jobs = effective_n_jobs(self.n_jobs)
index_list = np.array_split(indices, n_jobs)
weights = Parallel(n_jobs=n_jobs,
verbose=self.verbose)(
delayed(_lstsq)(X, y, index_list[job], self.fit_intercept)
for job in range(n_jobs))
weights = np.vstack(weights)
self.n_iter_, coefs = _spatial_median(weights,
max_iter=self.max_iter,
tol=self.tol)
if self.fit_intercept:
self.intercept_ = coefs[0]
self.coef_ = coefs[1:]
else:
self.intercept_ = 0.
self.coef_ = coefs
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
"X",
",",
"y",
"=",
"check_X_y",
"(",
"X",
",",
"y",
",",
"y_numeric",
"=",
"True",
")",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"n_subsamples",
",",
"self",
".",
"n_subpopulation_",
"=",
"self",
".",
"_check_subparams",
"(",
"n_samples",
",",
"n_features",
")",
"self",
".",
"breakdown_",
"=",
"_breakdown_point",
"(",
"n_samples",
",",
"n_subsamples",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Breakdown point: {0}\"",
".",
"format",
"(",
"self",
".",
"breakdown_",
")",
")",
"print",
"(",
"\"Number of samples: {0}\"",
".",
"format",
"(",
"n_samples",
")",
")",
"tol_outliers",
"=",
"int",
"(",
"self",
".",
"breakdown_",
"*",
"n_samples",
")",
"print",
"(",
"\"Tolerable outliers: {0}\"",
".",
"format",
"(",
"tol_outliers",
")",
")",
"print",
"(",
"\"Number of subpopulations: {0}\"",
".",
"format",
"(",
"self",
".",
"n_subpopulation_",
")",
")",
"# Determine indices of subpopulation",
"if",
"np",
".",
"rint",
"(",
"binom",
"(",
"n_samples",
",",
"n_subsamples",
")",
")",
"<=",
"self",
".",
"max_subpopulation",
":",
"indices",
"=",
"list",
"(",
"combinations",
"(",
"range",
"(",
"n_samples",
")",
",",
"n_subsamples",
")",
")",
"else",
":",
"indices",
"=",
"[",
"random_state",
".",
"choice",
"(",
"n_samples",
",",
"size",
"=",
"n_subsamples",
",",
"replace",
"=",
"False",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"n_subpopulation_",
")",
"]",
"n_jobs",
"=",
"effective_n_jobs",
"(",
"self",
".",
"n_jobs",
")",
"index_list",
"=",
"np",
".",
"array_split",
"(",
"indices",
",",
"n_jobs",
")",
"weights",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"n_jobs",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"(",
"delayed",
"(",
"_lstsq",
")",
"(",
"X",
",",
"y",
",",
"index_list",
"[",
"job",
"]",
",",
"self",
".",
"fit_intercept",
")",
"for",
"job",
"in",
"range",
"(",
"n_jobs",
")",
")",
"weights",
"=",
"np",
".",
"vstack",
"(",
"weights",
")",
"self",
".",
"n_iter_",
",",
"coefs",
"=",
"_spatial_median",
"(",
"weights",
",",
"max_iter",
"=",
"self",
".",
"max_iter",
",",
"tol",
"=",
"self",
".",
"tol",
")",
"if",
"self",
".",
"fit_intercept",
":",
"self",
".",
"intercept_",
"=",
"coefs",
"[",
"0",
"]",
"self",
".",
"coef_",
"=",
"coefs",
"[",
"1",
":",
"]",
"else",
":",
"self",
".",
"intercept_",
"=",
"0.",
"self",
".",
"coef_",
"=",
"coefs",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/linear_model/_theil_sen.py#L346-L401 | |
moderngl/moderngl | 32fe79927e02b0fa893b3603d677bdae39771e14 | moderngl/vertex_array.py | python | VertexArray.render | (self, mode=None, vertices=-1, *, first=0, instances=-1) | The render primitive (mode) must be the same as
the input primitive of the GeometryShader.
Args:
mode (int): By default :py:data:`TRIANGLES` will be used.
vertices (int): The number of vertices to transform.
Keyword Args:
first (int): The index of the first vertex to start with.
instances (int): The number of instances. | The render primitive (mode) must be the same as
the input primitive of the GeometryShader. | [
"The",
"render",
"primitive",
"(",
"mode",
")",
"must",
"be",
"the",
"same",
"as",
"the",
"input",
"primitive",
"of",
"the",
"GeometryShader",
"."
] | def render(self, mode=None, vertices=-1, *, first=0, instances=-1) -> None:
'''
The render primitive (mode) must be the same as
the input primitive of the GeometryShader.
Args:
mode (int): By default :py:data:`TRIANGLES` will be used.
vertices (int): The number of vertices to transform.
Keyword Args:
first (int): The index of the first vertex to start with.
instances (int): The number of instances.
'''
if mode is None:
mode = self._mode
if self.scope:
with self.scope:
self.mglo.render(mode, vertices, first, instances)
else:
self.mglo.render(mode, vertices, first, instances) | [
"def",
"render",
"(",
"self",
",",
"mode",
"=",
"None",
",",
"vertices",
"=",
"-",
"1",
",",
"*",
",",
"first",
"=",
"0",
",",
"instances",
"=",
"-",
"1",
")",
"->",
"None",
":",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"self",
".",
"_mode",
"if",
"self",
".",
"scope",
":",
"with",
"self",
".",
"scope",
":",
"self",
".",
"mglo",
".",
"render",
"(",
"mode",
",",
"vertices",
",",
"first",
",",
"instances",
")",
"else",
":",
"self",
".",
"mglo",
".",
"render",
"(",
"mode",
",",
"vertices",
",",
"first",
",",
"instances",
")"
] | https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/vertex_array.py#L194-L215 | ||
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Tool/intelc.py | python | get_version_from_list | (v, vlist) | See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way. | See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way. | [
"See",
"if",
"we",
"can",
"match",
"v",
"(",
"string",
")",
"in",
"vlist",
"(",
"list",
"of",
"strings",
")",
"Linux",
"has",
"to",
"match",
"in",
"a",
"fuzzy",
"way",
"."
] | def get_version_from_list(v, vlist):
"""See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way."""
if is_windows:
# Simple case, just find it in the list
if v in vlist: return v
else: return None
else:
# Fuzzy match: normalize version number first, but still return
# original non-normalized form.
fuzz = 0.001
for vi in vlist:
if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz:
return vi
# Not found
return None | [
"def",
"get_version_from_list",
"(",
"v",
",",
"vlist",
")",
":",
"if",
"is_windows",
":",
"# Simple case, just find it in the list",
"if",
"v",
"in",
"vlist",
":",
"return",
"v",
"else",
":",
"return",
"None",
"else",
":",
"# Fuzzy match: normalize version number first, but still return",
"# original non-normalized form.",
"fuzz",
"=",
"0.001",
"for",
"vi",
"in",
"vlist",
":",
"if",
"math",
".",
"fabs",
"(",
"linux_ver_normalize",
"(",
"vi",
")",
"-",
"linux_ver_normalize",
"(",
"v",
")",
")",
"<",
"fuzz",
":",
"return",
"vi",
"# Not found",
"return",
"None"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/intelc.py#L118-L133 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/python_gflags/gflags.py | python | DEFINE_multi_int | (name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args) | Registers a flag whose value can be a list of arbitrary integers.
Use the flag on the command line multiple times to place multiple
integer values into the list. The 'default' may be a single integer
(which will be converted into a single-element list) or a list of
integers. | Registers a flag whose value can be a list of arbitrary integers. | [
"Registers",
"a",
"flag",
"whose",
"value",
"can",
"be",
"a",
"list",
"of",
"arbitrary",
"integers",
"."
] | def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary integers.
Use the flag on the command line multiple times to place multiple
integer values into the list. The 'default' may be a single integer
(which will be converted into a single-element list) or a list of
integers.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) | [
"def",
"DEFINE_multi_int",
"(",
"name",
",",
"default",
",",
"help",
",",
"lower_bound",
"=",
"None",
",",
"upper_bound",
"=",
"None",
",",
"flag_values",
"=",
"FLAGS",
",",
"*",
"*",
"args",
")",
":",
"parser",
"=",
"IntegerParser",
"(",
"lower_bound",
",",
"upper_bound",
")",
"serializer",
"=",
"ArgumentSerializer",
"(",
")",
"DEFINE_multi",
"(",
"parser",
",",
"serializer",
",",
"name",
",",
"default",
",",
"help",
",",
"flag_values",
",",
"*",
"*",
"args",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/python_gflags/gflags.py#L2812-L2823 | ||
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | BucketPointerArgument.WriteGetCode | (self, f) | Overridden from Argument. | Overridden from Argument. | [
"Overridden",
"from",
"Argument",
"."
] | def WriteGetCode(self, f):
"""Overridden from Argument."""
f.write(
" %s %s = bucket->GetData(0, data_size);\n" %
(self.type, self.name)) | [
"def",
"WriteGetCode",
"(",
"self",
",",
"f",
")",
":",
"f",
".",
"write",
"(",
"\" %s %s = bucket->GetData(0, data_size);\\n\"",
"%",
"(",
"self",
".",
"type",
",",
"self",
".",
"name",
")",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9005-L9009 | ||
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | scripts/recovery.py | python | insist | (*args, **kwargs) | Keep trying recoveries until the damn thing succeeds | Keep trying recoveries until the damn thing succeeds | [
"Keep",
"trying",
"recoveries",
"until",
"the",
"damn",
"thing",
"succeeds"
] | def insist(*args, **kwargs):
"""Keep trying recoveries until the damn thing succeeds"""
while True:
try:
return recover(*args, **kwargs)
except KeyboardInterrupt, e:
raise
except Exception, e:
print('Recovery failed:', e)
print('Trying again...')
time.sleep(0.1) | [
"def",
"insist",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"return",
"recover",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"KeyboardInterrupt",
",",
"e",
":",
"raise",
"except",
"Exception",
",",
"e",
":",
"print",
"(",
"'Recovery failed:'",
",",
"e",
")",
"print",
"(",
"'Trying again...'",
")",
"time",
".",
"sleep",
"(",
"0.1",
")"
] | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/scripts/recovery.py#L186-L196 | ||
dmlc/nnvm | dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38 | python/nnvm/_ctypes/symbol.py | python | SymbolBase._compose | (self, *args, **kwargs) | Compose symbol on inputs.
This call mutates the current symbol.
Parameters
----------
args:
provide positional arguments
kwargs:
provide keyword arguments
Returns
-------
the resulting symbol | Compose symbol on inputs. | [
"Compose",
"symbol",
"on",
"inputs",
"."
] | def _compose(self, *args, **kwargs):
"""Compose symbol on inputs.
This call mutates the current symbol.
Parameters
----------
args:
provide positional arguments
kwargs:
provide keyword arguments
Returns
-------
the resulting symbol
"""
name = kwargs.pop('name', None)
if name:
name = c_str(name)
if len(args) != 0 and len(kwargs) != 0:
raise TypeError('compose only accept input Symbols \
either as positional or keyword arguments, not both')
for arg in args:
if not isinstance(arg, SymbolBase):
raise TypeError('Compose expect `Symbol` as arguments')
for val in kwargs.values():
if not isinstance(val, SymbolBase):
raise TypeError('Compose expect `Symbol` as arguments')
num_args = len(args) + len(kwargs)
if len(kwargs) != 0:
keys = c_array(ctypes.c_char_p, [c_str(key) for key in kwargs.keys()])
args = c_array(SymbolHandle, [s.handle for s in kwargs.values()])
else:
keys = None
args = c_array(SymbolHandle, [s.handle for s in args])
check_call(_LIB.NNSymbolCompose(
self.handle, name, num_args, keys, args)) | [
"def",
"_compose",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"None",
")",
"if",
"name",
":",
"name",
"=",
"c_str",
"(",
"name",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"0",
"and",
"len",
"(",
"kwargs",
")",
"!=",
"0",
":",
"raise",
"TypeError",
"(",
"'compose only accept input Symbols \\\n either as positional or keyword arguments, not both'",
")",
"for",
"arg",
"in",
"args",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"SymbolBase",
")",
":",
"raise",
"TypeError",
"(",
"'Compose expect `Symbol` as arguments'",
")",
"for",
"val",
"in",
"kwargs",
".",
"values",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"SymbolBase",
")",
":",
"raise",
"TypeError",
"(",
"'Compose expect `Symbol` as arguments'",
")",
"num_args",
"=",
"len",
"(",
"args",
")",
"+",
"len",
"(",
"kwargs",
")",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"0",
":",
"keys",
"=",
"c_array",
"(",
"ctypes",
".",
"c_char_p",
",",
"[",
"c_str",
"(",
"key",
")",
"for",
"key",
"in",
"kwargs",
".",
"keys",
"(",
")",
"]",
")",
"args",
"=",
"c_array",
"(",
"SymbolHandle",
",",
"[",
"s",
".",
"handle",
"for",
"s",
"in",
"kwargs",
".",
"values",
"(",
")",
"]",
")",
"else",
":",
"keys",
"=",
"None",
"args",
"=",
"c_array",
"(",
"SymbolHandle",
",",
"[",
"s",
".",
"handle",
"for",
"s",
"in",
"args",
"]",
")",
"check_call",
"(",
"_LIB",
".",
"NNSymbolCompose",
"(",
"self",
".",
"handle",
",",
"name",
",",
"num_args",
",",
"keys",
",",
"args",
")",
")"
] | https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/_ctypes/symbol.py#L52-L92 | ||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/tools/scan-build-py/libscanbuild/clang.py | python | get_checkers | (clang, plugins) | return checkers | Get all the available checkers from default and from the plugins.
:param clang: the compiler we are using
:param plugins: list of plugins which was requested by the user
:return: a dictionary of all available checkers and its status
{<checker name>: (<checker description>, <is active by default>)} | Get all the available checkers from default and from the plugins. | [
"Get",
"all",
"the",
"available",
"checkers",
"from",
"default",
"and",
"from",
"the",
"plugins",
"."
] | def get_checkers(clang, plugins):
""" Get all the available checkers from default and from the plugins.
:param clang: the compiler we are using
:param plugins: list of plugins which was requested by the user
:return: a dictionary of all available checkers and its status
{<checker name>: (<checker description>, <is active by default>)} """
load = [elem for plugin in plugins for elem in ['-load', plugin]]
cmd = [clang, '-cc1'] + load + ['-analyzer-checker-help']
lines = run_command(cmd)
is_active_checker = is_active(get_active_checkers(clang, plugins))
checkers = {
name: (description, is_active_checker(name))
for name, description in parse_checkers(lines)
}
if not checkers:
raise Exception('Could not query Clang for available checkers.')
return checkers | [
"def",
"get_checkers",
"(",
"clang",
",",
"plugins",
")",
":",
"load",
"=",
"[",
"elem",
"for",
"plugin",
"in",
"plugins",
"for",
"elem",
"in",
"[",
"'-load'",
",",
"plugin",
"]",
"]",
"cmd",
"=",
"[",
"clang",
",",
"'-cc1'",
"]",
"+",
"load",
"+",
"[",
"'-analyzer-checker-help'",
"]",
"lines",
"=",
"run_command",
"(",
"cmd",
")",
"is_active_checker",
"=",
"is_active",
"(",
"get_active_checkers",
"(",
"clang",
",",
"plugins",
")",
")",
"checkers",
"=",
"{",
"name",
":",
"(",
"description",
",",
"is_active_checker",
"(",
"name",
")",
")",
"for",
"name",
",",
"description",
"in",
"parse_checkers",
"(",
"lines",
")",
"}",
"if",
"not",
"checkers",
":",
"raise",
"Exception",
"(",
"'Could not query Clang for available checkers.'",
")",
"return",
"checkers"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-build-py/libscanbuild/clang.py#L133-L156 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/parser.py | python | BytesParser.parse | (self, fp, headersonly=False) | Create a message structure from the data in a binary file.
Reads all the data from the file and returns the root of the message
structure. Optional headersonly is a flag specifying whether to stop
parsing after reading the headers or not. The default is False,
meaning it parses the entire contents of the file. | Create a message structure from the data in a binary file. | [
"Create",
"a",
"message",
"structure",
"from",
"the",
"data",
"in",
"a",
"binary",
"file",
"."
] | def parse(self, fp, headersonly=False):
"""Create a message structure from the data in a binary file.
Reads all the data from the file and returns the root of the message
structure. Optional headersonly is a flag specifying whether to stop
parsing after reading the headers or not. The default is False,
meaning it parses the entire contents of the file.
"""
fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape')
try:
return self.parser.parse(fp, headersonly)
finally:
fp.detach() | [
"def",
"parse",
"(",
"self",
",",
"fp",
",",
"headersonly",
"=",
"False",
")",
":",
"fp",
"=",
"TextIOWrapper",
"(",
"fp",
",",
"encoding",
"=",
"'ascii'",
",",
"errors",
"=",
"'surrogateescape'",
")",
"try",
":",
"return",
"self",
".",
"parser",
".",
"parse",
"(",
"fp",
",",
"headersonly",
")",
"finally",
":",
"fp",
".",
"detach",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/parser.py#L99-L111 | ||
oneapi-src/oneTBB | c9e43df34675ae5d9481c7ceab048085e3d5dae1 | python/tbb/__init__.py | python | TBBProcessPool3._repopulate_pool | (self) | Bring the number of pool processes up to the specified number,
for use after reaping workers which have exited. | Bring the number of pool processes up to the specified number,
for use after reaping workers which have exited. | [
"Bring",
"the",
"number",
"of",
"pool",
"processes",
"up",
"to",
"the",
"specified",
"number",
"for",
"use",
"after",
"reaping",
"workers",
"which",
"have",
"exited",
"."
] | def _repopulate_pool(self):
"""Bring the number of pool processes up to the specified number,
for use after reaping workers which have exited.
"""
from multiprocessing.util import debug
for i in range(self._processes - len(self._pool)):
w = self.Process(target=tbb_process_pool_worker3,
args=(self._inqueue, self._outqueue,
self._initializer,
self._initargs, self._maxtasksperchild,
self._wrap_exception)
)
self._pool.append(w)
w.name = w.name.replace('Process', 'PoolWorker')
w.daemon = True
w.start()
debug('added worker') | [
"def",
"_repopulate_pool",
"(",
"self",
")",
":",
"from",
"multiprocessing",
".",
"util",
"import",
"debug",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_processes",
"-",
"len",
"(",
"self",
".",
"_pool",
")",
")",
":",
"w",
"=",
"self",
".",
"Process",
"(",
"target",
"=",
"tbb_process_pool_worker3",
",",
"args",
"=",
"(",
"self",
".",
"_inqueue",
",",
"self",
".",
"_outqueue",
",",
"self",
".",
"_initializer",
",",
"self",
".",
"_initargs",
",",
"self",
".",
"_maxtasksperchild",
",",
"self",
".",
"_wrap_exception",
")",
")",
"self",
".",
"_pool",
".",
"append",
"(",
"w",
")",
"w",
".",
"name",
"=",
"w",
".",
"name",
".",
"replace",
"(",
"'Process'",
",",
"'PoolWorker'",
")",
"w",
".",
"daemon",
"=",
"True",
"w",
".",
"start",
"(",
")",
"debug",
"(",
"'added worker'",
")"
] | https://github.com/oneapi-src/oneTBB/blob/c9e43df34675ae5d9481c7ceab048085e3d5dae1/python/tbb/__init__.py#L125-L142 | ||
zhaoweicai/hwgq | ebc706bee3e2d145de1da4be446ce8de8740738f | scripts/cpp_lint.py | python | FindNextMultiLineCommentStart | (lines, lineix) | return len(lines) | Find the beginning marker for a multiline comment. | Find the beginning marker for a multiline comment. | [
"Find",
"the",
"beginning",
"marker",
"for",
"a",
"multiline",
"comment",
"."
] | def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return lineix
lineix += 1
return len(lines) | [
"def",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
":",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'/*'",
")",
":",
"# Only return this marker if the comment goes beyond this line",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"find",
"(",
"'*/'",
",",
"2",
")",
"<",
"0",
":",
"return",
"lineix",
"lineix",
"+=",
"1",
"return",
"len",
"(",
"lines",
")"
] | https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/scripts/cpp_lint.py#L1123-L1131 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/_inner_ops.py | python | DynamicBroadcastTo.__init__ | (self) | Initialize DynamicBroadcastTo | Initialize DynamicBroadcastTo | [
"Initialize",
"DynamicBroadcastTo"
] | def __init__(self):
"""Initialize DynamicBroadcastTo"""
self.init_prim_io_names(inputs=['x', 'shape'], outputs=['y']) | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"init_prim_io_names",
"(",
"inputs",
"=",
"[",
"'x'",
",",
"'shape'",
"]",
",",
"outputs",
"=",
"[",
"'y'",
"]",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/_inner_ops.py#L1431-L1433 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/alpha_zero/evaluator.py | python | AlphaZeroEvaluator.prior | (self, state) | return [(action, policy[action]) for action in state.legal_actions()] | Returns the probabilities for all actions. | Returns the probabilities for all actions. | [
"Returns",
"the",
"probabilities",
"for",
"all",
"actions",
"."
] | def prior(self, state):
"""Returns the probabilities for all actions."""
_, policy = self._inference(state)
return [(action, policy[action]) for action in state.legal_actions()] | [
"def",
"prior",
"(",
"self",
",",
"state",
")",
":",
"_",
",",
"policy",
"=",
"self",
".",
"_inference",
"(",
"state",
")",
"return",
"[",
"(",
"action",
",",
"policy",
"[",
"action",
"]",
")",
"for",
"action",
"in",
"state",
".",
"legal_actions",
"(",
")",
"]"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/alpha_zero/evaluator.py#L66-L69 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextCtrl.EndTextColour | (*args, **kwargs) | return _richtext.RichTextCtrl_EndTextColour(*args, **kwargs) | EndTextColour(self) -> bool
End using a colour | EndTextColour(self) -> bool | [
"EndTextColour",
"(",
"self",
")",
"-",
">",
"bool"
] | def EndTextColour(*args, **kwargs):
"""
EndTextColour(self) -> bool
End using a colour
"""
return _richtext.RichTextCtrl_EndTextColour(*args, **kwargs) | [
"def",
"EndTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_EndTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L3423-L3429 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Finder_items.py | python | Finder_items_Events.reveal | (self, _object, _attributes={}, **_arguments) | reveal: Bring the specified object(s) into view
Required argument: the object to be made visible
Keyword argument _attributes: AppleEvent attribute dictionary | reveal: Bring the specified object(s) into view
Required argument: the object to be made visible
Keyword argument _attributes: AppleEvent attribute dictionary | [
"reveal",
":",
"Bring",
"the",
"specified",
"object",
"(",
"s",
")",
"into",
"view",
"Required",
"argument",
":",
"the",
"object",
"to",
"be",
"made",
"visible",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary"
] | def reveal(self, _object, _attributes={}, **_arguments):
"""reveal: Bring the specified object(s) into view
Required argument: the object to be made visible
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'misc'
_subcode = 'mvis'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"reveal",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'misc'",
"_subcode",
"=",
"'mvis'",
"if",
"_arguments",
":",
"raise",
"TypeError",
",",
"'No optional args expected'",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Finder_items.py#L120-L138 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_vehicle.py | python | VehicleDomain.addSubscriptionFilterCFManeuver | (self, downstreamDist=None, upstreamDist=None) | addSubscriptionFilterCFManeuver() -> None
Restricts vehicles returned by the last modified vehicle context subscription to leader and follower of the ego.
downstreamDist and upstreamDist specify the range of the search for leader and follower along the road net. | addSubscriptionFilterCFManeuver() -> None | [
"addSubscriptionFilterCFManeuver",
"()",
"-",
">",
"None"
] | def addSubscriptionFilterCFManeuver(self, downstreamDist=None, upstreamDist=None):
"""addSubscriptionFilterCFManeuver() -> None
Restricts vehicles returned by the last modified vehicle context subscription to leader and follower of the ego.
downstreamDist and upstreamDist specify the range of the search for leader and follower along the road net.
"""
self.addSubscriptionFilterLeadFollow([0])
if downstreamDist is not None:
self.addSubscriptionFilterDownstreamDistance(downstreamDist)
if upstreamDist is not None:
self.addSubscriptionFilterUpstreamDistance(upstreamDist) | [
"def",
"addSubscriptionFilterCFManeuver",
"(",
"self",
",",
"downstreamDist",
"=",
"None",
",",
"upstreamDist",
"=",
"None",
")",
":",
"self",
".",
"addSubscriptionFilterLeadFollow",
"(",
"[",
"0",
"]",
")",
"if",
"downstreamDist",
"is",
"not",
"None",
":",
"self",
".",
"addSubscriptionFilterDownstreamDistance",
"(",
"downstreamDist",
")",
"if",
"upstreamDist",
"is",
"not",
"None",
":",
"self",
".",
"addSubscriptionFilterUpstreamDistance",
"(",
"upstreamDist",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L1669-L1679 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_ACT_SetTimeout_REQUEST.fromTpm | (buf) | return buf.createObj(TPM2_ACT_SetTimeout_REQUEST) | Returns new TPM2_ACT_SetTimeout_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | Returns new TPM2_ACT_SetTimeout_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | [
"Returns",
"new",
"TPM2_ACT_SetTimeout_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new TPM2_ACT_SetTimeout_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer
"""
return buf.createObj(TPM2_ACT_SetTimeout_REQUEST) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"TPM2_ACT_SetTimeout_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L17574-L17578 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/resources.py | python | Version.delete | (self, moveFixIssuesTo=None, moveAffectedIssuesTo=None) | return super(Version, self).delete(params) | Delete this project version from the server.
If neither of the arguments are specified, the version is
removed from all issues it is attached to.
:param moveFixIssuesTo: in issues for which this version is a fix
version, add this argument version to the fix version list
:param moveAffectedIssuesTo: in issues for which this version is an
affected version, add this argument version to the affected version list | Delete this project version from the server. | [
"Delete",
"this",
"project",
"version",
"from",
"the",
"server",
"."
] | def delete(self, moveFixIssuesTo=None, moveAffectedIssuesTo=None):
"""Delete this project version from the server.
If neither of the arguments are specified, the version is
removed from all issues it is attached to.
:param moveFixIssuesTo: in issues for which this version is a fix
version, add this argument version to the fix version list
:param moveAffectedIssuesTo: in issues for which this version is an
affected version, add this argument version to the affected version list
"""
params = {}
if moveFixIssuesTo is not None:
params['moveFixIssuesTo'] = moveFixIssuesTo
if moveAffectedIssuesTo is not None:
params['moveAffectedIssuesTo'] = moveAffectedIssuesTo
return super(Version, self).delete(params) | [
"def",
"delete",
"(",
"self",
",",
"moveFixIssuesTo",
"=",
"None",
",",
"moveAffectedIssuesTo",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"moveFixIssuesTo",
"is",
"not",
"None",
":",
"params",
"[",
"'moveFixIssuesTo'",
"]",
"=",
"moveFixIssuesTo",
"if",
"moveAffectedIssuesTo",
"is",
"not",
"None",
":",
"params",
"[",
"'moveAffectedIssuesTo'",
"]",
"=",
"moveAffectedIssuesTo",
"return",
"super",
"(",
"Version",
",",
"self",
")",
".",
"delete",
"(",
"params",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/resources.py#L765-L783 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/peakmeter.py | python | PeakMeterCtrl.IsGridVisible | (self) | return self._showGrid | Returns if gridlines are visible. | Returns if gridlines are visible. | [
"Returns",
"if",
"gridlines",
"are",
"visible",
"."
] | def IsGridVisible(self):
""" Returns if gridlines are visible. """
return self._showGrid | [
"def",
"IsGridVisible",
"(",
"self",
")",
":",
"return",
"self",
".",
"_showGrid"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/peakmeter.py#L530-L533 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/python_gflags/gflags.py | python | FlagValues.MainModuleHelp | (self) | return self.ModuleHelp(_GetMainModule()) | Describe the key flags of the main module.
Returns:
string describing the key flags of a module. | Describe the key flags of the main module. | [
"Describe",
"the",
"key",
"flags",
"of",
"the",
"main",
"module",
"."
] | def MainModuleHelp(self):
"""Describe the key flags of the main module.
Returns:
string describing the key flags of a module.
"""
return self.ModuleHelp(_GetMainModule()) | [
"def",
"MainModuleHelp",
"(",
"self",
")",
":",
"return",
"self",
".",
"ModuleHelp",
"(",
"_GetMainModule",
"(",
")",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/python_gflags/gflags.py#L1428-L1434 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/extras/eclipse.py | python | eclipse.create_cproject | (self, appname, workspace_includes=[], pythonpath=[]) | Create the Eclipse CDT .project and .cproject files
@param appname The name that will appear in the Project Explorer
@param build The BuildContext object to extract includes from
@param workspace_includes Optional project includes to prevent
"Unresolved Inclusion" errors in the Eclipse editor
@param pythonpath Optional project specific python paths | Create the Eclipse CDT .project and .cproject files | [
"Create",
"the",
"Eclipse",
"CDT",
".",
"project",
"and",
".",
"cproject",
"files"
] | def create_cproject(self, appname, workspace_includes=[], pythonpath=[]):
"""
Create the Eclipse CDT .project and .cproject files
@param appname The name that will appear in the Project Explorer
@param build The BuildContext object to extract includes from
@param workspace_includes Optional project includes to prevent
"Unresolved Inclusion" errors in the Eclipse editor
@param pythonpath Optional project specific python paths
"""
source_dirs = []
cpppath = self.env['CPPPATH']
Logs.warn('Generating Eclipse CDT project files')
for g in self.groups:
for tg in g:
if not isinstance(tg, TaskGen.task_gen):
continue
tg.post()
if not getattr(tg, 'link_task', None):
continue
l = Utils.to_list(getattr(tg, "includes", ''))
sources = Utils.to_list(getattr(tg, 'source', ''))
features = Utils.to_list(getattr(tg, 'features', ''))
is_cc = 'c' in features or 'cxx' in features
bldpath = tg.path.bldpath()
base = os.path.normpath(os.path.join(self.bldnode.name, tg.path.srcpath()))
if is_cc:
sources_dirs = set([src.parent for src in tg.to_nodes(sources)])
incnodes = tg.to_incnodes(tg.to_list(getattr(tg, 'includes', [])) + tg.env['INCLUDES'])
for p in incnodes:
path = p.path_from(self.srcnode)
workspace_includes.append(path)
if is_cc and path not in source_dirs:
source_dirs.append(path)
project = self.impl_create_project(sys.executable, appname)
self.srcnode.make_node('.project').write(project.toprettyxml())
waf = os.path.abspath(sys.argv[0])
project = self.impl_create_cproject(sys.executable, waf, appname, workspace_includes, cpppath, source_dirs)
self.srcnode.make_node('.cproject').write(project.toprettyxml())
project = self.impl_create_pydevproject(appname, sys.path, pythonpath)
self.srcnode.make_node('.pydevproject').write(project.toprettyxml()) | [
"def",
"create_cproject",
"(",
"self",
",",
"appname",
",",
"workspace_includes",
"=",
"[",
"]",
",",
"pythonpath",
"=",
"[",
"]",
")",
":",
"source_dirs",
"=",
"[",
"]",
"cpppath",
"=",
"self",
".",
"env",
"[",
"'CPPPATH'",
"]",
"Logs",
".",
"warn",
"(",
"'Generating Eclipse CDT project files'",
")",
"for",
"g",
"in",
"self",
".",
"groups",
":",
"for",
"tg",
"in",
"g",
":",
"if",
"not",
"isinstance",
"(",
"tg",
",",
"TaskGen",
".",
"task_gen",
")",
":",
"continue",
"tg",
".",
"post",
"(",
")",
"if",
"not",
"getattr",
"(",
"tg",
",",
"'link_task'",
",",
"None",
")",
":",
"continue",
"l",
"=",
"Utils",
".",
"to_list",
"(",
"getattr",
"(",
"tg",
",",
"\"includes\"",
",",
"''",
")",
")",
"sources",
"=",
"Utils",
".",
"to_list",
"(",
"getattr",
"(",
"tg",
",",
"'source'",
",",
"''",
")",
")",
"features",
"=",
"Utils",
".",
"to_list",
"(",
"getattr",
"(",
"tg",
",",
"'features'",
",",
"''",
")",
")",
"is_cc",
"=",
"'c'",
"in",
"features",
"or",
"'cxx'",
"in",
"features",
"bldpath",
"=",
"tg",
".",
"path",
".",
"bldpath",
"(",
")",
"base",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"bldnode",
".",
"name",
",",
"tg",
".",
"path",
".",
"srcpath",
"(",
")",
")",
")",
"if",
"is_cc",
":",
"sources_dirs",
"=",
"set",
"(",
"[",
"src",
".",
"parent",
"for",
"src",
"in",
"tg",
".",
"to_nodes",
"(",
"sources",
")",
"]",
")",
"incnodes",
"=",
"tg",
".",
"to_incnodes",
"(",
"tg",
".",
"to_list",
"(",
"getattr",
"(",
"tg",
",",
"'includes'",
",",
"[",
"]",
")",
")",
"+",
"tg",
".",
"env",
"[",
"'INCLUDES'",
"]",
")",
"for",
"p",
"in",
"incnodes",
":",
"path",
"=",
"p",
".",
"path_from",
"(",
"self",
".",
"srcnode",
")",
"workspace_includes",
".",
"append",
"(",
"path",
")",
"if",
"is_cc",
"and",
"path",
"not",
"in",
"source_dirs",
":",
"source_dirs",
".",
"append",
"(",
"path",
")",
"project",
"=",
"self",
".",
"impl_create_project",
"(",
"sys",
".",
"executable",
",",
"appname",
")",
"self",
".",
"srcnode",
".",
"make_node",
"(",
"'.project'",
")",
".",
"write",
"(",
"project",
".",
"toprettyxml",
"(",
")",
")",
"waf",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"project",
"=",
"self",
".",
"impl_create_cproject",
"(",
"sys",
".",
"executable",
",",
"waf",
",",
"appname",
",",
"workspace_includes",
",",
"cpppath",
",",
"source_dirs",
")",
"self",
".",
"srcnode",
".",
"make_node",
"(",
"'.cproject'",
")",
".",
"write",
"(",
"project",
".",
"toprettyxml",
"(",
")",
")",
"project",
"=",
"self",
".",
"impl_create_pydevproject",
"(",
"appname",
",",
"sys",
".",
"path",
",",
"pythonpath",
")",
"self",
".",
"srcnode",
".",
"make_node",
"(",
"'.pydevproject'",
")",
".",
"write",
"(",
"project",
".",
"toprettyxml",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/eclipse.py#L41-L92 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/value_object/read/media/datfile/terrain.py | python | TerrainBorder.get_data_format_members | (cls, game_version) | return data_format | Return the members in this struct. | Return the members in this struct. | [
"Return",
"the",
"members",
"in",
"this",
"struct",
"."
] | def get_data_format_members(cls, game_version):
"""
Return the members in this struct.
"""
data_format = [
(READ_GEN, "enabled", StorageType.BOOLEAN_MEMBER, "int8_t"),
(READ_GEN, "random", StorageType.INT_MEMBER, "int8_t"),
(READ_GEN, "internal_name", StorageType.STRING_MEMBER, "char[13]"),
(READ_GEN, "filename", StorageType.STRING_MEMBER, "char[13]"),
(READ_GEN, "slp_id", StorageType.ID_MEMBER, "int32_t"),
(SKIP, "shape_ptr", StorageType.ID_MEMBER, "int32_t"),
(READ_GEN, "sound_id", StorageType.ID_MEMBER, "int32_t"),
(READ_GEN, "color", StorageType.ARRAY_ID, "uint8_t[3]"),
(READ_GEN, None, None, IncludeMembers(cls=TerrainAnimation)),
(READ_GEN, "frames", StorageType.ARRAY_CONTAINER, SubdataMember(
ref_type=FrameData,
length=19 * 12, # number of tile types * 12
)),
(SKIP, "draw_tile", StorageType.INT_MEMBER, "int16_t"), # always 0
(READ_GEN, "underlay_terrain", StorageType.ID_MEMBER, "int16_t"),
(READ_GEN, "border_style", StorageType.INT_MEMBER, "int16_t"),
]
return data_format | [
"def",
"get_data_format_members",
"(",
"cls",
",",
"game_version",
")",
":",
"data_format",
"=",
"[",
"(",
"READ_GEN",
",",
"\"enabled\"",
",",
"StorageType",
".",
"BOOLEAN_MEMBER",
",",
"\"int8_t\"",
")",
",",
"(",
"READ_GEN",
",",
"\"random\"",
",",
"StorageType",
".",
"INT_MEMBER",
",",
"\"int8_t\"",
")",
",",
"(",
"READ_GEN",
",",
"\"internal_name\"",
",",
"StorageType",
".",
"STRING_MEMBER",
",",
"\"char[13]\"",
")",
",",
"(",
"READ_GEN",
",",
"\"filename\"",
",",
"StorageType",
".",
"STRING_MEMBER",
",",
"\"char[13]\"",
")",
",",
"(",
"READ_GEN",
",",
"\"slp_id\"",
",",
"StorageType",
".",
"ID_MEMBER",
",",
"\"int32_t\"",
")",
",",
"(",
"SKIP",
",",
"\"shape_ptr\"",
",",
"StorageType",
".",
"ID_MEMBER",
",",
"\"int32_t\"",
")",
",",
"(",
"READ_GEN",
",",
"\"sound_id\"",
",",
"StorageType",
".",
"ID_MEMBER",
",",
"\"int32_t\"",
")",
",",
"(",
"READ_GEN",
",",
"\"color\"",
",",
"StorageType",
".",
"ARRAY_ID",
",",
"\"uint8_t[3]\"",
")",
",",
"(",
"READ_GEN",
",",
"None",
",",
"None",
",",
"IncludeMembers",
"(",
"cls",
"=",
"TerrainAnimation",
")",
")",
",",
"(",
"READ_GEN",
",",
"\"frames\"",
",",
"StorageType",
".",
"ARRAY_CONTAINER",
",",
"SubdataMember",
"(",
"ref_type",
"=",
"FrameData",
",",
"length",
"=",
"19",
"*",
"12",
",",
"# number of tile types * 12",
")",
")",
",",
"(",
"SKIP",
",",
"\"draw_tile\"",
",",
"StorageType",
".",
"INT_MEMBER",
",",
"\"int16_t\"",
")",
",",
"# always 0",
"(",
"READ_GEN",
",",
"\"underlay_terrain\"",
",",
"StorageType",
".",
"ID_MEMBER",
",",
"\"int16_t\"",
")",
",",
"(",
"READ_GEN",
",",
"\"border_style\"",
",",
"StorageType",
".",
"INT_MEMBER",
",",
"\"int16_t\"",
")",
",",
"]",
"return",
"data_format"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/value_object/read/media/datfile/terrain.py#L271-L297 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/oldnumeric/ma.py | python | domain_greater_equal.__init__ | (self, critical_value) | domain_greater_equal(v)(x) = true where x < v | domain_greater_equal(v)(x) = true where x < v | [
"domain_greater_equal",
"(",
"v",
")",
"(",
"x",
")",
"=",
"true",
"where",
"x",
"<",
"v"
] | def __init__(self, critical_value):
"domain_greater_equal(v)(x) = true where x < v"
self.critical_value = critical_value | [
"def",
"__init__",
"(",
"self",
",",
"critical_value",
")",
":",
"self",
".",
"critical_value",
"=",
"critical_value"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L291-L293 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/input_lib.py | python | _replace_per_replica_spec | (spec, i) | If `spec` is a `PerReplicaSpec`, then return its `i`th value_spec. | If `spec` is a `PerReplicaSpec`, then return its `i`th value_spec. | [
"If",
"spec",
"is",
"a",
"PerReplicaSpec",
"then",
"return",
"its",
"i",
"th",
"value_spec",
"."
] | def _replace_per_replica_spec(spec, i):
"""If `spec` is a `PerReplicaSpec`, then return its `i`th value_spec."""
if isinstance(spec, values.PerReplicaSpec):
return spec._value_specs[i] # pylint: disable=protected-access
else:
return spec | [
"def",
"_replace_per_replica_spec",
"(",
"spec",
",",
"i",
")",
":",
"if",
"isinstance",
"(",
"spec",
",",
"values",
".",
"PerReplicaSpec",
")",
":",
"return",
"spec",
".",
"_value_specs",
"[",
"i",
"]",
"# pylint: disable=protected-access",
"else",
":",
"return",
"spec"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/input_lib.py#L2047-L2052 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/sessions.py | python | merge_hooks | (request_hooks, session_hooks, dict_class=OrderedDict) | return merge_setting(request_hooks, session_hooks, dict_class) | Properly merges both requests and session hooks.
This is necessary because when request_hooks == {'response': []}, the
merge breaks Session hooks entirely. | Properly merges both requests and session hooks. | [
"Properly",
"merges",
"both",
"requests",
"and",
"session",
"hooks",
"."
] | def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
"""Properly merges both requests and session hooks.
This is necessary because when request_hooks == {'response': []}, the
merge breaks Session hooks entirely.
"""
if session_hooks is None or session_hooks.get('response') == []:
return request_hooks
if request_hooks is None or request_hooks.get('response') == []:
return session_hooks
return merge_setting(request_hooks, session_hooks, dict_class) | [
"def",
"merge_hooks",
"(",
"request_hooks",
",",
"session_hooks",
",",
"dict_class",
"=",
"OrderedDict",
")",
":",
"if",
"session_hooks",
"is",
"None",
"or",
"session_hooks",
".",
"get",
"(",
"'response'",
")",
"==",
"[",
"]",
":",
"return",
"request_hooks",
"if",
"request_hooks",
"is",
"None",
"or",
"request_hooks",
".",
"get",
"(",
"'response'",
")",
"==",
"[",
"]",
":",
"return",
"session_hooks",
"return",
"merge_setting",
"(",
"request_hooks",
",",
"session_hooks",
",",
"dict_class",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/sessions.py#L81-L93 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/foldpanelbar.py | python | FoldPanelItem.AddWindow | (self, window, flags=FPB_ALIGN_WIDTH, spacing=FPB_DEFAULT_SPACING,
leftSpacing=FPB_DEFAULT_LEFTLINESPACING,
rightSpacing=FPB_DEFAULT_RIGHTLINESPACING) | Adds a window item to the list of items on this panel.
:param `window`: an instance of :class:`Window`;
:param `flags`: can be one of the following bits:
====================== ======= ====================================
Align Flag Value Description
====================== ======= ====================================
``FPB_ALIGN_WIDTH`` 1 The :class:`Window` to be added will be aligned to fit the width of the FoldPanel when it is resized. Very handy for sizer items, buttons and text boxes.
``FPB_ALIGN_LEFT`` 0 Aligns left instead of fitting the width of the child window to be added. Use either this one or ``FPB_ALIGN_WIDTH``.
====================== ======= ====================================
:param `spacing`: reserves a number of pixels before the window element;
:param `leftSpacing`: an indent, in pixels;
:param `rightSpacing`: a right spacing, only relevant when the style
``FPB_ALIGN_WIDTH`` is chosen. | Adds a window item to the list of items on this panel. | [
"Adds",
"a",
"window",
"item",
"to",
"the",
"list",
"of",
"items",
"on",
"this",
"panel",
"."
] | def AddWindow(self, window, flags=FPB_ALIGN_WIDTH, spacing=FPB_DEFAULT_SPACING,
leftSpacing=FPB_DEFAULT_LEFTLINESPACING,
rightSpacing=FPB_DEFAULT_RIGHTLINESPACING):
"""
Adds a window item to the list of items on this panel.
:param `window`: an instance of :class:`Window`;
:param `flags`: can be one of the following bits:
====================== ======= ====================================
Align Flag Value Description
====================== ======= ====================================
``FPB_ALIGN_WIDTH`` 1 The :class:`Window` to be added will be aligned to fit the width of the FoldPanel when it is resized. Very handy for sizer items, buttons and text boxes.
``FPB_ALIGN_LEFT`` 0 Aligns left instead of fitting the width of the child window to be added. Use either this one or ``FPB_ALIGN_WIDTH``.
====================== ======= ====================================
:param `spacing`: reserves a number of pixels before the window element;
:param `leftSpacing`: an indent, in pixels;
:param `rightSpacing`: a right spacing, only relevant when the style
``FPB_ALIGN_WIDTH`` is chosen.
"""
wi = FoldWindowItem(self, window, Type="WINDOW", flags=flags, spacing=spacing,
leftSpacing=leftSpacing, rightSpacing=rightSpacing)
self._items.append(wi)
vertical = self.IsVertical()
self._spacing = spacing
self._leftSpacing = leftSpacing
self._rightSpacing = rightSpacing
xpos = (vertical and [leftSpacing] or [self._LastInsertPos + spacing])[0]
ypos = (vertical and [self._LastInsertPos + spacing] or [leftSpacing])[0]
window.SetDimensions(xpos, ypos, -1, -1, wx.SIZE_USE_EXISTING)
self._LastInsertPos = self._LastInsertPos + wi.GetWindowLength(vertical)
self.ResizePanel() | [
"def",
"AddWindow",
"(",
"self",
",",
"window",
",",
"flags",
"=",
"FPB_ALIGN_WIDTH",
",",
"spacing",
"=",
"FPB_DEFAULT_SPACING",
",",
"leftSpacing",
"=",
"FPB_DEFAULT_LEFTLINESPACING",
",",
"rightSpacing",
"=",
"FPB_DEFAULT_RIGHTLINESPACING",
")",
":",
"wi",
"=",
"FoldWindowItem",
"(",
"self",
",",
"window",
",",
"Type",
"=",
"\"WINDOW\"",
",",
"flags",
"=",
"flags",
",",
"spacing",
"=",
"spacing",
",",
"leftSpacing",
"=",
"leftSpacing",
",",
"rightSpacing",
"=",
"rightSpacing",
")",
"self",
".",
"_items",
".",
"append",
"(",
"wi",
")",
"vertical",
"=",
"self",
".",
"IsVertical",
"(",
")",
"self",
".",
"_spacing",
"=",
"spacing",
"self",
".",
"_leftSpacing",
"=",
"leftSpacing",
"self",
".",
"_rightSpacing",
"=",
"rightSpacing",
"xpos",
"=",
"(",
"vertical",
"and",
"[",
"leftSpacing",
"]",
"or",
"[",
"self",
".",
"_LastInsertPos",
"+",
"spacing",
"]",
")",
"[",
"0",
"]",
"ypos",
"=",
"(",
"vertical",
"and",
"[",
"self",
".",
"_LastInsertPos",
"+",
"spacing",
"]",
"or",
"[",
"leftSpacing",
"]",
")",
"[",
"0",
"]",
"window",
".",
"SetDimensions",
"(",
"xpos",
",",
"ypos",
",",
"-",
"1",
",",
"-",
"1",
",",
"wx",
".",
"SIZE_USE_EXISTING",
")",
"self",
".",
"_LastInsertPos",
"=",
"self",
".",
"_LastInsertPos",
"+",
"wi",
".",
"GetWindowLength",
"(",
"vertical",
")",
"self",
".",
"ResizePanel",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/foldpanelbar.py#L1782-L1821 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/models.py | python | PreparedRequest.prepare_auth | (self, auth, url='') | Prepares the given HTTP auth data. | Prepares the given HTTP auth data. | [
"Prepares",
"the",
"given",
"HTTP",
"auth",
"data",
"."
] | def prepare_auth(self, auth, url=''):
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
url_auth = get_auth_from_url(self.url)
auth = url_auth if any(url_auth) else None
if auth:
if isinstance(auth, tuple) and len(auth) == 2:
# special-case basic HTTP auth
auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes.
r = auth(self)
# Update self to reflect the auth changes.
self.__dict__.update(r.__dict__)
# Recompute Content-Length
self.prepare_content_length(self.body) | [
"def",
"prepare_auth",
"(",
"self",
",",
"auth",
",",
"url",
"=",
"''",
")",
":",
"# If no Auth is explicitly provided, extract it from the URL first.",
"if",
"auth",
"is",
"None",
":",
"url_auth",
"=",
"get_auth_from_url",
"(",
"self",
".",
"url",
")",
"auth",
"=",
"url_auth",
"if",
"any",
"(",
"url_auth",
")",
"else",
"None",
"if",
"auth",
":",
"if",
"isinstance",
"(",
"auth",
",",
"tuple",
")",
"and",
"len",
"(",
"auth",
")",
"==",
"2",
":",
"# special-case basic HTTP auth",
"auth",
"=",
"HTTPBasicAuth",
"(",
"*",
"auth",
")",
"# Allow auth to make its changes.",
"r",
"=",
"auth",
"(",
"self",
")",
"# Update self to reflect the auth changes.",
"self",
".",
"__dict__",
".",
"update",
"(",
"r",
".",
"__dict__",
")",
"# Recompute Content-Length",
"self",
".",
"prepare_content_length",
"(",
"self",
".",
"body",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/models.py#L1073-L1113 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/examples/how_tos/reading_data/fully_connected_reader.py | python | inputs | (train, batch_size, num_epochs) | Reads input data num_epochs times.
Args:
train: Selects between the training (True) and validation (False) data.
batch_size: Number of examples per returned batch.
num_epochs: Number of times to read the input data, or 0/None to
train forever.
Returns:
A tuple (images, labels), where:
* images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]
in the range [-0.5, 0.5].
* labels is an int32 tensor with shape [batch_size] with the true label,
a number in the range [0, mnist.NUM_CLASSES).
Note that an tf.train.QueueRunner is added to the graph, which
must be run using e.g. tf.train.start_queue_runners(). | Reads input data num_epochs times. | [
"Reads",
"input",
"data",
"num_epochs",
"times",
"."
] | def inputs(train, batch_size, num_epochs):
"""Reads input data num_epochs times.
Args:
train: Selects between the training (True) and validation (False) data.
batch_size: Number of examples per returned batch.
num_epochs: Number of times to read the input data, or 0/None to
train forever.
Returns:
A tuple (images, labels), where:
* images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]
in the range [-0.5, 0.5].
* labels is an int32 tensor with shape [batch_size] with the true label,
a number in the range [0, mnist.NUM_CLASSES).
Note that an tf.train.QueueRunner is added to the graph, which
must be run using e.g. tf.train.start_queue_runners().
"""
if not num_epochs: num_epochs = None
filename = os.path.join(FLAGS.train_dir,
TRAIN_FILE if train else VALIDATION_FILE)
with tf.name_scope('input'):
filename_queue = tf.train.string_input_producer(
[filename], num_epochs=num_epochs)
# Even when reading in multiple threads, share the filename
# queue.
image, label = read_and_decode(filename_queue)
# Shuffle the examples and collect them into batch_size batches.
# (Internally uses a RandomShuffleQueue.)
# We run this in two threads to avoid being a bottleneck.
images, sparse_labels = tf.train.shuffle_batch(
[image, label], batch_size=batch_size, num_threads=2,
capacity=1000 + 3 * batch_size,
# Ensures a minimum amount of shuffling of examples.
min_after_dequeue=1000)
return images, sparse_labels | [
"def",
"inputs",
"(",
"train",
",",
"batch_size",
",",
"num_epochs",
")",
":",
"if",
"not",
"num_epochs",
":",
"num_epochs",
"=",
"None",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"FLAGS",
".",
"train_dir",
",",
"TRAIN_FILE",
"if",
"train",
"else",
"VALIDATION_FILE",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'input'",
")",
":",
"filename_queue",
"=",
"tf",
".",
"train",
".",
"string_input_producer",
"(",
"[",
"filename",
"]",
",",
"num_epochs",
"=",
"num_epochs",
")",
"# Even when reading in multiple threads, share the filename",
"# queue.",
"image",
",",
"label",
"=",
"read_and_decode",
"(",
"filename_queue",
")",
"# Shuffle the examples and collect them into batch_size batches.",
"# (Internally uses a RandomShuffleQueue.)",
"# We run this in two threads to avoid being a bottleneck.",
"images",
",",
"sparse_labels",
"=",
"tf",
".",
"train",
".",
"shuffle_batch",
"(",
"[",
"image",
",",
"label",
"]",
",",
"batch_size",
"=",
"batch_size",
",",
"num_threads",
"=",
"2",
",",
"capacity",
"=",
"1000",
"+",
"3",
"*",
"batch_size",
",",
"# Ensures a minimum amount of shuffling of examples.",
"min_after_dequeue",
"=",
"1000",
")",
"return",
"images",
",",
"sparse_labels"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/examples/how_tos/reading_data/fully_connected_reader.py#L84-L123 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | TopLevelWindow.OSXIsModified | (*args, **kwargs) | return _windows_.TopLevelWindow_OSXIsModified(*args, **kwargs) | OSXIsModified(self) -> bool | OSXIsModified(self) -> bool | [
"OSXIsModified",
"(",
"self",
")",
"-",
">",
"bool"
] | def OSXIsModified(*args, **kwargs):
"""OSXIsModified(self) -> bool"""
return _windows_.TopLevelWindow_OSXIsModified(*args, **kwargs) | [
"def",
"OSXIsModified",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"TopLevelWindow_OSXIsModified",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L540-L542 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/utils.py | python | LRUCache.itervalue | (self) | return iter(self.values()) | Iterate over all values. | Iterate over all values. | [
"Iterate",
"over",
"all",
"values",
"."
] | def itervalue(self):
"""Iterate over all values."""
return iter(self.values()) | [
"def",
"itervalue",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"values",
"(",
")",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/utils.py#L458-L460 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | load_json | (json_str) | return _Symbol(handle) | Loads symbol from json string.
Parameters
----------
json_str : str
A JSON string.
Returns
-------
sym : Symbol
The loaded symbol.
See Also
--------
_Symbol.tojson : Used to save symbol into json string. | Loads symbol from json string. | [
"Loads",
"symbol",
"from",
"json",
"string",
"."
] | def load_json(json_str):
"""Loads symbol from json string.
Parameters
----------
json_str : str
A JSON string.
Returns
-------
sym : Symbol
The loaded symbol.
See Also
--------
_Symbol.tojson : Used to save symbol into json string.
"""
if not isinstance(json_str, string_types):
raise TypeError('json_str needs to be string')
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromJSON(c_str(json_str), ctypes.byref(handle)))
return _Symbol(handle) | [
"def",
"load_json",
"(",
"json_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"json_str",
",",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'json_str needs to be string'",
")",
"handle",
"=",
"SymbolHandle",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXSymbolCreateFromJSON",
"(",
"c_str",
"(",
"json_str",
")",
",",
"ctypes",
".",
"byref",
"(",
"handle",
")",
")",
")",
"return",
"_Symbol",
"(",
"handle",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L7646-L7667 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pytz/tzinfo.py | python | unpickler | (zone, utcoffset=None, dstoffset=None, tzname=None) | return tz._tzinfos[inf] | Factory function for unpickling pytz tzinfo instances.
This is shared for both StaticTzInfo and DstTzInfo instances, because
database changes could cause a zones implementation to switch between
these two base classes and we can't break pickles on a pytz version
upgrade. | Factory function for unpickling pytz tzinfo instances. | [
"Factory",
"function",
"for",
"unpickling",
"pytz",
"tzinfo",
"instances",
"."
] | def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
"""Factory function for unpickling pytz tzinfo instances.
This is shared for both StaticTzInfo and DstTzInfo instances, because
database changes could cause a zones implementation to switch between
these two base classes and we can't break pickles on a pytz version
upgrade.
"""
# Raises a KeyError if zone no longer exists, which should never happen
# and would be a bug.
tz = pytz.timezone(zone)
# A StaticTzInfo - just return it
if utcoffset is None:
return tz
# This pickle was created from a DstTzInfo. We need to
# determine which of the list of tzinfo instances for this zone
# to use in order to restore the state of any datetime instances using
# it correctly.
utcoffset = memorized_timedelta(utcoffset)
dstoffset = memorized_timedelta(dstoffset)
try:
return tz._tzinfos[(utcoffset, dstoffset, tzname)]
except KeyError:
# The particular state requested in this timezone no longer exists.
# This indicates a corrupt pickle, or the timezone database has been
# corrected violently enough to make this particular
# (utcoffset,dstoffset) no longer exist in the zone, or the
# abbreviation has been changed.
pass
# See if we can find an entry differing only by tzname. Abbreviations
# get changed from the initial guess by the database maintainers to
# match reality when this information is discovered.
for localized_tz in tz._tzinfos.values():
if (localized_tz._utcoffset == utcoffset and
localized_tz._dst == dstoffset):
return localized_tz
# This (utcoffset, dstoffset) information has been removed from the
# zone. Add it back. This might occur when the database maintainers have
# corrected incorrect information. datetime instances using this
# incorrect information will continue to do so, exactly as they were
# before being pickled. This is purely an overly paranoid safety net - I
# doubt this will ever been needed in real life.
inf = (utcoffset, dstoffset, tzname)
tz._tzinfos[inf] = tz.__class__(inf, tz._tzinfos)
return tz._tzinfos[inf] | [
"def",
"unpickler",
"(",
"zone",
",",
"utcoffset",
"=",
"None",
",",
"dstoffset",
"=",
"None",
",",
"tzname",
"=",
"None",
")",
":",
"# Raises a KeyError if zone no longer exists, which should never happen",
"# and would be a bug.",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"zone",
")",
"# A StaticTzInfo - just return it",
"if",
"utcoffset",
"is",
"None",
":",
"return",
"tz",
"# This pickle was created from a DstTzInfo. We need to",
"# determine which of the list of tzinfo instances for this zone",
"# to use in order to restore the state of any datetime instances using",
"# it correctly.",
"utcoffset",
"=",
"memorized_timedelta",
"(",
"utcoffset",
")",
"dstoffset",
"=",
"memorized_timedelta",
"(",
"dstoffset",
")",
"try",
":",
"return",
"tz",
".",
"_tzinfos",
"[",
"(",
"utcoffset",
",",
"dstoffset",
",",
"tzname",
")",
"]",
"except",
"KeyError",
":",
"# The particular state requested in this timezone no longer exists.",
"# This indicates a corrupt pickle, or the timezone database has been",
"# corrected violently enough to make this particular",
"# (utcoffset,dstoffset) no longer exist in the zone, or the",
"# abbreviation has been changed.",
"pass",
"# See if we can find an entry differing only by tzname. Abbreviations",
"# get changed from the initial guess by the database maintainers to",
"# match reality when this information is discovered.",
"for",
"localized_tz",
"in",
"tz",
".",
"_tzinfos",
".",
"values",
"(",
")",
":",
"if",
"(",
"localized_tz",
".",
"_utcoffset",
"==",
"utcoffset",
"and",
"localized_tz",
".",
"_dst",
"==",
"dstoffset",
")",
":",
"return",
"localized_tz",
"# This (utcoffset, dstoffset) information has been removed from the",
"# zone. Add it back. This might occur when the database maintainers have",
"# corrected incorrect information. datetime instances using this",
"# incorrect information will continue to do so, exactly as they were",
"# before being pickled. This is purely an overly paranoid safety net - I",
"# doubt this will ever been needed in real life.",
"inf",
"=",
"(",
"utcoffset",
",",
"dstoffset",
",",
"tzname",
")",
"tz",
".",
"_tzinfos",
"[",
"inf",
"]",
"=",
"tz",
".",
"__class__",
"(",
"inf",
",",
"tz",
".",
"_tzinfos",
")",
"return",
"tz",
".",
"_tzinfos",
"[",
"inf",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pytz/tzinfo.py#L529-L577 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | lldb/examples/python/gdbremote.py | python | TerminalColors.red | (self, fg=True) | return '' | Set the foreground or background color to red.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. | Set the foreground or background color to red.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. | [
"Set",
"the",
"foreground",
"or",
"background",
"color",
"to",
"red",
".",
"The",
"foreground",
"color",
"will",
"be",
"set",
"if",
"fg",
"tests",
"True",
".",
"The",
"background",
"color",
"will",
"be",
"set",
"if",
"fg",
"tests",
"False",
"."
] | def red(self, fg=True):
'''Set the foreground or background color to red.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[31m"
else:
return "\x1b[41m"
return '' | [
"def",
"red",
"(",
"self",
",",
"fg",
"=",
"True",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"fg",
":",
"return",
"\"\\x1b[31m\"",
"else",
":",
"return",
"\"\\x1b[41m\"",
"return",
"''"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/examples/python/gdbremote.py#L111-L119 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.WriteSubMake | (self, output_filename, makefile_path, targets, build_dir) | Write a "sub-project" Makefile.
This is a small, wrapper Makefile that calls the top-level Makefile to build
the targets from a single gyp file (i.e. a sub-project).
Arguments:
output_filename: sub-project Makefile name to write
makefile_path: path to the top-level Makefile
targets: list of "all" targets for this sub-project
build_dir: build output directory, relative to the sub-project | Write a "sub-project" Makefile. | [
"Write",
"a",
"sub",
"-",
"project",
"Makefile",
"."
] | def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
"""Write a "sub-project" Makefile.
This is a small, wrapper Makefile that calls the top-level Makefile to build
the targets from a single gyp file (i.e. a sub-project).
Arguments:
output_filename: sub-project Makefile name to write
makefile_path: path to the top-level Makefile
targets: list of "all" targets for this sub-project
build_dir: build output directory, relative to the sub-project
"""
gyp.common.EnsureDirExists(output_filename)
self.fp = open(output_filename, 'w')
self.fp.write(header)
# For consistency with other builders, put sub-project build output in the
# sub-project dir (see test/subdirectory/gyptest-subdir-all.py).
self.WriteLn('export builddir_name ?= %s' %
os.path.join(os.path.dirname(output_filename), build_dir))
self.WriteLn('.PHONY: all')
self.WriteLn('all:')
if makefile_path:
makefile_path = ' -C ' + makefile_path
self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets)))
self.fp.close() | [
"def",
"WriteSubMake",
"(",
"self",
",",
"output_filename",
",",
"makefile_path",
",",
"targets",
",",
"build_dir",
")",
":",
"gyp",
".",
"common",
".",
"EnsureDirExists",
"(",
"output_filename",
")",
"self",
".",
"fp",
"=",
"open",
"(",
"output_filename",
",",
"'w'",
")",
"self",
".",
"fp",
".",
"write",
"(",
"header",
")",
"# For consistency with other builders, put sub-project build output in the",
"# sub-project dir (see test/subdirectory/gyptest-subdir-all.py).",
"self",
".",
"WriteLn",
"(",
"'export builddir_name ?= %s'",
"%",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"output_filename",
")",
",",
"build_dir",
")",
")",
"self",
".",
"WriteLn",
"(",
"'.PHONY: all'",
")",
"self",
".",
"WriteLn",
"(",
"'all:'",
")",
"if",
"makefile_path",
":",
"makefile_path",
"=",
"' -C '",
"+",
"makefile_path",
"self",
".",
"WriteLn",
"(",
"'\\t$(MAKE)%s %s'",
"%",
"(",
"makefile_path",
",",
"' '",
".",
"join",
"(",
"targets",
")",
")",
")",
"self",
".",
"fp",
".",
"close",
"(",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/make.py#L839-L863 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/events.py | python | get_event_loop | () | return get_event_loop_policy().get_event_loop() | Return an asyncio event loop.
When called from a coroutine or a callback (e.g. scheduled with call_soon
or similar API), this function will always return the running event loop.
If there is no running event loop set, the function will return
the result of `get_event_loop_policy().get_event_loop()` call. | Return an asyncio event loop. | [
"Return",
"an",
"asyncio",
"event",
"loop",
"."
] | def get_event_loop():
"""Return an asyncio event loop.
When called from a coroutine or a callback (e.g. scheduled with call_soon
or similar API), this function will always return the running event loop.
If there is no running event loop set, the function will return
the result of `get_event_loop_policy().get_event_loop()` call.
"""
# NOTE: this function is implemented in C (see _asynciomodule.c)
current_loop = _get_running_loop()
if current_loop is not None:
return current_loop
return get_event_loop_policy().get_event_loop() | [
"def",
"get_event_loop",
"(",
")",
":",
"# NOTE: this function is implemented in C (see _asynciomodule.c)",
"current_loop",
"=",
"_get_running_loop",
"(",
")",
"if",
"current_loop",
"is",
"not",
"None",
":",
"return",
"current_loop",
"return",
"get_event_loop_policy",
"(",
")",
".",
"get_event_loop",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/events.py#L739-L752 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/internal/well_known_types.py | python | Timestamp.ToMilliseconds | (self) | return (self.seconds * _MILLIS_PER_SECOND +
self.nanos // _NANOS_PER_MILLISECOND) | Converts Timestamp to milliseconds since epoch. | Converts Timestamp to milliseconds since epoch. | [
"Converts",
"Timestamp",
"to",
"milliseconds",
"since",
"epoch",
"."
] | def ToMilliseconds(self):
"""Converts Timestamp to milliseconds since epoch."""
return (self.seconds * _MILLIS_PER_SECOND +
self.nanos // _NANOS_PER_MILLISECOND) | [
"def",
"ToMilliseconds",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"seconds",
"*",
"_MILLIS_PER_SECOND",
"+",
"self",
".",
"nanos",
"//",
"_NANOS_PER_MILLISECOND",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/well_known_types.py#L210-L213 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/math_grad.py | python | _BetaincGrad | (op, grad) | return (
None, # da
None, # db
array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) | Returns gradient of betainc(a, b, x) with respect to x. | Returns gradient of betainc(a, b, x) with respect to x. | [
"Returns",
"gradient",
"of",
"betainc",
"(",
"a",
"b",
"x",
")",
"with",
"respect",
"to",
"x",
"."
] | def _BetaincGrad(op, grad):
"""Returns gradient of betainc(a, b, x) with respect to x."""
# TODO(ebrevdo): Perhaps add the derivative w.r.t. a, b
a, b, x = op.inputs
# two cases: x is a scalar and a/b are same-shaped tensors, or vice
# versa; so its sufficient to check against shape(a).
sa = array_ops.shape(a)
sx = array_ops.shape(x)
_, rx = gen_array_ops.broadcast_gradient_args(sa, sx)
# Perform operations in log space before summing, because terms
# can grow large.
log_beta = (
gen_math_ops.lgamma(a) + gen_math_ops.lgamma(b) -
gen_math_ops.lgamma(a + b))
# We use xlog1py and xlogy since the derivatives should tend to
# zero one one of the tails when a is 1. or b is 1.
partial_x = math_ops.exp(math_ops.xlog1py(b - 1, -x) +
math_ops.xlogy(a - 1, x) - log_beta)
return (
None, # da
None, # db
array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) | [
"def",
"_BetaincGrad",
"(",
"op",
",",
"grad",
")",
":",
"# TODO(ebrevdo): Perhaps add the derivative w.r.t. a, b",
"a",
",",
"b",
",",
"x",
"=",
"op",
".",
"inputs",
"# two cases: x is a scalar and a/b are same-shaped tensors, or vice",
"# versa; so its sufficient to check against shape(a).",
"sa",
"=",
"array_ops",
".",
"shape",
"(",
"a",
")",
"sx",
"=",
"array_ops",
".",
"shape",
"(",
"x",
")",
"_",
",",
"rx",
"=",
"gen_array_ops",
".",
"broadcast_gradient_args",
"(",
"sa",
",",
"sx",
")",
"# Perform operations in log space before summing, because terms",
"# can grow large.",
"log_beta",
"=",
"(",
"gen_math_ops",
".",
"lgamma",
"(",
"a",
")",
"+",
"gen_math_ops",
".",
"lgamma",
"(",
"b",
")",
"-",
"gen_math_ops",
".",
"lgamma",
"(",
"a",
"+",
"b",
")",
")",
"# We use xlog1py and xlogy since the derivatives should tend to",
"# zero one one of the tails when a is 1. or b is 1.",
"partial_x",
"=",
"math_ops",
".",
"exp",
"(",
"math_ops",
".",
"xlog1py",
"(",
"b",
"-",
"1",
",",
"-",
"x",
")",
"+",
"math_ops",
".",
"xlogy",
"(",
"a",
"-",
"1",
",",
"x",
")",
"-",
"log_beta",
")",
"return",
"(",
"None",
",",
"# da",
"None",
",",
"# db",
"array_ops",
".",
"reshape",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"partial_x",
"*",
"grad",
",",
"rx",
")",
",",
"sx",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_grad.py#L1099-L1123 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | Decimal._ln_exp_bound | (self) | return e + len(str(10**-e - c)) - 1 | Compute a lower bound for the adjusted exponent of self.ln().
In other words, compute r such that self.ln() >= 10**r. Assumes
that self is finite and positive and that self != 1. | Compute a lower bound for the adjusted exponent of self.ln().
In other words, compute r such that self.ln() >= 10**r. Assumes
that self is finite and positive and that self != 1. | [
"Compute",
"a",
"lower",
"bound",
"for",
"the",
"adjusted",
"exponent",
"of",
"self",
".",
"ln",
"()",
".",
"In",
"other",
"words",
"compute",
"r",
"such",
"that",
"self",
".",
"ln",
"()",
">",
"=",
"10",
"**",
"r",
".",
"Assumes",
"that",
"self",
"is",
"finite",
"and",
"positive",
"and",
"that",
"self",
"!",
"=",
"1",
"."
] | def _ln_exp_bound(self):
"""Compute a lower bound for the adjusted exponent of self.ln().
In other words, compute r such that self.ln() >= 10**r. Assumes
that self is finite and positive and that self != 1.
"""
# for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
adj = self._exp + len(self._int) - 1
if adj >= 1:
# argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
return len(str(adj*23//10)) - 1
if adj <= -2:
# argument <= 0.1
return len(str((-1-adj)*23//10)) - 1
op = _WorkRep(self)
c, e = op.int, op.exp
if adj == 0:
# 1 < self < 10
num = str(c-10**-e)
den = str(c)
return len(num) - len(den) - (num < den)
# adj == -1, 0.1 <= self < 1
return e + len(str(10**-e - c)) - 1 | [
"def",
"_ln_exp_bound",
"(",
"self",
")",
":",
"# for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1",
"adj",
"=",
"self",
".",
"_exp",
"+",
"len",
"(",
"self",
".",
"_int",
")",
"-",
"1",
"if",
"adj",
">=",
"1",
":",
"# argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)",
"return",
"len",
"(",
"str",
"(",
"adj",
"*",
"23",
"//",
"10",
")",
")",
"-",
"1",
"if",
"adj",
"<=",
"-",
"2",
":",
"# argument <= 0.1",
"return",
"len",
"(",
"str",
"(",
"(",
"-",
"1",
"-",
"adj",
")",
"*",
"23",
"//",
"10",
")",
")",
"-",
"1",
"op",
"=",
"_WorkRep",
"(",
"self",
")",
"c",
",",
"e",
"=",
"op",
".",
"int",
",",
"op",
".",
"exp",
"if",
"adj",
"==",
"0",
":",
"# 1 < self < 10",
"num",
"=",
"str",
"(",
"c",
"-",
"10",
"**",
"-",
"e",
")",
"den",
"=",
"str",
"(",
"c",
")",
"return",
"len",
"(",
"num",
")",
"-",
"len",
"(",
"den",
")",
"-",
"(",
"num",
"<",
"den",
")",
"# adj == -1, 0.1 <= self < 1",
"return",
"e",
"+",
"len",
"(",
"str",
"(",
"10",
"**",
"-",
"e",
"-",
"c",
")",
")",
"-",
"1"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L3063-L3085 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/special/orthogonal.py | python | sh_chebyt | (n, monic=False) | return base | r"""Shifted Chebyshev polynomial of the first kind.
Defined as :math:`T^*_n(x) = T_n(2x - 1)` for :math:`T_n` the nth
Chebyshev polynomial of the first kind.
Parameters
----------
n : int
Degree of the polynomial.
monic : bool, optional
If `True`, scale the leading coefficient to be 1. Default is
`False`.
Returns
-------
T : orthopoly1d
Shifted Chebyshev polynomial of the first kind.
Notes
-----
The polynomials :math:`T^*_n` are orthogonal over :math:`[0, 1]`
with weight function :math:`(x - x^2)^{-1/2}`. | r"""Shifted Chebyshev polynomial of the first kind. | [
"r",
"Shifted",
"Chebyshev",
"polynomial",
"of",
"the",
"first",
"kind",
"."
] | def sh_chebyt(n, monic=False):
r"""Shifted Chebyshev polynomial of the first kind.
Defined as :math:`T^*_n(x) = T_n(2x - 1)` for :math:`T_n` the nth
Chebyshev polynomial of the first kind.
Parameters
----------
n : int
Degree of the polynomial.
monic : bool, optional
If `True`, scale the leading coefficient to be 1. Default is
`False`.
Returns
-------
T : orthopoly1d
Shifted Chebyshev polynomial of the first kind.
Notes
-----
The polynomials :math:`T^*_n` are orthogonal over :math:`[0, 1]`
with weight function :math:`(x - x^2)^{-1/2}`.
"""
base = sh_jacobi(n, 0.0, 0.5, monic=monic)
if monic:
return base
if n > 0:
factor = 4**n / 2.0
else:
factor = 1.0
base._scale(factor)
return base | [
"def",
"sh_chebyt",
"(",
"n",
",",
"monic",
"=",
"False",
")",
":",
"base",
"=",
"sh_jacobi",
"(",
"n",
",",
"0.0",
",",
"0.5",
",",
"monic",
"=",
"monic",
")",
"if",
"monic",
":",
"return",
"base",
"if",
"n",
">",
"0",
":",
"factor",
"=",
"4",
"**",
"n",
"/",
"2.0",
"else",
":",
"factor",
"=",
"1.0",
"base",
".",
"_scale",
"(",
"factor",
")",
"return",
"base"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/special/orthogonal.py#L1771-L1804 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Validator.TransferFromWindow | (*args, **kwargs) | return _core_.Validator_TransferFromWindow(*args, **kwargs) | TransferFromWindow(self) -> bool | TransferFromWindow(self) -> bool | [
"TransferFromWindow",
"(",
"self",
")",
"-",
">",
"bool"
] | def TransferFromWindow(*args, **kwargs):
"""TransferFromWindow(self) -> bool"""
return _core_.Validator_TransferFromWindow(*args, **kwargs) | [
"def",
"TransferFromWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Validator_TransferFromWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L11888-L11890 | |
CleverRaven/Cataclysm-DDA | 03e7363df0835ec1b39da973ea29f26f27833b38 | utilities/building-utility/deconstruct.py | python | complete_json_file | (template_file, all_cells, remove_template=True) | Combines json template with cell list and writes out results.
Reads and separates json template from template settings. Then combines
cells and template, putting template_function_exec output into a list.
Finally writes out each json template list. | Combines json template with cell list and writes out results. | [
"Combines",
"json",
"template",
"with",
"cell",
"list",
"and",
"writes",
"out",
"results",
"."
] | def complete_json_file(template_file, all_cells, remove_template=True):
'''Combines json template with cell list and writes out results.
Reads and separates json template from template settings. Then combines
cells and template, putting template_function_exec output into a list.
Finally writes out each json template list.
'''
json_output_list = []
json_template = json.load(template_file)
template_settings = json_template.get(_TEMPLATE_JSON_SECTION)
if remove_template:
json_template.pop(_TEMPLATE_JSON_SECTION, None)
for cell_no, cell in enumerate(all_cells, 1):
copy_of_template = copy.deepcopy(json_template)
template_function_exec(
copy_of_template,
template_settings.get(_TEMPLATE_TYPE_CELL_MAP, {}),
cell)
template_function_exec(
copy_of_template,
template_settings.get(_TEMPLATE_TYPE_CELL_NUM, {}),
cell_no)
json_output_list.append(copy_of_template)
# TODO: better output file names
with open("output_" + os.path.basename(template_file.name),
"w", encoding="utf-8") as outfile:
json.dump(json_output_list, outfile, indent=4, separators=(",", ": "),
sort_keys=True, ensure_ascii=False) | [
"def",
"complete_json_file",
"(",
"template_file",
",",
"all_cells",
",",
"remove_template",
"=",
"True",
")",
":",
"json_output_list",
"=",
"[",
"]",
"json_template",
"=",
"json",
".",
"load",
"(",
"template_file",
")",
"template_settings",
"=",
"json_template",
".",
"get",
"(",
"_TEMPLATE_JSON_SECTION",
")",
"if",
"remove_template",
":",
"json_template",
".",
"pop",
"(",
"_TEMPLATE_JSON_SECTION",
",",
"None",
")",
"for",
"cell_no",
",",
"cell",
"in",
"enumerate",
"(",
"all_cells",
",",
"1",
")",
":",
"copy_of_template",
"=",
"copy",
".",
"deepcopy",
"(",
"json_template",
")",
"template_function_exec",
"(",
"copy_of_template",
",",
"template_settings",
".",
"get",
"(",
"_TEMPLATE_TYPE_CELL_MAP",
",",
"{",
"}",
")",
",",
"cell",
")",
"template_function_exec",
"(",
"copy_of_template",
",",
"template_settings",
".",
"get",
"(",
"_TEMPLATE_TYPE_CELL_NUM",
",",
"{",
"}",
")",
",",
"cell_no",
")",
"json_output_list",
".",
"append",
"(",
"copy_of_template",
")",
"# TODO: better output file names",
"with",
"open",
"(",
"\"output_\"",
"+",
"os",
".",
"path",
".",
"basename",
"(",
"template_file",
".",
"name",
")",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"json_output_list",
",",
"outfile",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\": \"",
")",
",",
"sort_keys",
"=",
"True",
",",
"ensure_ascii",
"=",
"False",
")"
] | https://github.com/CleverRaven/Cataclysm-DDA/blob/03e7363df0835ec1b39da973ea29f26f27833b38/utilities/building-utility/deconstruct.py#L160-L191 | ||
bundy-dns/bundy | 3d41934996b82b0cd2fe22dd74d2abc1daba835d | src/lib/python/bundy/cc/message.py | python | from_wire | (data) | return json.loads(data.decode('utf8'), strict=False) | Decodes the given bytes and parses it with the builtin JSON
parser. Raises a ValueError if the data is not valid JSON.
Raises an AttributeError if the given object has no decode()
method (which should return a string). | Decodes the given bytes and parses it with the builtin JSON
parser. Raises a ValueError if the data is not valid JSON.
Raises an AttributeError if the given object has no decode()
method (which should return a string). | [
"Decodes",
"the",
"given",
"bytes",
"and",
"parses",
"it",
"with",
"the",
"builtin",
"JSON",
"parser",
".",
"Raises",
"a",
"ValueError",
"if",
"the",
"data",
"is",
"not",
"valid",
"JSON",
".",
"Raises",
"an",
"AttributeError",
"if",
"the",
"given",
"object",
"has",
"no",
"decode",
"()",
"method",
"(",
"which",
"should",
"return",
"a",
"string",
")",
"."
] | def from_wire(data):
'''Decodes the given bytes and parses it with the builtin JSON
parser. Raises a ValueError if the data is not valid JSON.
Raises an AttributeError if the given object has no decode()
method (which should return a string).
'''
return json.loads(data.decode('utf8'), strict=False) | [
"def",
"from_wire",
"(",
"data",
")",
":",
"return",
"json",
".",
"loads",
"(",
"data",
".",
"decode",
"(",
"'utf8'",
")",
",",
"strict",
"=",
"False",
")"
] | https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/cc/message.py#L32-L38 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/setopt.py | python | edit_config | (filename, settings, dry_run=False) | Edit a configuration file to include `settings`
`settings` is a dictionary of dictionaries or ``None`` values, keyed by
command/section name. A ``None`` value means to delete the entire section,
while a dictionary lists settings to be changed or deleted in that section.
A setting of ``None`` means to delete that setting. | Edit a configuration file to include `settings` | [
"Edit",
"a",
"configuration",
"file",
"to",
"include",
"settings"
] | def edit_config(filename, settings, dry_run=False):
"""Edit a configuration file to include `settings`
`settings` is a dictionary of dictionaries or ``None`` values, keyed by
command/section name. A ``None`` value means to delete the entire section,
while a dictionary lists settings to be changed or deleted in that section.
A setting of ``None`` means to delete that setting.
"""
log.debug("Reading configuration from %s", filename)
opts = configparser.RawConfigParser()
opts.read([filename])
for section, options in settings.items():
if options is None:
log.info("Deleting section [%s] from %s", section, filename)
opts.remove_section(section)
else:
if not opts.has_section(section):
log.debug("Adding new section [%s] to %s", section, filename)
opts.add_section(section)
for option, value in options.items():
if value is None:
log.debug(
"Deleting %s.%s from %s",
section, option, filename
)
opts.remove_option(section, option)
if not opts.options(section):
log.info("Deleting empty [%s] section from %s",
section, filename)
opts.remove_section(section)
else:
log.debug(
"Setting %s.%s to %r in %s",
section, option, value, filename
)
opts.set(section, option, value)
log.info("Writing %s", filename)
if not dry_run:
with open(filename, 'w') as f:
opts.write(f) | [
"def",
"edit_config",
"(",
"filename",
",",
"settings",
",",
"dry_run",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"\"Reading configuration from %s\"",
",",
"filename",
")",
"opts",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"opts",
".",
"read",
"(",
"[",
"filename",
"]",
")",
"for",
"section",
",",
"options",
"in",
"settings",
".",
"items",
"(",
")",
":",
"if",
"options",
"is",
"None",
":",
"log",
".",
"info",
"(",
"\"Deleting section [%s] from %s\"",
",",
"section",
",",
"filename",
")",
"opts",
".",
"remove_section",
"(",
"section",
")",
"else",
":",
"if",
"not",
"opts",
".",
"has_section",
"(",
"section",
")",
":",
"log",
".",
"debug",
"(",
"\"Adding new section [%s] to %s\"",
",",
"section",
",",
"filename",
")",
"opts",
".",
"add_section",
"(",
"section",
")",
"for",
"option",
",",
"value",
"in",
"options",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"\"Deleting %s.%s from %s\"",
",",
"section",
",",
"option",
",",
"filename",
")",
"opts",
".",
"remove_option",
"(",
"section",
",",
"option",
")",
"if",
"not",
"opts",
".",
"options",
"(",
"section",
")",
":",
"log",
".",
"info",
"(",
"\"Deleting empty [%s] section from %s\"",
",",
"section",
",",
"filename",
")",
"opts",
".",
"remove_section",
"(",
"section",
")",
"else",
":",
"log",
".",
"debug",
"(",
"\"Setting %s.%s to %r in %s\"",
",",
"section",
",",
"option",
",",
"value",
",",
"filename",
")",
"opts",
".",
"set",
"(",
"section",
",",
"option",
",",
"value",
")",
"log",
".",
"info",
"(",
"\"Writing %s\"",
",",
"filename",
")",
"if",
"not",
"dry_run",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"opts",
".",
"write",
"(",
"f",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/setopt.py#L33-L73 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBInstruction.GetDescription | (self, description) | return _lldb.SBInstruction_GetDescription(self, description) | GetDescription(SBInstruction self, SBStream description) -> bool | GetDescription(SBInstruction self, SBStream description) -> bool | [
"GetDescription",
"(",
"SBInstruction",
"self",
"SBStream",
"description",
")",
"-",
">",
"bool"
] | def GetDescription(self, description):
"""GetDescription(SBInstruction self, SBStream description) -> bool"""
return _lldb.SBInstruction_GetDescription(self, description) | [
"def",
"GetDescription",
"(",
"self",
",",
"description",
")",
":",
"return",
"_lldb",
".",
"SBInstruction_GetDescription",
"(",
"self",
",",
"description",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6223-L6225 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/jinja2/filters.py | python | do_rejectattr | (*args, **kwargs) | return _select_or_reject(args, kwargs, lambda x: not x, True) | Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
.. versionadded:: 2.7 | Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding. | [
"Filters",
"a",
"sequence",
"of",
"objects",
"by",
"appying",
"a",
"test",
"to",
"either",
"the",
"object",
"or",
"the",
"attribute",
"and",
"rejecting",
"the",
"ones",
"with",
"the",
"test",
"succeeding",
"."
] | def do_rejectattr(*args, **kwargs):
"""Filters a sequence of objects by appying a test to either the object
or the attribute and rejecting the ones with the test succeeding.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
.. versionadded:: 2.7
"""
return _select_or_reject(args, kwargs, lambda x: not x, True) | [
"def",
"do_rejectattr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_select_or_reject",
"(",
"args",
",",
"kwargs",
",",
"lambda",
"x",
":",
"not",
"x",
",",
"True",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/filters.py#L893-L904 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/turtle.py | python | RawTurtle.undo | (self) | undo (repeatedly) the last turtle action.
No argument.
undo (repeatedly) the last turtle action.
Number of available undo actions is determined by the size of
the undobuffer.
Example (for a Turtle instance named turtle):
>>> for i in range(4):
... turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
... turtle.undo()
... | undo (repeatedly) the last turtle action. | [
"undo",
"(",
"repeatedly",
")",
"the",
"last",
"turtle",
"action",
"."
] | def undo(self):
"""undo (repeatedly) the last turtle action.
No argument.
undo (repeatedly) the last turtle action.
Number of available undo actions is determined by the size of
the undobuffer.
Example (for a Turtle instance named turtle):
>>> for i in range(4):
... turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
... turtle.undo()
...
"""
if self.undobuffer is None:
return
item = self.undobuffer.pop()
action = item[0]
data = item[1:]
if action == "seq":
while data:
item = data.pop()
self._undo(item[0], item[1:])
else:
self._undo(action, data) | [
"def",
"undo",
"(",
"self",
")",
":",
"if",
"self",
".",
"undobuffer",
"is",
"None",
":",
"return",
"item",
"=",
"self",
".",
"undobuffer",
".",
"pop",
"(",
")",
"action",
"=",
"item",
"[",
"0",
"]",
"data",
"=",
"item",
"[",
"1",
":",
"]",
"if",
"action",
"==",
"\"seq\"",
":",
"while",
"data",
":",
"item",
"=",
"data",
".",
"pop",
"(",
")",
"self",
".",
"_undo",
"(",
"item",
"[",
"0",
"]",
",",
"item",
"[",
"1",
":",
"]",
")",
"else",
":",
"self",
".",
"_undo",
"(",
"action",
",",
"data",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/turtle.py#L3513-L3540 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/collections.py | python | Counter.__or__ | (self, other) | return result | Union is the maximum of value in either of the input counters.
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1}) | Union is the maximum of value in either of the input counters. | [
"Union",
"is",
"the",
"maximum",
"of",
"value",
"in",
"either",
"of",
"the",
"input",
"counters",
"."
] | def __or__(self, other):
'''Union is the maximum of value in either of the input counters.
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = other_count if count < other_count else count
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result | [
"def",
"__or__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Counter",
")",
":",
"return",
"NotImplemented",
"result",
"=",
"Counter",
"(",
")",
"for",
"elem",
",",
"count",
"in",
"self",
".",
"items",
"(",
")",
":",
"other_count",
"=",
"other",
"[",
"elem",
"]",
"newcount",
"=",
"other_count",
"if",
"count",
"<",
"other_count",
"else",
"count",
"if",
"newcount",
">",
"0",
":",
"result",
"[",
"elem",
"]",
"=",
"newcount",
"for",
"elem",
",",
"count",
"in",
"other",
".",
"items",
"(",
")",
":",
"if",
"elem",
"not",
"in",
"self",
"and",
"count",
">",
"0",
":",
"result",
"[",
"elem",
"]",
"=",
"count",
"return",
"result"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/collections.py#L622-L640 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | SizerItem.AssignWindow | (*args, **kwargs) | return _core_.SizerItem_AssignWindow(*args, **kwargs) | AssignWindow(self, Window window)
Set the window to be managed by this sizer item. | AssignWindow(self, Window window) | [
"AssignWindow",
"(",
"self",
"Window",
"window",
")"
] | def AssignWindow(*args, **kwargs):
"""
AssignWindow(self, Window window)
Set the window to be managed by this sizer item.
"""
return _core_.SizerItem_AssignWindow(*args, **kwargs) | [
"def",
"AssignWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerItem_AssignWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14287-L14293 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/norm1.py | python | norm1.is_atom_concave | (self) | return False | Is the atom concave? | Is the atom concave? | [
"Is",
"the",
"atom",
"concave?"
] | def is_atom_concave(self) -> bool:
"""Is the atom concave?
"""
return False | [
"def",
"is_atom_concave",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"False"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/norm1.py#L48-L51 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | PRESUBMIT.py | python | _CheckUnwantedDependencies | (input_api, output_api) | return results | Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning. | Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning. | [
"Runs",
"checkdeps",
"on",
"#include",
"statements",
"added",
"in",
"this",
"change",
".",
"Breaking",
"-",
"rules",
"is",
"an",
"error",
"breaking",
"!",
"rules",
"is",
"a",
"warning",
"."
] | def _CheckUnwantedDependencies(input_api, output_api):
"""Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning.
"""
# We need to wait until we have an input_api object and use this
# roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__.
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'tools', 'checkdeps')]
import checkdeps
from cpp_checker import CppChecker
from rules import Rule
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
added_includes = []
for f in input_api.AffectedFiles():
if not CppChecker.IsCppFile(f.LocalPath()):
continue
changed_lines = [line for line_num, line in f.ChangedContents()]
added_includes.append([f.LocalPath(), changed_lines])
deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
error_descriptions = []
warning_descriptions = []
for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
added_includes):
description_with_path = '%s\n %s' % (path, rule_description)
if rule_type == Rule.DISALLOW:
error_descriptions.append(description_with_path)
else:
warning_descriptions.append(description_with_path)
results = []
if error_descriptions:
results.append(output_api.PresubmitError(
'You added one or more #includes that violate checkdeps rules.',
error_descriptions))
if warning_descriptions:
results.append(output_api.PresubmitPromptOrNotify(
'You added one or more #includes of files that are temporarily\n'
'allowed but being removed. Can you avoid introducing the\n'
'#include? See relevant DEPS file(s) for details and contacts.',
warning_descriptions))
return results | [
"def",
"_CheckUnwantedDependencies",
"(",
"input_api",
",",
"output_api",
")",
":",
"# We need to wait until we have an input_api object and use this",
"# roundabout construct to import checkdeps because this file is",
"# eval-ed and thus doesn't have __file__.",
"original_sys_path",
"=",
"sys",
".",
"path",
"try",
":",
"sys",
".",
"path",
"=",
"sys",
".",
"path",
"+",
"[",
"input_api",
".",
"os_path",
".",
"join",
"(",
"input_api",
".",
"PresubmitLocalPath",
"(",
")",
",",
"'tools'",
",",
"'checkdeps'",
")",
"]",
"import",
"checkdeps",
"from",
"cpp_checker",
"import",
"CppChecker",
"from",
"rules",
"import",
"Rule",
"finally",
":",
"# Restore sys.path to what it was before.",
"sys",
".",
"path",
"=",
"original_sys_path",
"added_includes",
"=",
"[",
"]",
"for",
"f",
"in",
"input_api",
".",
"AffectedFiles",
"(",
")",
":",
"if",
"not",
"CppChecker",
".",
"IsCppFile",
"(",
"f",
".",
"LocalPath",
"(",
")",
")",
":",
"continue",
"changed_lines",
"=",
"[",
"line",
"for",
"line_num",
",",
"line",
"in",
"f",
".",
"ChangedContents",
"(",
")",
"]",
"added_includes",
".",
"append",
"(",
"[",
"f",
".",
"LocalPath",
"(",
")",
",",
"changed_lines",
"]",
")",
"deps_checker",
"=",
"checkdeps",
".",
"DepsChecker",
"(",
"input_api",
".",
"PresubmitLocalPath",
"(",
")",
")",
"error_descriptions",
"=",
"[",
"]",
"warning_descriptions",
"=",
"[",
"]",
"for",
"path",
",",
"rule_type",
",",
"rule_description",
"in",
"deps_checker",
".",
"CheckAddedCppIncludes",
"(",
"added_includes",
")",
":",
"description_with_path",
"=",
"'%s\\n %s'",
"%",
"(",
"path",
",",
"rule_description",
")",
"if",
"rule_type",
"==",
"Rule",
".",
"DISALLOW",
":",
"error_descriptions",
".",
"append",
"(",
"description_with_path",
")",
"else",
":",
"warning_descriptions",
".",
"append",
"(",
"description_with_path",
")",
"results",
"=",
"[",
"]",
"if",
"error_descriptions",
":",
"results",
".",
"append",
"(",
"output_api",
".",
"PresubmitError",
"(",
"'You added one or more #includes that violate checkdeps rules.'",
",",
"error_descriptions",
")",
")",
"if",
"warning_descriptions",
":",
"results",
".",
"append",
"(",
"output_api",
".",
"PresubmitPromptOrNotify",
"(",
"'You added one or more #includes of files that are temporarily\\n'",
"'allowed but being removed. Can you avoid introducing the\\n'",
"'#include? See relevant DEPS file(s) for details and contacts.'",
",",
"warning_descriptions",
")",
")",
"return",
"results"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/PRESUBMIT.py#L472-L522 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Action.py | python | CommandAction.get_presig | (self, target, source, env, executor=None) | Return the signature contents of this action's command line.
This strips $(-$) and everything in between the string,
since those parts don't affect signatures. | Return the signature contents of this action's command line. | [
"Return",
"the",
"signature",
"contents",
"of",
"this",
"action",
"s",
"command",
"line",
"."
] | def get_presig(self, target, source, env, executor=None):
"""Return the signature contents of this action's command line.
This strips $(-$) and everything in between the string,
since those parts don't affect signatures.
"""
from SCons.Subst import SUBST_SIG
cmd = self.cmd_list
if is_List(cmd):
cmd = ' '.join(map(str, cmd))
else:
cmd = str(cmd)
if executor:
return env.subst_target_source(cmd, SUBST_SIG, executor=executor)
else:
return env.subst_target_source(cmd, SUBST_SIG, target, source) | [
"def",
"get_presig",
"(",
"self",
",",
"target",
",",
"source",
",",
"env",
",",
"executor",
"=",
"None",
")",
":",
"from",
"SCons",
".",
"Subst",
"import",
"SUBST_SIG",
"cmd",
"=",
"self",
".",
"cmd_list",
"if",
"is_List",
"(",
"cmd",
")",
":",
"cmd",
"=",
"' '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"cmd",
")",
")",
"else",
":",
"cmd",
"=",
"str",
"(",
"cmd",
")",
"if",
"executor",
":",
"return",
"env",
".",
"subst_target_source",
"(",
"cmd",
",",
"SUBST_SIG",
",",
"executor",
"=",
"executor",
")",
"else",
":",
"return",
"env",
".",
"subst_target_source",
"(",
"cmd",
",",
"SUBST_SIG",
",",
"target",
",",
"source",
")"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Action.py#L948-L963 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/resource_variable_ops.py | python | BaseResourceVariable.dtype | (self) | return self._dtype | The dtype of this variable. | The dtype of this variable. | [
"The",
"dtype",
"of",
"this",
"variable",
"."
] | def dtype(self):
"""The dtype of this variable."""
return self._dtype | [
"def",
"dtype",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dtype"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/resource_variable_ops.py#L470-L472 | |
taskflow/taskflow | f423a100a70b275f6e7331bc96537a3fe172e8d7 | 3rd-party/tbb/python/tbb/pool.py | python | ApplyResult.ready | (self) | return self._event.isSet() | Returns whether the call has completed. | Returns whether the call has completed. | [
"Returns",
"whether",
"the",
"call",
"has",
"completed",
"."
] | def ready(self):
"""Returns whether the call has completed."""
return self._event.isSet() | [
"def",
"ready",
"(",
"self",
")",
":",
"return",
"self",
".",
"_event",
".",
"isSet",
"(",
")"
] | https://github.com/taskflow/taskflow/blob/f423a100a70b275f6e7331bc96537a3fe172e8d7/3rd-party/tbb/python/tbb/pool.py#L361-L363 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py | python | _sparse_dense_truediv | (sp_indices, sp_values, sp_shape, y, name=None) | Internal helper function for 'sp_t / dense_t'. | Internal helper function for 'sp_t / dense_t'. | [
"Internal",
"helper",
"function",
"for",
"sp_t",
"/",
"dense_t",
"."
] | def _sparse_dense_truediv(sp_indices, sp_values, sp_shape, y, name=None):
"""Internal helper function for 'sp_t / dense_t'."""
with ops.name_scope(name, "truediv",
[sp_indices, sp_values, sp_shape, y]) as name:
sp_values = ops.convert_to_tensor(sp_values, name="sp_values")
y = ops.convert_to_tensor(y, name="y")
x_dtype = sp_values.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if x_dtype != y_dtype:
raise TypeError("x and y must have the same dtype, got %r != %r" %
(x_dtype, y_dtype))
try:
dtype = _TRUEDIV_TABLE[x_dtype]
except KeyError:
raise TypeError("Invalid dtype %r in __truediv__" % x_dtype)
if dtype is not None:
sp_values = cast(sp_values, dtype)
y = cast(y, dtype)
return gen_sparse_ops.sparse_dense_cwise_div(
sp_indices, sp_values, sp_shape, y, name=name) | [
"def",
"_sparse_dense_truediv",
"(",
"sp_indices",
",",
"sp_values",
",",
"sp_shape",
",",
"y",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"truediv\"",
",",
"[",
"sp_indices",
",",
"sp_values",
",",
"sp_shape",
",",
"y",
"]",
")",
"as",
"name",
":",
"sp_values",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"sp_values",
",",
"name",
"=",
"\"sp_values\"",
")",
"y",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"y",
",",
"name",
"=",
"\"y\"",
")",
"x_dtype",
"=",
"sp_values",
".",
"dtype",
".",
"base_dtype",
"y_dtype",
"=",
"y",
".",
"dtype",
".",
"base_dtype",
"if",
"x_dtype",
"!=",
"y_dtype",
":",
"raise",
"TypeError",
"(",
"\"x and y must have the same dtype, got %r != %r\"",
"%",
"(",
"x_dtype",
",",
"y_dtype",
")",
")",
"try",
":",
"dtype",
"=",
"_TRUEDIV_TABLE",
"[",
"x_dtype",
"]",
"except",
"KeyError",
":",
"raise",
"TypeError",
"(",
"\"Invalid dtype %r in __truediv__\"",
"%",
"x_dtype",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"sp_values",
"=",
"cast",
"(",
"sp_values",
",",
"dtype",
")",
"y",
"=",
"cast",
"(",
"y",
",",
"dtype",
")",
"return",
"gen_sparse_ops",
".",
"sparse_dense_cwise_div",
"(",
"sp_indices",
",",
"sp_values",
",",
"sp_shape",
",",
"y",
",",
"name",
"=",
"name",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py#L967-L986 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xmlDoc.newDocComment | (self, content) | return __tmp | Creation of a new node containing a comment within a
document. | Creation of a new node containing a comment within a
document. | [
"Creation",
"of",
"a",
"new",
"node",
"containing",
"a",
"comment",
"within",
"a",
"document",
"."
] | def newDocComment(self, content):
"""Creation of a new node containing a comment within a
document. """
ret = libxml2mod.xmlNewDocComment(self._o, content)
if ret is None:raise treeError('xmlNewDocComment() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"newDocComment",
"(",
"self",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDocComment",
"(",
"self",
".",
"_o",
",",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewDocComment() failed'",
")",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L3529-L3535 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | MouseEvent.ButtonDClick | (*args, **kwargs) | return _core_.MouseEvent_ButtonDClick(*args, **kwargs) | ButtonDClick(self, int but=MOUSE_BTN_ANY) -> bool
If the argument is omitted, this returns true if the event was any
mouse double click event. Otherwise the argument specifies which
double click event to check for (see `Button` for the possible
values). | ButtonDClick(self, int but=MOUSE_BTN_ANY) -> bool | [
"ButtonDClick",
"(",
"self",
"int",
"but",
"=",
"MOUSE_BTN_ANY",
")",
"-",
">",
"bool"
] | def ButtonDClick(*args, **kwargs):
"""
ButtonDClick(self, int but=MOUSE_BTN_ANY) -> bool
If the argument is omitted, this returns true if the event was any
mouse double click event. Otherwise the argument specifies which
double click event to check for (see `Button` for the possible
values).
"""
return _core_.MouseEvent_ButtonDClick(*args, **kwargs) | [
"def",
"ButtonDClick",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MouseEvent_ButtonDClick",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L5574-L5583 | |
waymo-research/waymo-open-dataset | 5de359f3429e1496761790770868296140161b66 | waymo_open_dataset/metrics/python/wod_detection_evaluator.py | python | WODDetectionEvaluator._get_default_config | (self) | return config | Returns the default Config proto for detection.
This is the python version of the GetConfig() function in
metrics/tools/compute_detection_metrics_main.cc | Returns the default Config proto for detection. | [
"Returns",
"the",
"default",
"Config",
"proto",
"for",
"detection",
"."
] | def _get_default_config(self):
"""Returns the default Config proto for detection.
This is the python version of the GetConfig() function in
metrics/tools/compute_detection_metrics_main.cc
"""
config = metrics_pb2.Config()
config.breakdown_generator_ids.append(breakdown_pb2.Breakdown.OBJECT_TYPE)
difficulty = config.difficulties.add()
difficulty.levels.append(label_pb2.Label.LEVEL_1)
difficulty.levels.append(label_pb2.Label.LEVEL_2)
config.breakdown_generator_ids.append(breakdown_pb2.Breakdown.RANGE)
difficulty = config.difficulties.add()
difficulty.levels.append(label_pb2.Label.LEVEL_1)
difficulty.levels.append(label_pb2.Label.LEVEL_2)
config.matcher_type = metrics_pb2.MatcherProto.TYPE_HUNGARIAN
config.iou_thresholds.append(0.0)
config.iou_thresholds.append(0.7)
config.iou_thresholds.append(0.5)
config.iou_thresholds.append(0.5)
config.iou_thresholds.append(0.5)
config.box_type = label_pb2.Label.Box.TYPE_3D
for i in range(100):
config.score_cutoffs.append(i * 0.01)
config.score_cutoffs.append(1.0)
return config | [
"def",
"_get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"metrics_pb2",
".",
"Config",
"(",
")",
"config",
".",
"breakdown_generator_ids",
".",
"append",
"(",
"breakdown_pb2",
".",
"Breakdown",
".",
"OBJECT_TYPE",
")",
"difficulty",
"=",
"config",
".",
"difficulties",
".",
"add",
"(",
")",
"difficulty",
".",
"levels",
".",
"append",
"(",
"label_pb2",
".",
"Label",
".",
"LEVEL_1",
")",
"difficulty",
".",
"levels",
".",
"append",
"(",
"label_pb2",
".",
"Label",
".",
"LEVEL_2",
")",
"config",
".",
"breakdown_generator_ids",
".",
"append",
"(",
"breakdown_pb2",
".",
"Breakdown",
".",
"RANGE",
")",
"difficulty",
"=",
"config",
".",
"difficulties",
".",
"add",
"(",
")",
"difficulty",
".",
"levels",
".",
"append",
"(",
"label_pb2",
".",
"Label",
".",
"LEVEL_1",
")",
"difficulty",
".",
"levels",
".",
"append",
"(",
"label_pb2",
".",
"Label",
".",
"LEVEL_2",
")",
"config",
".",
"matcher_type",
"=",
"metrics_pb2",
".",
"MatcherProto",
".",
"TYPE_HUNGARIAN",
"config",
".",
"iou_thresholds",
".",
"append",
"(",
"0.0",
")",
"config",
".",
"iou_thresholds",
".",
"append",
"(",
"0.7",
")",
"config",
".",
"iou_thresholds",
".",
"append",
"(",
"0.5",
")",
"config",
".",
"iou_thresholds",
".",
"append",
"(",
"0.5",
")",
"config",
".",
"iou_thresholds",
".",
"append",
"(",
"0.5",
")",
"config",
".",
"box_type",
"=",
"label_pb2",
".",
"Label",
".",
"Box",
".",
"TYPE_3D",
"for",
"i",
"in",
"range",
"(",
"100",
")",
":",
"config",
".",
"score_cutoffs",
".",
"append",
"(",
"i",
"*",
"0.01",
")",
"config",
".",
"score_cutoffs",
".",
"append",
"(",
"1.0",
")",
"return",
"config"
] | https://github.com/waymo-research/waymo-open-dataset/blob/5de359f3429e1496761790770868296140161b66/waymo_open_dataset/metrics/python/wod_detection_evaluator.py#L198-L227 | |
raspberrypi/tools | 13474ee775d0c5ec8a7da4fb0a9fa84187abfc87 | arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/share/gdb/python/gdb/prompt.py | python | _prompt_param | (attr) | return gdb.parameter(attr) | A parameter's value; the argument names the parameter. | A parameter's value; the argument names the parameter. | [
"A",
"parameter",
"s",
"value",
";",
"the",
"argument",
"names",
"the",
"parameter",
"."
] | def _prompt_param(attr):
"A parameter's value; the argument names the parameter."
return gdb.parameter(attr) | [
"def",
"_prompt_param",
"(",
"attr",
")",
":",
"return",
"gdb",
".",
"parameter",
"(",
"attr",
")"
] | https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/share/gdb/python/gdb/prompt.py#L70-L72 | |
chanyn/3Dpose_ssl | 585696676279683a279b1ecca136c0e0d02aef2a | caffe-3dssl/scripts/cpp_lint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/chanyn/3Dpose_ssl/blob/585696676279683a279b1ecca136c0e0d02aef2a/caffe-3dssl/scripts/cpp_lint.py#L1204-L1206 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListLineData.InReportView | (self) | return self._owner.HasAGWFlag(ULC_REPORT) | Returns ``True`` if the parent :class:`UltimateListCtrl` is in report view. | Returns ``True`` if the parent :class:`UltimateListCtrl` is in report view. | [
"Returns",
"True",
"if",
"the",
"parent",
":",
"class",
":",
"UltimateListCtrl",
"is",
"in",
"report",
"view",
"."
] | def InReportView(self):
""" Returns ``True`` if the parent :class:`UltimateListCtrl` is in report view. """
return self._owner.HasAGWFlag(ULC_REPORT) | [
"def",
"InReportView",
"(",
"self",
")",
":",
"return",
"self",
".",
"_owner",
".",
"HasAGWFlag",
"(",
"ULC_REPORT",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L3886-L3889 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py | python | IConversion.UserSexToText | (self, Sex) | return self._ToText('usex', Sex) | Returns user sex as text.
@param Sex: User sex.
@type Sex: L{User sex<enums.usexUnknown>}
@return: Text describing the user sex.
@rtype: unicode | Returns user sex as text. | [
"Returns",
"user",
"sex",
"as",
"text",
"."
] | def UserSexToText(self, Sex):
'''Returns user sex as text.
@param Sex: User sex.
@type Sex: L{User sex<enums.usexUnknown>}
@return: Text describing the user sex.
@rtype: unicode
'''
return self._ToText('usex', Sex) | [
"def",
"UserSexToText",
"(",
"self",
",",
"Sex",
")",
":",
"return",
"self",
".",
"_ToText",
"(",
"'usex'",
",",
"Sex",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py#L377-L385 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | RobotModelLink.setName | (self, name: "char const *") | return _robotsim.RobotModelLink_setName(self, name) | r"""
setName(RobotModelLink self, char const * name)
Sets the name of the robot link. | r"""
setName(RobotModelLink self, char const * name) | [
"r",
"setName",
"(",
"RobotModelLink",
"self",
"char",
"const",
"*",
"name",
")"
] | def setName(self, name: "char const *") -> "void":
r"""
setName(RobotModelLink self, char const * name)
Sets the name of the robot link.
"""
return _robotsim.RobotModelLink_setName(self, name) | [
"def",
"setName",
"(",
"self",
",",
"name",
":",
"\"char const *\"",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"RobotModelLink_setName",
"(",
"self",
",",
"name",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L4068-L4076 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/_lobpcg.py | python | LOBPCG._get_ortho | (self, U, V) | return U | Return B-orthonormal U with columns are B-orthogonal to V.
.. note:: When `bparams["ortho_use_drop"] == False` then
`_get_ortho` is based on the Algorithm 3 from
[DuerschPhD2015] that is a slight modification of
the corresponding algorithm introduced in
[StathopolousWu2002]. Otherwise, the method
implements Algorithm 6 from [DuerschPhD2015]
.. note:: If all U columns are B-collinear to V then the
returned tensor U will be empty.
Args:
U (Tensor) : initial approximation, size is (m, n)
V (Tensor) : B-orthogonal external basis, size is (m, k)
Returns:
U (Tensor) : B-orthonormal columns (:math:`U^T B U = I`)
such that :math:`V^T B U=0`, size is (m, n1),
where `n1 = n` if `drop` is `False, otherwise
`n1 <= n`. | Return B-orthonormal U with columns are B-orthogonal to V. | [
"Return",
"B",
"-",
"orthonormal",
"U",
"with",
"columns",
"are",
"B",
"-",
"orthogonal",
"to",
"V",
"."
] | def _get_ortho(self, U, V):
"""Return B-orthonormal U with columns are B-orthogonal to V.
.. note:: When `bparams["ortho_use_drop"] == False` then
`_get_ortho` is based on the Algorithm 3 from
[DuerschPhD2015] that is a slight modification of
the corresponding algorithm introduced in
[StathopolousWu2002]. Otherwise, the method
implements Algorithm 6 from [DuerschPhD2015]
.. note:: If all U columns are B-collinear to V then the
returned tensor U will be empty.
Args:
U (Tensor) : initial approximation, size is (m, n)
V (Tensor) : B-orthogonal external basis, size is (m, k)
Returns:
U (Tensor) : B-orthonormal columns (:math:`U^T B U = I`)
such that :math:`V^T B U=0`, size is (m, n1),
where `n1 = n` if `drop` is `False, otherwise
`n1 <= n`.
"""
mm = torch.matmul
mm_B = _utils.matmul
m = self.iparams['m']
tau_ortho = self.fparams['ortho_tol']
tau_drop = self.fparams['ortho_tol_drop']
tau_replace = self.fparams['ortho_tol_replace']
i_max = self.iparams['ortho_i_max']
j_max = self.iparams['ortho_j_max']
# when use_drop==True, enable dropping U columns that have
# small contribution to the `span([U, V])`.
use_drop = self.bparams['ortho_use_drop']
# clean up variables from the previous call
for vkey in list(self.fvars.keys()):
if vkey.startswith('ortho_') and vkey.endswith('_rerr'):
self.fvars.pop(vkey)
self.ivars.pop('ortho_i', 0)
self.ivars.pop('ortho_j', 0)
BV_norm = torch.norm(mm_B(self.B, V))
BU = mm_B(self.B, U)
VBU = mm(_utils.transpose(V), BU)
i = j = 0
stats = ''
for i in range(i_max):
U = U - mm(V, VBU)
drop = False
tau_svqb = tau_drop
for j in range(j_max):
if use_drop:
U = self._get_svqb(U, drop, tau_svqb)
drop = True
tau_svqb = tau_replace
else:
U = self._get_svqb(U, False, tau_replace)
if torch.numel(U) == 0:
# all initial U columns are B-collinear to V
self.ivars['ortho_i'] = i
self.ivars['ortho_j'] = j
return U
BU = mm_B(self.B, U)
UBU = mm(_utils.transpose(U), BU)
U_norm = torch.norm(U)
BU_norm = torch.norm(BU)
R = UBU - torch.eye(UBU.shape[-1],
device=UBU.device,
dtype=UBU.dtype)
R_norm = torch.norm(R)
# https://github.com/pytorch/pytorch/issues/33810 workaround:
rerr = float(R_norm) * float(BU_norm * U_norm) ** -1
vkey = 'ortho_UBUmI_rerr[{}, {}]'.format(i, j)
self.fvars[vkey] = rerr
if rerr < tau_ortho:
break
VBU = mm(_utils.transpose(V), BU)
VBU_norm = torch.norm(VBU)
U_norm = torch.norm(U)
rerr = float(VBU_norm) * float(BV_norm * U_norm) ** -1
vkey = 'ortho_VBU_rerr[{}]'.format(i)
self.fvars[vkey] = rerr
if rerr < tau_ortho:
break
if m < U.shape[-1] + V.shape[-1]:
# TorchScript needs the class var to be assigned to a local to
# do optional type refinement
B = self.B
assert B is not None
raise ValueError(
'Overdetermined shape of U:'
' #B-cols(={}) >= #U-cols(={}) + #V-cols(={}) must hold'
.format(B.shape[-1], U.shape[-1], V.shape[-1]))
self.ivars['ortho_i'] = i
self.ivars['ortho_j'] = j
return U | [
"def",
"_get_ortho",
"(",
"self",
",",
"U",
",",
"V",
")",
":",
"mm",
"=",
"torch",
".",
"matmul",
"mm_B",
"=",
"_utils",
".",
"matmul",
"m",
"=",
"self",
".",
"iparams",
"[",
"'m'",
"]",
"tau_ortho",
"=",
"self",
".",
"fparams",
"[",
"'ortho_tol'",
"]",
"tau_drop",
"=",
"self",
".",
"fparams",
"[",
"'ortho_tol_drop'",
"]",
"tau_replace",
"=",
"self",
".",
"fparams",
"[",
"'ortho_tol_replace'",
"]",
"i_max",
"=",
"self",
".",
"iparams",
"[",
"'ortho_i_max'",
"]",
"j_max",
"=",
"self",
".",
"iparams",
"[",
"'ortho_j_max'",
"]",
"# when use_drop==True, enable dropping U columns that have",
"# small contribution to the `span([U, V])`.",
"use_drop",
"=",
"self",
".",
"bparams",
"[",
"'ortho_use_drop'",
"]",
"# clean up variables from the previous call",
"for",
"vkey",
"in",
"list",
"(",
"self",
".",
"fvars",
".",
"keys",
"(",
")",
")",
":",
"if",
"vkey",
".",
"startswith",
"(",
"'ortho_'",
")",
"and",
"vkey",
".",
"endswith",
"(",
"'_rerr'",
")",
":",
"self",
".",
"fvars",
".",
"pop",
"(",
"vkey",
")",
"self",
".",
"ivars",
".",
"pop",
"(",
"'ortho_i'",
",",
"0",
")",
"self",
".",
"ivars",
".",
"pop",
"(",
"'ortho_j'",
",",
"0",
")",
"BV_norm",
"=",
"torch",
".",
"norm",
"(",
"mm_B",
"(",
"self",
".",
"B",
",",
"V",
")",
")",
"BU",
"=",
"mm_B",
"(",
"self",
".",
"B",
",",
"U",
")",
"VBU",
"=",
"mm",
"(",
"_utils",
".",
"transpose",
"(",
"V",
")",
",",
"BU",
")",
"i",
"=",
"j",
"=",
"0",
"stats",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"i_max",
")",
":",
"U",
"=",
"U",
"-",
"mm",
"(",
"V",
",",
"VBU",
")",
"drop",
"=",
"False",
"tau_svqb",
"=",
"tau_drop",
"for",
"j",
"in",
"range",
"(",
"j_max",
")",
":",
"if",
"use_drop",
":",
"U",
"=",
"self",
".",
"_get_svqb",
"(",
"U",
",",
"drop",
",",
"tau_svqb",
")",
"drop",
"=",
"True",
"tau_svqb",
"=",
"tau_replace",
"else",
":",
"U",
"=",
"self",
".",
"_get_svqb",
"(",
"U",
",",
"False",
",",
"tau_replace",
")",
"if",
"torch",
".",
"numel",
"(",
"U",
")",
"==",
"0",
":",
"# all initial U columns are B-collinear to V",
"self",
".",
"ivars",
"[",
"'ortho_i'",
"]",
"=",
"i",
"self",
".",
"ivars",
"[",
"'ortho_j'",
"]",
"=",
"j",
"return",
"U",
"BU",
"=",
"mm_B",
"(",
"self",
".",
"B",
",",
"U",
")",
"UBU",
"=",
"mm",
"(",
"_utils",
".",
"transpose",
"(",
"U",
")",
",",
"BU",
")",
"U_norm",
"=",
"torch",
".",
"norm",
"(",
"U",
")",
"BU_norm",
"=",
"torch",
".",
"norm",
"(",
"BU",
")",
"R",
"=",
"UBU",
"-",
"torch",
".",
"eye",
"(",
"UBU",
".",
"shape",
"[",
"-",
"1",
"]",
",",
"device",
"=",
"UBU",
".",
"device",
",",
"dtype",
"=",
"UBU",
".",
"dtype",
")",
"R_norm",
"=",
"torch",
".",
"norm",
"(",
"R",
")",
"# https://github.com/pytorch/pytorch/issues/33810 workaround:",
"rerr",
"=",
"float",
"(",
"R_norm",
")",
"*",
"float",
"(",
"BU_norm",
"*",
"U_norm",
")",
"**",
"-",
"1",
"vkey",
"=",
"'ortho_UBUmI_rerr[{}, {}]'",
".",
"format",
"(",
"i",
",",
"j",
")",
"self",
".",
"fvars",
"[",
"vkey",
"]",
"=",
"rerr",
"if",
"rerr",
"<",
"tau_ortho",
":",
"break",
"VBU",
"=",
"mm",
"(",
"_utils",
".",
"transpose",
"(",
"V",
")",
",",
"BU",
")",
"VBU_norm",
"=",
"torch",
".",
"norm",
"(",
"VBU",
")",
"U_norm",
"=",
"torch",
".",
"norm",
"(",
"U",
")",
"rerr",
"=",
"float",
"(",
"VBU_norm",
")",
"*",
"float",
"(",
"BV_norm",
"*",
"U_norm",
")",
"**",
"-",
"1",
"vkey",
"=",
"'ortho_VBU_rerr[{}]'",
".",
"format",
"(",
"i",
")",
"self",
".",
"fvars",
"[",
"vkey",
"]",
"=",
"rerr",
"if",
"rerr",
"<",
"tau_ortho",
":",
"break",
"if",
"m",
"<",
"U",
".",
"shape",
"[",
"-",
"1",
"]",
"+",
"V",
".",
"shape",
"[",
"-",
"1",
"]",
":",
"# TorchScript needs the class var to be assigned to a local to",
"# do optional type refinement",
"B",
"=",
"self",
".",
"B",
"assert",
"B",
"is",
"not",
"None",
"raise",
"ValueError",
"(",
"'Overdetermined shape of U:'",
"' #B-cols(={}) >= #U-cols(={}) + #V-cols(={}) must hold'",
".",
"format",
"(",
"B",
".",
"shape",
"[",
"-",
"1",
"]",
",",
"U",
".",
"shape",
"[",
"-",
"1",
"]",
",",
"V",
".",
"shape",
"[",
"-",
"1",
"]",
")",
")",
"self",
".",
"ivars",
"[",
"'ortho_i'",
"]",
"=",
"i",
"self",
".",
"ivars",
"[",
"'ortho_j'",
"]",
"=",
"j",
"return",
"U"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/_lobpcg.py#L1015-L1113 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/deprecation.py | python | _wrap_decorator | (wrapped_function) | return wrapper | Indicate that one function wraps another.
This decorator wraps a function using `tf_decorator.make_decorator`
so that doc generation scripts can pick up original function
signature.
It would be better to use @functools.wrap decorator, but it would
not update function signature to match wrapped function in Python 2.
Args:
wrapped_function: The function that decorated function wraps.
Returns:
Function that accepts wrapper function as an argument and returns
`TFDecorator` instance. | Indicate that one function wraps another. | [
"Indicate",
"that",
"one",
"function",
"wraps",
"another",
"."
] | def _wrap_decorator(wrapped_function):
"""Indicate that one function wraps another.
This decorator wraps a function using `tf_decorator.make_decorator`
so that doc generation scripts can pick up original function
signature.
It would be better to use @functools.wrap decorator, but it would
not update function signature to match wrapped function in Python 2.
Args:
wrapped_function: The function that decorated function wraps.
Returns:
Function that accepts wrapper function as an argument and returns
`TFDecorator` instance.
"""
def wrapper(wrapper_func):
return tf_decorator.make_decorator(wrapped_function, wrapper_func)
return wrapper | [
"def",
"_wrap_decorator",
"(",
"wrapped_function",
")",
":",
"def",
"wrapper",
"(",
"wrapper_func",
")",
":",
"return",
"tf_decorator",
".",
"make_decorator",
"(",
"wrapped_function",
",",
"wrapper_func",
")",
"return",
"wrapper"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/deprecation.py#L113-L131 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/multiarray.py | python | einsum | (*operands, **kwargs) | return _mx_nd_np.einsum(*operands, **kwargs) | r"""
einsum(subscripts, *operands, out=None, optimize=False)
Evaluates the Einstein summation convention on the operands.
Using the Einstein summation convention, many common multi-dimensional,
linear algebraic array operations can be represented in a simple fashion.
In *implicit* mode `einsum` computes these values.
In *explicit* mode, `einsum` provides further flexibility to compute
other array operations that might not be considered classical Einstein
summation operations, by disabling, or forcing summation over specified
subscript labels.
See the notes and examples for clarification.
Parameters
----------
subscripts : str
Specifies the subscripts for summation as comma separated list of
subscript labels. An implicit (classical Einstein summation)
calculation is performed unless the explicit indicator '->' is
included as well as subscript labels of the precise output form.
operands : list of ndarray
These are the arrays for the operation.
out : ndarray, optional
If provided, the calculation is done into this array.
optimize : {False, True}, optional
Controls if intermediate optimization should occur. No optimization
will occur if False. Defaults to False.
Returns
-------
output : ndarray
The calculation based on the Einstein summation convention.
Notes
-----
The Einstein summation convention can be used to compute
many multi-dimensional, linear algebraic array operations. `einsum`
provides a succinct way of representing these.
A non-exhaustive list of these operations,
which can be computed by `einsum`, is shown below along with examples:
* Trace of an array, :py:func:`np.trace`.
* Return a diagonal, :py:func:`np.diag`.
* Array axis summations, :py:func:`np.sum`.
* Transpositions and permutations, :py:func:`np.transpose`.
* Matrix multiplication and dot product, :py:func:`np.matmul` :py:func:`np.dot`.
* Vector inner and outer products, :py:func:`np.inner` :py:func:`np.outer`.
* Broadcasting, element-wise and scalar multiplication, :py:func:`np.multiply`.
* Tensor contractions, :py:func:`np.tensordot`.
The subscripts string is a comma-separated list of subscript labels,
where each label refers to a dimension of the corresponding operand.
Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
is equivalent to :py:func:`np.inner(a,b) <np.inner>`. If a label
appears only once, it is not summed, so ``np.einsum('i', a)`` produces a
view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``
describes traditional matrix multiplication and is equivalent to
:py:func:`np.matmul(a,b) <np.matmul>`. Repeated subscript labels in one
operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent
to :py:func:`np.trace(a) <np.trace>`.
In *implicit mode*, the chosen subscripts are important
since the axes of the output are reordered alphabetically. This
means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
``np.einsum('ji', a)`` takes its transpose. Additionally,
``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
``np.einsum('ij,jh', a, b)`` returns the transpose of the
multiplication since subscript 'h' precedes subscript 'i'.
In *explicit mode* the output can be directly controlled by
specifying output subscript labels. This requires the
identifier '->' as well as the list of output subscript labels.
This feature increases the flexibility of the function since
summing can be disabled or forced when required. The call
``np.einsum('i->', a)`` is like :py:func:`np.sum(a, axis=-1) <np.sum>`,
and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <np.diag>`.
The difference is that `einsum` does not allow broadcasting by default.
Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
order of the output subscript labels and therefore returns matrix
multiplication, unlike the example above in implicit mode.
To enable and control broadcasting, use an ellipsis. Default
NumPy-style broadcasting is done by adding an ellipsis
to the left of each term, like ``np.einsum('...ii->...i', a)``.
To take the trace along the first and last axes,
you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
product with the left-most indices instead of rightmost, one can do
``np.einsum('ij...,jk...->ik...', a, b)``.
When there is only one operand, no axes are summed, and no output
parameter is provided, a view into the operand is returned instead
of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
produces a view.
The ``optimize`` argument which will optimize the contraction order
of an einsum expression. For a contraction with three or more operands this
can greatly increase the computational efficiency at the cost of a larger
memory footprint during computation.
Typically a 'greedy' algorithm is applied which empirical tests have shown
returns the optimal path in the majority of cases. 'optimal' is not supported
for now.
.. note::
This function differs from the original `numpy.einsum
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html>`_ in
the following way(s):
* Does not support 'optimal' strategy
* Does not support the alternative subscript like
`einsum(op0, sublist0, op1, sublist1, ..., [sublistout])`
* Does not produce view in any cases
Examples
--------
>>> a = np.arange(25).reshape(5,5)
>>> b = np.arange(5)
>>> c = np.arange(6).reshape(2,3)
Trace of a matrix:
>>> np.einsum('ii', a)
array(60.)
Extract the diagonal (requires explicit form):
>>> np.einsum('ii->i', a)
array([ 0., 6., 12., 18., 24.])
Sum over an axis (requires explicit form):
>>> np.einsum('ij->i', a)
array([ 10., 35., 60., 85., 110.])
>>> np.sum(a, axis=1)
array([ 10., 35., 60., 85., 110.])
For higher dimensional arrays summing a single axis can be done with ellipsis:
>>> np.einsum('...j->...', a)
array([ 10., 35., 60., 85., 110.])
Compute a matrix transpose, or reorder any number of axes:
>>> np.einsum('ji', c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
>>> np.einsum('ij->ji', c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
>>> np.transpose(c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
Vector inner products:
>>> np.einsum('i,i', b, b)
array(30.)
Matrix vector multiplication:
>>> np.einsum('ij,j', a, b)
array([ 30., 80., 130., 180., 230.])
>>> np.dot(a, b)
array([ 30., 80., 130., 180., 230.])
>>> np.einsum('...j,j', a, b)
array([ 30., 80., 130., 180., 230.])
Broadcasting and scalar multiplication:
>>> np.einsum('..., ...', np.array(3), c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
>>> np.einsum(',ij', np.array(3), c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
>>> np.multiply(3, c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
Vector outer product:
>>> np.einsum('i,j', np.arange(2)+1, b)
array([[0., 1., 2., 3., 4.],
[0., 2., 4., 6., 8.]])
Tensor contraction:
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> np.einsum('ijk,jil->kl', a, b)
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
Example of ellipsis use:
>>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
>>> np.einsum('k...,jk', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
Chained array operations. For more complicated contractions, speed ups
might be achieved by repeatedly computing a 'greedy' path. Performance
improvements can be particularly significant with larger arrays:
>>> a = np.ones(64).reshape(2,4,8)
# Basic `einsum`: ~42.22ms (benchmarked on 3.4GHz Intel Xeon.)
>>> for iteration in range(500):
... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
# Greedy `einsum` (faster optimal path approximation): ~0.117ms
>>> for iteration in range(500):
... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=True) | r"""
einsum(subscripts, *operands, out=None, optimize=False) | [
"r",
"einsum",
"(",
"subscripts",
"*",
"operands",
"out",
"=",
"None",
"optimize",
"=",
"False",
")"
] | def einsum(*operands, **kwargs):
r"""
einsum(subscripts, *operands, out=None, optimize=False)
Evaluates the Einstein summation convention on the operands.
Using the Einstein summation convention, many common multi-dimensional,
linear algebraic array operations can be represented in a simple fashion.
In *implicit* mode `einsum` computes these values.
In *explicit* mode, `einsum` provides further flexibility to compute
other array operations that might not be considered classical Einstein
summation operations, by disabling, or forcing summation over specified
subscript labels.
See the notes and examples for clarification.
Parameters
----------
subscripts : str
Specifies the subscripts for summation as comma separated list of
subscript labels. An implicit (classical Einstein summation)
calculation is performed unless the explicit indicator '->' is
included as well as subscript labels of the precise output form.
operands : list of ndarray
These are the arrays for the operation.
out : ndarray, optional
If provided, the calculation is done into this array.
optimize : {False, True}, optional
Controls if intermediate optimization should occur. No optimization
will occur if False. Defaults to False.
Returns
-------
output : ndarray
The calculation based on the Einstein summation convention.
Notes
-----
The Einstein summation convention can be used to compute
many multi-dimensional, linear algebraic array operations. `einsum`
provides a succinct way of representing these.
A non-exhaustive list of these operations,
which can be computed by `einsum`, is shown below along with examples:
* Trace of an array, :py:func:`np.trace`.
* Return a diagonal, :py:func:`np.diag`.
* Array axis summations, :py:func:`np.sum`.
* Transpositions and permutations, :py:func:`np.transpose`.
* Matrix multiplication and dot product, :py:func:`np.matmul` :py:func:`np.dot`.
* Vector inner and outer products, :py:func:`np.inner` :py:func:`np.outer`.
* Broadcasting, element-wise and scalar multiplication, :py:func:`np.multiply`.
* Tensor contractions, :py:func:`np.tensordot`.
The subscripts string is a comma-separated list of subscript labels,
where each label refers to a dimension of the corresponding operand.
Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
is equivalent to :py:func:`np.inner(a,b) <np.inner>`. If a label
appears only once, it is not summed, so ``np.einsum('i', a)`` produces a
view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``
describes traditional matrix multiplication and is equivalent to
:py:func:`np.matmul(a,b) <np.matmul>`. Repeated subscript labels in one
operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent
to :py:func:`np.trace(a) <np.trace>`.
In *implicit mode*, the chosen subscripts are important
since the axes of the output are reordered alphabetically. This
means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
``np.einsum('ji', a)`` takes its transpose. Additionally,
``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
``np.einsum('ij,jh', a, b)`` returns the transpose of the
multiplication since subscript 'h' precedes subscript 'i'.
In *explicit mode* the output can be directly controlled by
specifying output subscript labels. This requires the
identifier '->' as well as the list of output subscript labels.
This feature increases the flexibility of the function since
summing can be disabled or forced when required. The call
``np.einsum('i->', a)`` is like :py:func:`np.sum(a, axis=-1) <np.sum>`,
and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <np.diag>`.
The difference is that `einsum` does not allow broadcasting by default.
Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
order of the output subscript labels and therefore returns matrix
multiplication, unlike the example above in implicit mode.
To enable and control broadcasting, use an ellipsis. Default
NumPy-style broadcasting is done by adding an ellipsis
to the left of each term, like ``np.einsum('...ii->...i', a)``.
To take the trace along the first and last axes,
you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
product with the left-most indices instead of rightmost, one can do
``np.einsum('ij...,jk...->ik...', a, b)``.
When there is only one operand, no axes are summed, and no output
parameter is provided, a view into the operand is returned instead
of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
produces a view.
The ``optimize`` argument which will optimize the contraction order
of an einsum expression. For a contraction with three or more operands this
can greatly increase the computational efficiency at the cost of a larger
memory footprint during computation.
Typically a 'greedy' algorithm is applied which empirical tests have shown
returns the optimal path in the majority of cases. 'optimal' is not supported
for now.
.. note::
This function differs from the original `numpy.einsum
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html>`_ in
the following way(s):
* Does not support 'optimal' strategy
* Does not support the alternative subscript like
`einsum(op0, sublist0, op1, sublist1, ..., [sublistout])`
* Does not produce view in any cases
Examples
--------
>>> a = np.arange(25).reshape(5,5)
>>> b = np.arange(5)
>>> c = np.arange(6).reshape(2,3)
Trace of a matrix:
>>> np.einsum('ii', a)
array(60.)
Extract the diagonal (requires explicit form):
>>> np.einsum('ii->i', a)
array([ 0., 6., 12., 18., 24.])
Sum over an axis (requires explicit form):
>>> np.einsum('ij->i', a)
array([ 10., 35., 60., 85., 110.])
>>> np.sum(a, axis=1)
array([ 10., 35., 60., 85., 110.])
For higher dimensional arrays summing a single axis can be done with ellipsis:
>>> np.einsum('...j->...', a)
array([ 10., 35., 60., 85., 110.])
Compute a matrix transpose, or reorder any number of axes:
>>> np.einsum('ji', c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
>>> np.einsum('ij->ji', c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
>>> np.transpose(c)
array([[0., 3.],
[1., 4.],
[2., 5.]])
Vector inner products:
>>> np.einsum('i,i', b, b)
array(30.)
Matrix vector multiplication:
>>> np.einsum('ij,j', a, b)
array([ 30., 80., 130., 180., 230.])
>>> np.dot(a, b)
array([ 30., 80., 130., 180., 230.])
>>> np.einsum('...j,j', a, b)
array([ 30., 80., 130., 180., 230.])
Broadcasting and scalar multiplication:
>>> np.einsum('..., ...', np.array(3), c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
>>> np.einsum(',ij', np.array(3), c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
>>> np.multiply(3, c)
array([[ 0., 3., 6.],
[ 9., 12., 15.]])
Vector outer product:
>>> np.einsum('i,j', np.arange(2)+1, b)
array([[0., 1., 2., 3., 4.],
[0., 2., 4., 6., 8.]])
Tensor contraction:
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> np.einsum('ijk,jil->kl', a, b)
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
Example of ellipsis use:
>>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
>>> np.einsum('k...,jk', a, b)
array([[10., 28., 46., 64.],
[13., 40., 67., 94.]])
Chained array operations. For more complicated contractions, speed ups
might be achieved by repeatedly computing a 'greedy' path. Performance
improvements can be particularly significant with larger arrays:
>>> a = np.ones(64).reshape(2,4,8)
# Basic `einsum`: ~42.22ms (benchmarked on 3.4GHz Intel Xeon.)
>>> for iteration in range(500):
... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
# Greedy `einsum` (faster optimal path approximation): ~0.117ms
>>> for iteration in range(500):
... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=True)
"""
return _mx_nd_np.einsum(*operands, **kwargs) | [
"def",
"einsum",
"(",
"*",
"operands",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_mx_nd_np",
".",
"einsum",
"(",
"*",
"operands",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L10679-L10909 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py | python | _main | () | Logic for inspecting an object given at command line | Logic for inspecting an object given at command line | [
"Logic",
"for",
"inspecting",
"an",
"object",
"given",
"at",
"command",
"line"
] | def _main():
""" Logic for inspecting an object given at command line """
import argparse
import importlib
parser = argparse.ArgumentParser()
parser.add_argument(
'object',
help="The object to be analysed. "
"It supports the 'module:qualname' syntax")
parser.add_argument(
'-d', '--details', action='store_true',
help='Display info about the module rather than its source code')
args = parser.parse_args()
target = args.object
mod_name, has_attrs, attrs = target.partition(":")
try:
obj = module = importlib.import_module(mod_name)
except Exception as exc:
msg = "Failed to import {} ({}: {})".format(mod_name,
type(exc).__name__,
exc)
print(msg, file=sys.stderr)
sys.exit(2)
if has_attrs:
parts = attrs.split(".")
obj = module
for part in parts:
obj = getattr(obj, part)
if module.__name__ in sys.builtin_module_names:
print("Can't get info for builtin modules.", file=sys.stderr)
sys.exit(1)
if args.details:
print('Target: {}'.format(target))
print('Origin: {}'.format(getsourcefile(module)))
print('Cached: {}'.format(module.__cached__))
if obj is module:
print('Loader: {}'.format(repr(module.__loader__)))
if hasattr(module, '__path__'):
print('Submodule search path: {}'.format(module.__path__))
else:
try:
__, lineno = findsource(obj)
except Exception:
pass
else:
print('Line: {}'.format(lineno))
print('\n')
else:
print(getsource(obj)) | [
"def",
"_main",
"(",
")",
":",
"import",
"argparse",
"import",
"importlib",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'object'",
",",
"help",
"=",
"\"The object to be analysed. \"",
"\"It supports the 'module:qualname' syntax\"",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--details'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Display info about the module rather than its source code'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"target",
"=",
"args",
".",
"object",
"mod_name",
",",
"has_attrs",
",",
"attrs",
"=",
"target",
".",
"partition",
"(",
"\":\"",
")",
"try",
":",
"obj",
"=",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"mod_name",
")",
"except",
"Exception",
"as",
"exc",
":",
"msg",
"=",
"\"Failed to import {} ({}: {})\"",
".",
"format",
"(",
"mod_name",
",",
"type",
"(",
"exc",
")",
".",
"__name__",
",",
"exc",
")",
"print",
"(",
"msg",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"if",
"has_attrs",
":",
"parts",
"=",
"attrs",
".",
"split",
"(",
"\".\"",
")",
"obj",
"=",
"module",
"for",
"part",
"in",
"parts",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"part",
")",
"if",
"module",
".",
"__name__",
"in",
"sys",
".",
"builtin_module_names",
":",
"print",
"(",
"\"Can't get info for builtin modules.\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"args",
".",
"details",
":",
"print",
"(",
"'Target: {}'",
".",
"format",
"(",
"target",
")",
")",
"print",
"(",
"'Origin: {}'",
".",
"format",
"(",
"getsourcefile",
"(",
"module",
")",
")",
")",
"print",
"(",
"'Cached: {}'",
".",
"format",
"(",
"module",
".",
"__cached__",
")",
")",
"if",
"obj",
"is",
"module",
":",
"print",
"(",
"'Loader: {}'",
".",
"format",
"(",
"repr",
"(",
"module",
".",
"__loader__",
")",
")",
")",
"if",
"hasattr",
"(",
"module",
",",
"'__path__'",
")",
":",
"print",
"(",
"'Submodule search path: {}'",
".",
"format",
"(",
"module",
".",
"__path__",
")",
")",
"else",
":",
"try",
":",
"__",
",",
"lineno",
"=",
"findsource",
"(",
"obj",
")",
"except",
"Exception",
":",
"pass",
"else",
":",
"print",
"(",
"'Line: {}'",
".",
"format",
"(",
"lineno",
")",
")",
"print",
"(",
"'\\n'",
")",
"else",
":",
"print",
"(",
"getsource",
"(",
"obj",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L3086-L3141 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/profiler/parser/integrator.py | python | BaseTimelineGenerator.write_timeline | (self, size_limit=SIZE_LIMIT_DEFAULT) | Load data according to the parsed profiling files. | Load data according to the parsed profiling files. | [
"Load",
"data",
"according",
"to",
"the",
"parsed",
"profiling",
"files",
"."
] | def write_timeline(self, size_limit=SIZE_LIMIT_DEFAULT):
"""Load data according to the parsed profiling files."""
# Write timeline to file.
logger.info('Writing timeline file...')
self.write_timeline_to_json_by_limitation(size_limit)
logger.info('Finished file writing!') | [
"def",
"write_timeline",
"(",
"self",
",",
"size_limit",
"=",
"SIZE_LIMIT_DEFAULT",
")",
":",
"# Write timeline to file.",
"logger",
".",
"info",
"(",
"'Writing timeline file...'",
")",
"self",
".",
"write_timeline_to_json_by_limitation",
"(",
"size_limit",
")",
"logger",
".",
"info",
"(",
"'Finished file writing!'",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/integrator.py#L582-L587 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | MoveEvent.__init__ | (self, *args, **kwargs) | __init__(self, Point pos=DefaultPosition, int winid=0) -> MoveEvent
Constructor. | __init__(self, Point pos=DefaultPosition, int winid=0) -> MoveEvent | [
"__init__",
"(",
"self",
"Point",
"pos",
"=",
"DefaultPosition",
"int",
"winid",
"=",
"0",
")",
"-",
">",
"MoveEvent"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Point pos=DefaultPosition, int winid=0) -> MoveEvent
Constructor.
"""
_core_.MoveEvent_swiginit(self,_core_.new_MoveEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_core_",
".",
"MoveEvent_swiginit",
"(",
"self",
",",
"_core_",
".",
"new_MoveEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L6182-L6188 | ||
Smorodov/Multitarget-tracker | bee300e8bfd660c86cbeb6892c65a5b7195c9381 | thirdparty/pybind11/tools/clang/cindex.py | python | SourceLocation.offset | (self) | return self._get_instantiation()[3] | Get the file offset represented by this source location. | Get the file offset represented by this source location. | [
"Get",
"the",
"file",
"offset",
"represented",
"by",
"this",
"source",
"location",
"."
] | def offset(self):
"""Get the file offset represented by this source location."""
return self._get_instantiation()[3] | [
"def",
"offset",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_instantiation",
"(",
")",
"[",
"3",
"]"
] | https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L213-L215 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/rnn.py | python | bidirectional_dynamic_rnn | (cell_fw,
cell_bw,
inputs,
sequence_length=None,
initial_state_fw=None,
initial_state_bw=None,
dtype=None,
parallel_iterations=None,
swap_memory=False,
time_major=False,
scope=None) | return (outputs, output_states) | Creates a dynamic version of bidirectional recurrent neural network.
Takes input and builds independent forward and backward RNNs. The input_size
of forward and backward cell must match. The initial state for both directions
is zero by default (but can be set optionally) and no intermediate states are
ever returned -- the network is fully unrolled for the given (passed in)
length(s) of the sequence(s) or completely unrolled if length(s) is not
given.
Args:
cell_fw: An instance of RNNCell, to be used for forward direction.
cell_bw: An instance of RNNCell, to be used for backward direction.
inputs: The RNN inputs.
If time_major == False (default), this must be a tensor of shape:
`[batch_size, max_time, ...]`, or a nested tuple of such elements.
If time_major == True, this must be a tensor of shape: `[max_time,
batch_size, ...]`, or a nested tuple of such elements.
sequence_length: (optional) An int32/int64 vector, size `[batch_size]`,
containing the actual lengths for each of the sequences in the batch. If
not provided, all batch entries are assumed to be full sequences; and time
reversal is applied from time `0` to `max_time` for each sequence.
initial_state_fw: (optional) An initial state for the forward RNN. This must
be a tensor of appropriate type and shape `[batch_size,
cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a
tuple of tensors having shapes `[batch_size, s] for s in
cell_fw.state_size`.
initial_state_bw: (optional) Same as for `initial_state_fw`, but using the
corresponding properties of `cell_bw`.
dtype: (optional) The data type for the initial states and expected output.
Required if initial_states are not provided or RNN states have a
heterogeneous dtype.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency and
can be run in parallel, will be. This parameter trades off time for
space. Values >> 1 use more memory but take less time, while smaller
values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs which
would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
time_major: The shape format of the `inputs` and `outputs` Tensors. If true,
these `Tensors` must be shaped `[max_time, batch_size, depth]`. If false,
these `Tensors` must be shaped `[batch_size, max_time, depth]`. Using
`time_major = True` is a bit more efficient because it avoids transposes
at the beginning and end of the RNN calculation. However, most TensorFlow
data is batch-major, so by default this function accepts input and emits
output in batch-major form.
scope: VariableScope for the created subgraph; defaults to
"bidirectional_rnn"
Returns:
A tuple (outputs, output_states) where:
outputs: A tuple (output_fw, output_bw) containing the forward and
the backward rnn output `Tensor`.
If time_major == False (default),
output_fw will be a `Tensor` shaped:
`[batch_size, max_time, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[batch_size, max_time, cell_bw.output_size]`.
If time_major == True,
output_fw will be a `Tensor` shaped:
`[max_time, batch_size, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[max_time, batch_size, cell_bw.output_size]`.
It returns a tuple instead of a single concatenated `Tensor`, unlike
in the `bidirectional_rnn`. If the concatenated one is preferred,
the forward and backward outputs can be concatenated as
`tf.concat(outputs, 2)`.
output_states: A tuple (output_state_fw, output_state_bw) containing
the forward and the backward final states of bidirectional rnn.
Raises:
TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. | Creates a dynamic version of bidirectional recurrent neural network. | [
"Creates",
"a",
"dynamic",
"version",
"of",
"bidirectional",
"recurrent",
"neural",
"network",
"."
] | def bidirectional_dynamic_rnn(cell_fw,
cell_bw,
inputs,
sequence_length=None,
initial_state_fw=None,
initial_state_bw=None,
dtype=None,
parallel_iterations=None,
swap_memory=False,
time_major=False,
scope=None):
"""Creates a dynamic version of bidirectional recurrent neural network.
Takes input and builds independent forward and backward RNNs. The input_size
of forward and backward cell must match. The initial state for both directions
is zero by default (but can be set optionally) and no intermediate states are
ever returned -- the network is fully unrolled for the given (passed in)
length(s) of the sequence(s) or completely unrolled if length(s) is not
given.
Args:
cell_fw: An instance of RNNCell, to be used for forward direction.
cell_bw: An instance of RNNCell, to be used for backward direction.
inputs: The RNN inputs.
If time_major == False (default), this must be a tensor of shape:
`[batch_size, max_time, ...]`, or a nested tuple of such elements.
If time_major == True, this must be a tensor of shape: `[max_time,
batch_size, ...]`, or a nested tuple of such elements.
sequence_length: (optional) An int32/int64 vector, size `[batch_size]`,
containing the actual lengths for each of the sequences in the batch. If
not provided, all batch entries are assumed to be full sequences; and time
reversal is applied from time `0` to `max_time` for each sequence.
initial_state_fw: (optional) An initial state for the forward RNN. This must
be a tensor of appropriate type and shape `[batch_size,
cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a
tuple of tensors having shapes `[batch_size, s] for s in
cell_fw.state_size`.
initial_state_bw: (optional) Same as for `initial_state_fw`, but using the
corresponding properties of `cell_bw`.
dtype: (optional) The data type for the initial states and expected output.
Required if initial_states are not provided or RNN states have a
heterogeneous dtype.
parallel_iterations: (Default: 32). The number of iterations to run in
parallel. Those operations which do not have any temporal dependency and
can be run in parallel, will be. This parameter trades off time for
space. Values >> 1 use more memory but take less time, while smaller
values use less memory but computations take longer.
swap_memory: Transparently swap the tensors produced in forward inference
but needed for back prop from GPU to CPU. This allows training RNNs which
would typically not fit on a single GPU, with very minimal (or no)
performance penalty.
time_major: The shape format of the `inputs` and `outputs` Tensors. If true,
these `Tensors` must be shaped `[max_time, batch_size, depth]`. If false,
these `Tensors` must be shaped `[batch_size, max_time, depth]`. Using
`time_major = True` is a bit more efficient because it avoids transposes
at the beginning and end of the RNN calculation. However, most TensorFlow
data is batch-major, so by default this function accepts input and emits
output in batch-major form.
scope: VariableScope for the created subgraph; defaults to
"bidirectional_rnn"
Returns:
A tuple (outputs, output_states) where:
outputs: A tuple (output_fw, output_bw) containing the forward and
the backward rnn output `Tensor`.
If time_major == False (default),
output_fw will be a `Tensor` shaped:
`[batch_size, max_time, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[batch_size, max_time, cell_bw.output_size]`.
If time_major == True,
output_fw will be a `Tensor` shaped:
`[max_time, batch_size, cell_fw.output_size]`
and output_bw will be a `Tensor` shaped:
`[max_time, batch_size, cell_bw.output_size]`.
It returns a tuple instead of a single concatenated `Tensor`, unlike
in the `bidirectional_rnn`. If the concatenated one is preferred,
the forward and backward outputs can be concatenated as
`tf.concat(outputs, 2)`.
output_states: A tuple (output_state_fw, output_state_bw) containing
the forward and the backward final states of bidirectional rnn.
Raises:
TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`.
"""
rnn_cell_impl.assert_like_rnncell("cell_fw", cell_fw)
rnn_cell_impl.assert_like_rnncell("cell_bw", cell_bw)
with vs.variable_scope(scope or "bidirectional_rnn"):
# Forward direction
with vs.variable_scope("fw") as fw_scope:
output_fw, output_state_fw = dynamic_rnn(
cell=cell_fw,
inputs=inputs,
sequence_length=sequence_length,
initial_state=initial_state_fw,
dtype=dtype,
parallel_iterations=parallel_iterations,
swap_memory=swap_memory,
time_major=time_major,
scope=fw_scope)
# Backward direction
if not time_major:
time_axis = 1
batch_axis = 0
else:
time_axis = 0
batch_axis = 1
def _reverse(input_, seq_lengths, seq_axis, batch_axis):
if seq_lengths is not None:
return array_ops.reverse_sequence(
input=input_,
seq_lengths=seq_lengths,
seq_axis=seq_axis,
batch_axis=batch_axis)
else:
return array_ops.reverse(input_, axis=[seq_axis])
with vs.variable_scope("bw") as bw_scope:
def _map_reverse(inp):
return _reverse(
inp,
seq_lengths=sequence_length,
seq_axis=time_axis,
batch_axis=batch_axis)
inputs_reverse = nest.map_structure(_map_reverse, inputs)
tmp, output_state_bw = dynamic_rnn(
cell=cell_bw,
inputs=inputs_reverse,
sequence_length=sequence_length,
initial_state=initial_state_bw,
dtype=dtype,
parallel_iterations=parallel_iterations,
swap_memory=swap_memory,
time_major=time_major,
scope=bw_scope)
output_bw = _reverse(
tmp,
seq_lengths=sequence_length,
seq_axis=time_axis,
batch_axis=batch_axis)
outputs = (output_fw, output_bw)
output_states = (output_state_fw, output_state_bw)
return (outputs, output_states) | [
"def",
"bidirectional_dynamic_rnn",
"(",
"cell_fw",
",",
"cell_bw",
",",
"inputs",
",",
"sequence_length",
"=",
"None",
",",
"initial_state_fw",
"=",
"None",
",",
"initial_state_bw",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"parallel_iterations",
"=",
"None",
",",
"swap_memory",
"=",
"False",
",",
"time_major",
"=",
"False",
",",
"scope",
"=",
"None",
")",
":",
"rnn_cell_impl",
".",
"assert_like_rnncell",
"(",
"\"cell_fw\"",
",",
"cell_fw",
")",
"rnn_cell_impl",
".",
"assert_like_rnncell",
"(",
"\"cell_bw\"",
",",
"cell_bw",
")",
"with",
"vs",
".",
"variable_scope",
"(",
"scope",
"or",
"\"bidirectional_rnn\"",
")",
":",
"# Forward direction",
"with",
"vs",
".",
"variable_scope",
"(",
"\"fw\"",
")",
"as",
"fw_scope",
":",
"output_fw",
",",
"output_state_fw",
"=",
"dynamic_rnn",
"(",
"cell",
"=",
"cell_fw",
",",
"inputs",
"=",
"inputs",
",",
"sequence_length",
"=",
"sequence_length",
",",
"initial_state",
"=",
"initial_state_fw",
",",
"dtype",
"=",
"dtype",
",",
"parallel_iterations",
"=",
"parallel_iterations",
",",
"swap_memory",
"=",
"swap_memory",
",",
"time_major",
"=",
"time_major",
",",
"scope",
"=",
"fw_scope",
")",
"# Backward direction",
"if",
"not",
"time_major",
":",
"time_axis",
"=",
"1",
"batch_axis",
"=",
"0",
"else",
":",
"time_axis",
"=",
"0",
"batch_axis",
"=",
"1",
"def",
"_reverse",
"(",
"input_",
",",
"seq_lengths",
",",
"seq_axis",
",",
"batch_axis",
")",
":",
"if",
"seq_lengths",
"is",
"not",
"None",
":",
"return",
"array_ops",
".",
"reverse_sequence",
"(",
"input",
"=",
"input_",
",",
"seq_lengths",
"=",
"seq_lengths",
",",
"seq_axis",
"=",
"seq_axis",
",",
"batch_axis",
"=",
"batch_axis",
")",
"else",
":",
"return",
"array_ops",
".",
"reverse",
"(",
"input_",
",",
"axis",
"=",
"[",
"seq_axis",
"]",
")",
"with",
"vs",
".",
"variable_scope",
"(",
"\"bw\"",
")",
"as",
"bw_scope",
":",
"def",
"_map_reverse",
"(",
"inp",
")",
":",
"return",
"_reverse",
"(",
"inp",
",",
"seq_lengths",
"=",
"sequence_length",
",",
"seq_axis",
"=",
"time_axis",
",",
"batch_axis",
"=",
"batch_axis",
")",
"inputs_reverse",
"=",
"nest",
".",
"map_structure",
"(",
"_map_reverse",
",",
"inputs",
")",
"tmp",
",",
"output_state_bw",
"=",
"dynamic_rnn",
"(",
"cell",
"=",
"cell_bw",
",",
"inputs",
"=",
"inputs_reverse",
",",
"sequence_length",
"=",
"sequence_length",
",",
"initial_state",
"=",
"initial_state_bw",
",",
"dtype",
"=",
"dtype",
",",
"parallel_iterations",
"=",
"parallel_iterations",
",",
"swap_memory",
"=",
"swap_memory",
",",
"time_major",
"=",
"time_major",
",",
"scope",
"=",
"bw_scope",
")",
"output_bw",
"=",
"_reverse",
"(",
"tmp",
",",
"seq_lengths",
"=",
"sequence_length",
",",
"seq_axis",
"=",
"time_axis",
",",
"batch_axis",
"=",
"batch_axis",
")",
"outputs",
"=",
"(",
"output_fw",
",",
"output_bw",
")",
"output_states",
"=",
"(",
"output_state_fw",
",",
"output_state_bw",
")",
"return",
"(",
"outputs",
",",
"output_states",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/rnn.py#L364-L514 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/python_gflags/gflags.py | python | FlagValues.__RemoveFlagFromDictByModule | (self, flags_by_module_dict, flag_obj) | Removes a flag object from a module -> list of flags dictionary.
Args:
flags_by_module_dict: A dictionary that maps module names to lists of
flags.
flag_obj: A flag object. | Removes a flag object from a module -> list of flags dictionary. | [
"Removes",
"a",
"flag",
"object",
"from",
"a",
"module",
"-",
">",
"list",
"of",
"flags",
"dictionary",
"."
] | def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj):
"""Removes a flag object from a module -> list of flags dictionary.
Args:
flags_by_module_dict: A dictionary that maps module names to lists of
flags.
flag_obj: A flag object.
"""
for unused_module, flags_in_module in flags_by_module_dict.iteritems():
# while (as opposed to if) takes care of multiple occurrences of a
# flag in the list for the same module.
while flag_obj in flags_in_module:
flags_in_module.remove(flag_obj) | [
"def",
"__RemoveFlagFromDictByModule",
"(",
"self",
",",
"flags_by_module_dict",
",",
"flag_obj",
")",
":",
"for",
"unused_module",
",",
"flags_in_module",
"in",
"flags_by_module_dict",
".",
"iteritems",
"(",
")",
":",
"# while (as opposed to if) takes care of multiple occurrences of a",
"# flag in the list for the same module.",
"while",
"flag_obj",
"in",
"flags_in_module",
":",
"flags_in_module",
".",
"remove",
"(",
"flag_obj",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags.py#L1158-L1170 | ||
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/win/Source/bin/jinja2/filters.py | python | do_forceescape | (value) | return escape(unicode(value)) | Enforce HTML escaping. This will probably double escape variables. | Enforce HTML escaping. This will probably double escape variables. | [
"Enforce",
"HTML",
"escaping",
".",
"This",
"will",
"probably",
"double",
"escape",
"variables",
"."
] | def do_forceescape(value):
"""Enforce HTML escaping. This will probably double escape variables."""
if hasattr(value, '__html__'):
value = value.__html__()
return escape(unicode(value)) | [
"def",
"do_forceescape",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'__html__'",
")",
":",
"value",
"=",
"value",
".",
"__html__",
"(",
")",
"return",
"escape",
"(",
"unicode",
"(",
"value",
")",
")"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/filters.py#L44-L48 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/activex/_activex_ex.py | python | GernerateAXModule.__init__ | (self, ax, className, modulePath, moduleName=None, verbose=False) | Make a Python module file with a class that has been specialized
for the AcitveX object.
ax An instance of the ActiveXWindow class
className The name to use for the new class
modulePath The path where the new module should be written to
moduleName The name of the .py file to create. If not given
then the className will be used. | Make a Python module file with a class that has been specialized
for the AcitveX object. | [
"Make",
"a",
"Python",
"module",
"file",
"with",
"a",
"class",
"that",
"has",
"been",
"specialized",
"for",
"the",
"AcitveX",
"object",
"."
] | def __init__(self, ax, className, modulePath, moduleName=None, verbose=False):
"""
Make a Python module file with a class that has been specialized
for the AcitveX object.
ax An instance of the ActiveXWindow class
className The name to use for the new class
modulePath The path where the new module should be written to
moduleName The name of the .py file to create. If not given
then the className will be used.
"""
import os
if moduleName is None:
moduleName = className + '.py'
filename = os.path.join(modulePath, moduleName)
if verbose:
print "Creating module in:", filename
print " ProgID: ", ax.GetCLSID().GetProgIDString()
print " CLSID: ", ax.GetCLSID().GetCLSIDString()
print
self.mf = file(filename, "w")
self.WriteFileHeader(ax)
self.WriteEvents(ax)
self.WriteClassHeader(ax, className)
self.WriteMethods(ax)
self.WriteProperties(ax)
self.WriteDocs(ax)
self.mf.close()
del self.mf | [
"def",
"__init__",
"(",
"self",
",",
"ax",
",",
"className",
",",
"modulePath",
",",
"moduleName",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"os",
"if",
"moduleName",
"is",
"None",
":",
"moduleName",
"=",
"className",
"+",
"'.py'",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"modulePath",
",",
"moduleName",
")",
"if",
"verbose",
":",
"print",
"\"Creating module in:\"",
",",
"filename",
"print",
"\" ProgID: \"",
",",
"ax",
".",
"GetCLSID",
"(",
")",
".",
"GetProgIDString",
"(",
")",
"print",
"\" CLSID: \"",
",",
"ax",
".",
"GetCLSID",
"(",
")",
".",
"GetCLSIDString",
"(",
")",
"print",
"self",
".",
"mf",
"=",
"file",
"(",
"filename",
",",
"\"w\"",
")",
"self",
".",
"WriteFileHeader",
"(",
"ax",
")",
"self",
".",
"WriteEvents",
"(",
"ax",
")",
"self",
".",
"WriteClassHeader",
"(",
"ax",
",",
"className",
")",
"self",
".",
"WriteMethods",
"(",
"ax",
")",
"self",
".",
"WriteProperties",
"(",
"ax",
")",
"self",
".",
"WriteDocs",
"(",
"ax",
")",
"self",
".",
"mf",
".",
"close",
"(",
")",
"del",
"self",
".",
"mf"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/activex/_activex_ex.py#L56-L84 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | AuiNotebook.OnTabBeginDrag | (self, event) | Handles the ``EVT_AUINOTEBOOK_BEGIN_DRAG`` event for :class:`AuiNotebook`.
:param `event`: a :class:`AuiNotebookEvent` event to be processed. | Handles the ``EVT_AUINOTEBOOK_BEGIN_DRAG`` event for :class:`AuiNotebook`. | [
"Handles",
"the",
"EVT_AUINOTEBOOK_BEGIN_DRAG",
"event",
"for",
":",
"class",
":",
"AuiNotebook",
"."
] | def OnTabBeginDrag(self, event):
"""
Handles the ``EVT_AUINOTEBOOK_BEGIN_DRAG`` event for :class:`AuiNotebook`.
:param `event`: a :class:`AuiNotebookEvent` event to be processed.
"""
tabs = event.GetEventObject()
if not tabs.GetEnabled(event.GetSelection()):
return
self._last_drag_x = 0 | [
"def",
"OnTabBeginDrag",
"(",
"self",
",",
"event",
")",
":",
"tabs",
"=",
"event",
".",
"GetEventObject",
"(",
")",
"if",
"not",
"tabs",
".",
"GetEnabled",
"(",
"event",
".",
"GetSelection",
"(",
")",
")",
":",
"return",
"self",
".",
"_last_drag_x",
"=",
"0"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L4552-L4563 | ||
MVIG-SJTU/RMPE | 5188c230ec800c12be7369c3619615bc9b020aa4 | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | PascalMultilabelDataLayerSync.backward | (self, top, propagate_down, bottom) | These layers does not back propagate | These layers does not back propagate | [
"These",
"layers",
"does",
"not",
"back",
"propagate"
] | def backward(self, top, propagate_down, bottom):
"""
These layers does not back propagate
"""
pass | [
"def",
"backward",
"(",
"self",
",",
"top",
",",
"propagate_down",
",",
"bottom",
")",
":",
"pass"
] | https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L74-L78 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftgeoutils/circles_incomplete.py | python | circlefrom1Circle2Points | (circle, point1, point2) | Do nothing. Placeholder function. Needs to be implemented. | Do nothing. Placeholder function. Needs to be implemented. | [
"Do",
"nothing",
".",
"Placeholder",
"function",
".",
"Needs",
"to",
"be",
"implemented",
"."
] | def circlefrom1Circle2Points(circle, point1, point2):
"""Do nothing. Placeholder function. Needs to be implemented."""
_wrn("Placeholder function, does nothing.") | [
"def",
"circlefrom1Circle2Points",
"(",
"circle",
",",
"point1",
",",
"point2",
")",
":",
"_wrn",
"(",
"\"Placeholder function, does nothing.\"",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftgeoutils/circles_incomplete.py#L134-L136 | ||
shader-slang/slang | b8982fcf43b86c1e39dcc3dd19bff2821633eda6 | external/vulkan/registry/generator.py | python | OutputGenerator.getMaxCParamTypeLength | (self, info) | return max(lengths) | Return the length of the longest type field for a member/parameter.
- info - TypeInfo or CommandInfo. | Return the length of the longest type field for a member/parameter. | [
"Return",
"the",
"length",
"of",
"the",
"longest",
"type",
"field",
"for",
"a",
"member",
"/",
"parameter",
"."
] | def getMaxCParamTypeLength(self, info):
"""Return the length of the longest type field for a member/parameter.
- info - TypeInfo or CommandInfo.
"""
lengths = (self.getCParamTypeLength(member)
for member in info.getMembers())
return max(lengths) | [
"def",
"getMaxCParamTypeLength",
"(",
"self",
",",
"info",
")",
":",
"lengths",
"=",
"(",
"self",
".",
"getCParamTypeLength",
"(",
"member",
")",
"for",
"member",
"in",
"info",
".",
"getMembers",
"(",
")",
")",
"return",
"max",
"(",
"lengths",
")"
] | https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/generator.py#L831-L838 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/training/input.py | python | match_filenames_once | (pattern, name=None) | Save the list of files matching pattern, so it is only computed once.
Args:
pattern: A file pattern (glob), or 1D tensor of file patterns.
name: A name for the operations (optional).
Returns:
A variable that is initialized to the list of files matching the pattern(s). | Save the list of files matching pattern, so it is only computed once. | [
"Save",
"the",
"list",
"of",
"files",
"matching",
"pattern",
"so",
"it",
"is",
"only",
"computed",
"once",
"."
] | def match_filenames_once(pattern, name=None):
"""Save the list of files matching pattern, so it is only computed once.
Args:
pattern: A file pattern (glob), or 1D tensor of file patterns.
name: A name for the operations (optional).
Returns:
A variable that is initialized to the list of files matching the pattern(s).
"""
with ops.name_scope(name, "matching_filenames", [pattern]) as name:
return vs.variable(
name=name, initial_value=io_ops.matching_files(pattern),
trainable=False, validate_shape=False,
collections=[ops.GraphKeys.LOCAL_VARIABLES]) | [
"def",
"match_filenames_once",
"(",
"pattern",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"matching_filenames\"",
",",
"[",
"pattern",
"]",
")",
"as",
"name",
":",
"return",
"vs",
".",
"variable",
"(",
"name",
"=",
"name",
",",
"initial_value",
"=",
"io_ops",
".",
"matching_files",
"(",
"pattern",
")",
",",
"trainable",
"=",
"False",
",",
"validate_shape",
"=",
"False",
",",
"collections",
"=",
"[",
"ops",
".",
"GraphKeys",
".",
"LOCAL_VARIABLES",
"]",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/input.py#L56-L70 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/ndarray/ndarray.py | python | NDArray.__pow__ | (self, other) | return power(self, other) | x.__pow__(y) <=> x**y <=> mx.nd.power(x,y) | x.__pow__(y) <=> x**y <=> mx.nd.power(x,y) | [
"x",
".",
"__pow__",
"(",
"y",
")",
"<",
"=",
">",
"x",
"**",
"y",
"<",
"=",
">",
"mx",
".",
"nd",
".",
"power",
"(",
"x",
"y",
")"
] | def __pow__(self, other):
"""x.__pow__(y) <=> x**y <=> mx.nd.power(x,y) """
return power(self, other) | [
"def",
"__pow__",
"(",
"self",
",",
"other",
")",
":",
"return",
"power",
"(",
"self",
",",
"other",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L314-L316 | |
numenta/nupic.core | 949950cf2c6d8d894c7eabfa2860aae679bf91f7 | bindings/py/src/nupic/bindings/check.py | python | checkMain | () | This script performs two checks. First it tries to import nupic.bindings
to check that it is correctly installed. Then it tries to import the C
extensions under nupic.bindings. Appropriate user-friendly status messages
are printed depend on the outcome. | This script performs two checks. First it tries to import nupic.bindings
to check that it is correctly installed. Then it tries to import the C
extensions under nupic.bindings. Appropriate user-friendly status messages
are printed depend on the outcome. | [
"This",
"script",
"performs",
"two",
"checks",
".",
"First",
"it",
"tries",
"to",
"import",
"nupic",
".",
"bindings",
"to",
"check",
"that",
"it",
"is",
"correctly",
"installed",
".",
"Then",
"it",
"tries",
"to",
"import",
"the",
"C",
"extensions",
"under",
"nupic",
".",
"bindings",
".",
"Appropriate",
"user",
"-",
"friendly",
"status",
"messages",
"are",
"printed",
"depend",
"on",
"the",
"outcome",
"."
] | def checkMain():
"""
This script performs two checks. First it tries to import nupic.bindings
to check that it is correctly installed. Then it tries to import the C
extensions under nupic.bindings. Appropriate user-friendly status messages
are printed depend on the outcome.
"""
try:
checkImportBindingsInstalled()
except ImportError as e:
print ("Could not import nupic.bindings. It must be installed before use. "
"Error message:")
print e.message
return
try:
checkImportBindingsExtensions()
except ImportError as e:
print ("Could not import C extensions for nupic.bindings. Make sure that "
"the package was properly installed. Error message:")
print e.message
return
print "Successfully imported nupic.bindings." | [
"def",
"checkMain",
"(",
")",
":",
"try",
":",
"checkImportBindingsInstalled",
"(",
")",
"except",
"ImportError",
"as",
"e",
":",
"print",
"(",
"\"Could not import nupic.bindings. It must be installed before use. \"",
"\"Error message:\"",
")",
"print",
"e",
".",
"message",
"return",
"try",
":",
"checkImportBindingsExtensions",
"(",
")",
"except",
"ImportError",
"as",
"e",
":",
"print",
"(",
"\"Could not import C extensions for nupic.bindings. Make sure that \"",
"\"the package was properly installed. Error message:\"",
")",
"print",
"e",
".",
"message",
"return",
"print",
"\"Successfully imported nupic.bindings.\""
] | https://github.com/numenta/nupic.core/blob/949950cf2c6d8d894c7eabfa2860aae679bf91f7/bindings/py/src/nupic/bindings/check.py#L44-L67 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/internals/managers.py | python | BlockManager.set | (self, item, value) | Set new item in-place. Does not consolidate. Adds new Block if not
contained in the current set of items | Set new item in-place. Does not consolidate. Adds new Block if not
contained in the current set of items | [
"Set",
"new",
"item",
"in",
"-",
"place",
".",
"Does",
"not",
"consolidate",
".",
"Adds",
"new",
"Block",
"if",
"not",
"contained",
"in",
"the",
"current",
"set",
"of",
"items"
] | def set(self, item, value):
"""
Set new item in-place. Does not consolidate. Adds new Block if not
contained in the current set of items
"""
# FIXME: refactor, clearly separate broadcasting & zip-like assignment
# can prob also fix the various if tests for sparse/categorical
# TODO(EA): Remove an is_extension_ when all extension types satisfy
# the interface
value_is_extension_type = (is_extension_type(value) or
is_extension_array_dtype(value))
# categorical/spares/datetimetz
if value_is_extension_type:
def value_getitem(placement):
return value
else:
if value.ndim == self.ndim - 1:
value = _safe_reshape(value, (1,) + value.shape)
def value_getitem(placement):
return value
else:
def value_getitem(placement):
return value[placement.indexer]
if value.shape[1:] != self.shape[1:]:
raise AssertionError('Shape of new values must be compatible '
'with manager shape')
try:
loc = self.items.get_loc(item)
except KeyError:
# This item wasn't present, just insert at end
self.insert(len(self.items), item, value)
return
if isinstance(loc, int):
loc = [loc]
blknos = self._blknos[loc]
blklocs = self._blklocs[loc].copy()
unfit_mgr_locs = []
unfit_val_locs = []
removed_blknos = []
for blkno, val_locs in libinternals.get_blkno_placements(blknos,
self.nblocks,
group=True):
blk = self.blocks[blkno]
blk_locs = blklocs[val_locs.indexer]
if blk.should_store(value):
blk.set(blk_locs, value_getitem(val_locs))
else:
unfit_mgr_locs.append(blk.mgr_locs.as_array[blk_locs])
unfit_val_locs.append(val_locs)
# If all block items are unfit, schedule the block for removal.
if len(val_locs) == len(blk.mgr_locs):
removed_blknos.append(blkno)
else:
self._blklocs[blk.mgr_locs.indexer] = -1
blk.delete(blk_locs)
self._blklocs[blk.mgr_locs.indexer] = np.arange(len(blk))
if len(removed_blknos):
# Remove blocks & update blknos accordingly
is_deleted = np.zeros(self.nblocks, dtype=np.bool_)
is_deleted[removed_blknos] = True
new_blknos = np.empty(self.nblocks, dtype=np.int64)
new_blknos.fill(-1)
new_blknos[~is_deleted] = np.arange(self.nblocks -
len(removed_blknos))
self._blknos = algos.take_1d(new_blknos, self._blknos, axis=0,
allow_fill=False)
self.blocks = tuple(blk for i, blk in enumerate(self.blocks)
if i not in set(removed_blknos))
if unfit_val_locs:
unfit_mgr_locs = np.concatenate(unfit_mgr_locs)
unfit_count = len(unfit_mgr_locs)
new_blocks = []
if value_is_extension_type:
# This code (ab-)uses the fact that sparse blocks contain only
# one item.
new_blocks.extend(
make_block(values=value.copy(), ndim=self.ndim,
placement=slice(mgr_loc, mgr_loc + 1))
for mgr_loc in unfit_mgr_locs)
self._blknos[unfit_mgr_locs] = (np.arange(unfit_count) +
len(self.blocks))
self._blklocs[unfit_mgr_locs] = 0
else:
# unfit_val_locs contains BlockPlacement objects
unfit_val_items = unfit_val_locs[0].append(unfit_val_locs[1:])
new_blocks.append(
make_block(values=value_getitem(unfit_val_items),
ndim=self.ndim, placement=unfit_mgr_locs))
self._blknos[unfit_mgr_locs] = len(self.blocks)
self._blklocs[unfit_mgr_locs] = np.arange(unfit_count)
self.blocks += tuple(new_blocks)
# Newly created block's dtype may already be present.
self._known_consolidated = False | [
"def",
"set",
"(",
"self",
",",
"item",
",",
"value",
")",
":",
"# FIXME: refactor, clearly separate broadcasting & zip-like assignment",
"# can prob also fix the various if tests for sparse/categorical",
"# TODO(EA): Remove an is_extension_ when all extension types satisfy",
"# the interface",
"value_is_extension_type",
"=",
"(",
"is_extension_type",
"(",
"value",
")",
"or",
"is_extension_array_dtype",
"(",
"value",
")",
")",
"# categorical/spares/datetimetz",
"if",
"value_is_extension_type",
":",
"def",
"value_getitem",
"(",
"placement",
")",
":",
"return",
"value",
"else",
":",
"if",
"value",
".",
"ndim",
"==",
"self",
".",
"ndim",
"-",
"1",
":",
"value",
"=",
"_safe_reshape",
"(",
"value",
",",
"(",
"1",
",",
")",
"+",
"value",
".",
"shape",
")",
"def",
"value_getitem",
"(",
"placement",
")",
":",
"return",
"value",
"else",
":",
"def",
"value_getitem",
"(",
"placement",
")",
":",
"return",
"value",
"[",
"placement",
".",
"indexer",
"]",
"if",
"value",
".",
"shape",
"[",
"1",
":",
"]",
"!=",
"self",
".",
"shape",
"[",
"1",
":",
"]",
":",
"raise",
"AssertionError",
"(",
"'Shape of new values must be compatible '",
"'with manager shape'",
")",
"try",
":",
"loc",
"=",
"self",
".",
"items",
".",
"get_loc",
"(",
"item",
")",
"except",
"KeyError",
":",
"# This item wasn't present, just insert at end",
"self",
".",
"insert",
"(",
"len",
"(",
"self",
".",
"items",
")",
",",
"item",
",",
"value",
")",
"return",
"if",
"isinstance",
"(",
"loc",
",",
"int",
")",
":",
"loc",
"=",
"[",
"loc",
"]",
"blknos",
"=",
"self",
".",
"_blknos",
"[",
"loc",
"]",
"blklocs",
"=",
"self",
".",
"_blklocs",
"[",
"loc",
"]",
".",
"copy",
"(",
")",
"unfit_mgr_locs",
"=",
"[",
"]",
"unfit_val_locs",
"=",
"[",
"]",
"removed_blknos",
"=",
"[",
"]",
"for",
"blkno",
",",
"val_locs",
"in",
"libinternals",
".",
"get_blkno_placements",
"(",
"blknos",
",",
"self",
".",
"nblocks",
",",
"group",
"=",
"True",
")",
":",
"blk",
"=",
"self",
".",
"blocks",
"[",
"blkno",
"]",
"blk_locs",
"=",
"blklocs",
"[",
"val_locs",
".",
"indexer",
"]",
"if",
"blk",
".",
"should_store",
"(",
"value",
")",
":",
"blk",
".",
"set",
"(",
"blk_locs",
",",
"value_getitem",
"(",
"val_locs",
")",
")",
"else",
":",
"unfit_mgr_locs",
".",
"append",
"(",
"blk",
".",
"mgr_locs",
".",
"as_array",
"[",
"blk_locs",
"]",
")",
"unfit_val_locs",
".",
"append",
"(",
"val_locs",
")",
"# If all block items are unfit, schedule the block for removal.",
"if",
"len",
"(",
"val_locs",
")",
"==",
"len",
"(",
"blk",
".",
"mgr_locs",
")",
":",
"removed_blknos",
".",
"append",
"(",
"blkno",
")",
"else",
":",
"self",
".",
"_blklocs",
"[",
"blk",
".",
"mgr_locs",
".",
"indexer",
"]",
"=",
"-",
"1",
"blk",
".",
"delete",
"(",
"blk_locs",
")",
"self",
".",
"_blklocs",
"[",
"blk",
".",
"mgr_locs",
".",
"indexer",
"]",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"blk",
")",
")",
"if",
"len",
"(",
"removed_blknos",
")",
":",
"# Remove blocks & update blknos accordingly",
"is_deleted",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"nblocks",
",",
"dtype",
"=",
"np",
".",
"bool_",
")",
"is_deleted",
"[",
"removed_blknos",
"]",
"=",
"True",
"new_blknos",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"nblocks",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"new_blknos",
".",
"fill",
"(",
"-",
"1",
")",
"new_blknos",
"[",
"~",
"is_deleted",
"]",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"nblocks",
"-",
"len",
"(",
"removed_blknos",
")",
")",
"self",
".",
"_blknos",
"=",
"algos",
".",
"take_1d",
"(",
"new_blknos",
",",
"self",
".",
"_blknos",
",",
"axis",
"=",
"0",
",",
"allow_fill",
"=",
"False",
")",
"self",
".",
"blocks",
"=",
"tuple",
"(",
"blk",
"for",
"i",
",",
"blk",
"in",
"enumerate",
"(",
"self",
".",
"blocks",
")",
"if",
"i",
"not",
"in",
"set",
"(",
"removed_blknos",
")",
")",
"if",
"unfit_val_locs",
":",
"unfit_mgr_locs",
"=",
"np",
".",
"concatenate",
"(",
"unfit_mgr_locs",
")",
"unfit_count",
"=",
"len",
"(",
"unfit_mgr_locs",
")",
"new_blocks",
"=",
"[",
"]",
"if",
"value_is_extension_type",
":",
"# This code (ab-)uses the fact that sparse blocks contain only",
"# one item.",
"new_blocks",
".",
"extend",
"(",
"make_block",
"(",
"values",
"=",
"value",
".",
"copy",
"(",
")",
",",
"ndim",
"=",
"self",
".",
"ndim",
",",
"placement",
"=",
"slice",
"(",
"mgr_loc",
",",
"mgr_loc",
"+",
"1",
")",
")",
"for",
"mgr_loc",
"in",
"unfit_mgr_locs",
")",
"self",
".",
"_blknos",
"[",
"unfit_mgr_locs",
"]",
"=",
"(",
"np",
".",
"arange",
"(",
"unfit_count",
")",
"+",
"len",
"(",
"self",
".",
"blocks",
")",
")",
"self",
".",
"_blklocs",
"[",
"unfit_mgr_locs",
"]",
"=",
"0",
"else",
":",
"# unfit_val_locs contains BlockPlacement objects",
"unfit_val_items",
"=",
"unfit_val_locs",
"[",
"0",
"]",
".",
"append",
"(",
"unfit_val_locs",
"[",
"1",
":",
"]",
")",
"new_blocks",
".",
"append",
"(",
"make_block",
"(",
"values",
"=",
"value_getitem",
"(",
"unfit_val_items",
")",
",",
"ndim",
"=",
"self",
".",
"ndim",
",",
"placement",
"=",
"unfit_mgr_locs",
")",
")",
"self",
".",
"_blknos",
"[",
"unfit_mgr_locs",
"]",
"=",
"len",
"(",
"self",
".",
"blocks",
")",
"self",
".",
"_blklocs",
"[",
"unfit_mgr_locs",
"]",
"=",
"np",
".",
"arange",
"(",
"unfit_count",
")",
"self",
".",
"blocks",
"+=",
"tuple",
"(",
"new_blocks",
")",
"# Newly created block's dtype may already be present.",
"self",
".",
"_known_consolidated",
"=",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/internals/managers.py#L1019-L1132 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/database.py | python | _Cache.__init__ | (self) | Initialise an instance. There is normally one for each DistributionPath. | Initialise an instance. There is normally one for each DistributionPath. | [
"Initialise",
"an",
"instance",
".",
"There",
"is",
"normally",
"one",
"for",
"each",
"DistributionPath",
"."
] | def __init__(self):
"""
Initialise an instance. There is normally one for each DistributionPath.
"""
self.name = {}
self.path = {}
self.generated = False | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"name",
"=",
"{",
"}",
"self",
".",
"path",
"=",
"{",
"}",
"self",
".",
"generated",
"=",
"False"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/database.py#L48-L54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.