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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | binary_search_tree/lowest_common_ancestor.py | python | lowest_common_ancestor | (root, a, b) | return root | lowest common ancestor in BST | lowest common ancestor in BST | [
"lowest",
"common",
"ancestor",
"in",
"BST"
] | def lowest_common_ancestor(root, a, b):
""" lowest common ancestor in BST """
if root.data > max(a, b):
return lowest_common_ancestor(root.left, a, b)
if root.data < min(a, b):
return lowest_common_ancestor(root.right, a, b)
return root | [
"def",
"lowest_common_ancestor",
"(",
"root",
",",
"a",
",",
"b",
")",
":",
"if",
"root",
".",
"data",
">",
"max",
"(",
"a",
",",
"b",
")",
":",
"return",
"lowest_common_ancestor",
"(",
"root",
".",
"left",
",",
"a",
",",
"b",
")",
"if",
"root",
... | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/binary_search_tree/lowest_common_ancestor.py#L35-L41 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/threading.py | python | Semaphore.acquire | (self, blocking=True, timeout=None) | return rc | Acquire a semaphore, decrementing the internal counter by one.
When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called release() to
make it larger than zero. This is done with proper interlocking so that
if multiple acquire() calls are blocked, release() will wake exactly one
of them up. The implementation may pick one at random, so the order in
which blocked threads are awakened should not be relied on. There is no
return value in this case.
When invoked with blocking set to true, do the same thing as when called
without arguments, and return true.
When invoked with blocking set to false, do not block. If a call without
an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true.
When invoked with a timeout other than None, it will block for at
most timeout seconds. If acquire does not complete successfully in
that interval, return false. Return true otherwise. | Acquire a semaphore, decrementing the internal counter by one. | [
"Acquire",
"a",
"semaphore",
"decrementing",
"the",
"internal",
"counter",
"by",
"one",
"."
] | def acquire(self, blocking=True, timeout=None):
"""Acquire a semaphore, decrementing the internal counter by one.
When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called release() to
make it larger than zero. This is done with proper interlocking so that
if multiple acquire() calls are blocked, release() will wake exactly one
of them up. The implementation may pick one at random, so the order in
which blocked threads are awakened should not be relied on. There is no
return value in this case.
When invoked with blocking set to true, do the same thing as when called
without arguments, and return true.
When invoked with blocking set to false, do not block. If a call without
an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true.
When invoked with a timeout other than None, it will block for at
most timeout seconds. If acquire does not complete successfully in
that interval, return false. Return true otherwise.
"""
if not blocking and timeout is not None:
raise ValueError("can't specify timeout for non-blocking acquire")
rc = False
endtime = None
with self._cond:
while self._value == 0:
if not blocking:
break
if timeout is not None:
if endtime is None:
endtime = _time() + timeout
else:
timeout = endtime - _time()
if timeout <= 0:
break
self._cond.wait(timeout)
else:
self._value -= 1
rc = True
return rc | [
"def",
"acquire",
"(",
"self",
",",
"blocking",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"blocking",
"and",
"timeout",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"can't specify timeout for non-blocking acquire\"",
")",
"rc"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/threading.py#L404-L447 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/depot_tools/cpplint.py | python | CheckForNewlineAtEOF | (filename, lines, error) | Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error if there is no newline char at the end of the file. | [
"Logs",
"an",
"error",
"if",
"there",
"is",
"no",
"newline",
"char",
"at",
"the",
"end",
"of",
"the",
"file",
"."
] | def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.') | [
"def",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# The array lines() was created by adding two newlines to the",
"# original file (go figure), then splitting on \\n.",
"# To verify that the file ends in \\n, we just have to make sure the",
"# last-but-... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L1912-L1927 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/sorting.py | python | compress_group_index | (group_index, sort=True) | return comp_ids, obs_group_ids | Group_index is offsets into cartesian product of all possible labels. This
space can be huge, so this function compresses it, by computing offsets
(comp_ids) into the list of unique labels (obs_group_ids). | Group_index is offsets into cartesian product of all possible labels. This
space can be huge, so this function compresses it, by computing offsets
(comp_ids) into the list of unique labels (obs_group_ids). | [
"Group_index",
"is",
"offsets",
"into",
"cartesian",
"product",
"of",
"all",
"possible",
"labels",
".",
"This",
"space",
"can",
"be",
"huge",
"so",
"this",
"function",
"compresses",
"it",
"by",
"computing",
"offsets",
"(",
"comp_ids",
")",
"into",
"the",
"li... | def compress_group_index(group_index, sort=True):
"""
Group_index is offsets into cartesian product of all possible labels. This
space can be huge, so this function compresses it, by computing offsets
(comp_ids) into the list of unique labels (obs_group_ids).
"""
size_hint = min(len(group_index), hashtable._SIZE_HINT_LIMIT)
table = hashtable.Int64HashTable(size_hint)
group_index = ensure_int64(group_index)
# note, group labels come out ascending (ie, 1,2,3 etc)
comp_ids, obs_group_ids = table.get_labels_groupby(group_index)
if sort and len(obs_group_ids) > 0:
obs_group_ids, comp_ids = _reorder_by_uniques(obs_group_ids, comp_ids)
return comp_ids, obs_group_ids | [
"def",
"compress_group_index",
"(",
"group_index",
",",
"sort",
"=",
"True",
")",
":",
"size_hint",
"=",
"min",
"(",
"len",
"(",
"group_index",
")",
",",
"hashtable",
".",
"_SIZE_HINT_LIMIT",
")",
"table",
"=",
"hashtable",
".",
"Int64HashTable",
"(",
"size_... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/sorting.py#L366-L384 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/layer/rnn_cells.py | python | _check_is_tuple | (param_name, input_data, cls_name) | Internal function, used to check whether the input data is Tensor. | Internal function, used to check whether the input data is Tensor. | [
"Internal",
"function",
"used",
"to",
"check",
"whether",
"the",
"input",
"data",
"is",
"Tensor",
"."
] | def _check_is_tuple(param_name, input_data, cls_name):
"""Internal function, used to check whether the input data is Tensor."""
if input_data is not None and not isinstance(P.typeof(input_data), mstype.Tuple):
raise TypeError(f"For '{cls_name}', the '{param_name}' should be '{mstype.Tuple}', "
f"but got '{P.typeof(input_data)}'") | [
"def",
"_check_is_tuple",
"(",
"param_name",
",",
"input_data",
",",
"cls_name",
")",
":",
"if",
"input_data",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"P",
".",
"typeof",
"(",
"input_data",
")",
",",
"mstype",
".",
"Tuple",
")",
":",
"raise... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/rnn_cells.py#L44-L48 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/bintrees/bintrees/treemixin.py | python | TreeMixin.update | (self, *args) | T.update(E) -> None. Update T from E : for (k, v) in E: T[k] = v | T.update(E) -> None. Update T from E : for (k, v) in E: T[k] = v | [
"T",
".",
"update",
"(",
"E",
")",
"-",
">",
"None",
".",
"Update",
"T",
"from",
"E",
":",
"for",
"(",
"k",
"v",
")",
"in",
"E",
":",
"T",
"[",
"k",
"]",
"=",
"v"
] | def update(self, *args):
""" T.update(E) -> None. Update T from E : for (k, v) in E: T[k] = v """
for items in args:
try:
generator = items.items()
except AttributeError:
generator = iter(items)
for key, value in generator:
self.insert(key, value) | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"items",
"in",
"args",
":",
"try",
":",
"generator",
"=",
"items",
".",
"items",
"(",
")",
"except",
"AttributeError",
":",
"generator",
"=",
"iter",
"(",
"items",
")",
"for",
"key",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/bintrees/bintrees/treemixin.py#L380-L389 | ||
google/skia | 82d65d0487bd72f5f7332d002429ec2dc61d2463 | tools/jsondiff.py | python | GMDiffer._GetActualResults | (self, contents) | return result_dict | Returns the dictionary of actual results from a JSON string,
in this form:
{
'test1' : 14760033689012826769,
'test2' : 9151974350149210736,
...
}
We make these simplifying assumptions:
1. All results are of type JSONKEY_HASHTYPE_BITMAP_64BITMD5.
Any tests which violate those assumptions will cause an exception to
be raised.
Any tests for which we have no actual results will be left out of the
returned dictionary. | Returns the dictionary of actual results from a JSON string,
in this form: | [
"Returns",
"the",
"dictionary",
"of",
"actual",
"results",
"from",
"a",
"JSON",
"string",
"in",
"this",
"form",
":"
] | def _GetActualResults(self, contents):
"""Returns the dictionary of actual results from a JSON string,
in this form:
{
'test1' : 14760033689012826769,
'test2' : 9151974350149210736,
...
}
We make these simplifying assumptions:
1. All results are of type JSONKEY_HASHTYPE_BITMAP_64BITMD5.
Any tests which violate those assumptions will cause an exception to
be raised.
Any tests for which we have no actual results will be left out of the
returned dictionary.
"""
result_dict = {}
json_dict = gm_json.LoadFromString(contents)
all_result_types = json_dict[gm_json.JSONKEY_ACTUALRESULTS]
for result_type in all_result_types.keys():
results_of_this_type = all_result_types[result_type]
if results_of_this_type:
for test_name in results_of_this_type.keys():
digest_pair = results_of_this_type[test_name]
if (digest_pair[0] !=
gm_json.JSONKEY_HASHTYPE_BITMAP_64BITMD5):
raise ValueError(
'test %s has unsupported hashtype %s' % (
test_name, digest_pair[0]))
result_dict[test_name] = digest_pair[1]
return result_dict | [
"def",
"_GetActualResults",
"(",
"self",
",",
"contents",
")",
":",
"result_dict",
"=",
"{",
"}",
"json_dict",
"=",
"gm_json",
".",
"LoadFromString",
"(",
"contents",
")",
"all_result_types",
"=",
"json_dict",
"[",
"gm_json",
".",
"JSONKEY_ACTUALRESULTS",
"]",
... | https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/tools/jsondiff.py#L106-L139 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py | python | TNavigator.sety | (self, y) | Set the turtle's second coordinate to y
Argument:
y -- a number (integer or float)
Set the turtle's first coordinate to x, second coordinate remains
unchanged.
Example (for a Turtle instance named turtle):
>>> turtle.position()
(0.00, 40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00, -10.00) | Set the turtle's second coordinate to y | [
"Set",
"the",
"turtle",
"s",
"second",
"coordinate",
"to",
"y"
] | def sety(self, y):
"""Set the turtle's second coordinate to y
Argument:
y -- a number (integer or float)
Set the turtle's first coordinate to x, second coordinate remains
unchanged.
Example (for a Turtle instance named turtle):
>>> turtle.position()
(0.00, 40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00, -10.00)
"""
self._goto(Vec2D(self._position[0], y)) | [
"def",
"sety",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"_goto",
"(",
"Vec2D",
"(",
"self",
".",
"_position",
"[",
"0",
"]",
",",
"y",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L1725-L1741 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/markupsafe/__init__.py | python | _escape_argspec | (obj, iterable, escape) | return obj | Helper for various string-wrapped functions. | Helper for various string-wrapped functions. | [
"Helper",
"for",
"various",
"string",
"-",
"wrapped",
"functions",
"."
] | def _escape_argspec(obj, iterable, escape):
"""Helper for various string-wrapped functions."""
for key, value in iterable:
if hasattr(value, '__html__') or isinstance(value, string_types):
obj[key] = escape(value)
return obj | [
"def",
"_escape_argspec",
"(",
"obj",
",",
"iterable",
",",
"escape",
")",
":",
"for",
"key",
",",
"value",
"in",
"iterable",
":",
"if",
"hasattr",
"(",
"value",
",",
"'__html__'",
")",
"or",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/markupsafe/__init__.py#L203-L208 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Window.SetMinSize | (*args, **kwargs) | return _core_.Window_SetMinSize(*args, **kwargs) | SetMinSize(self, Size minSize)
A more convenient method than `SetSizeHints` for setting just the
min size. | SetMinSize(self, Size minSize) | [
"SetMinSize",
"(",
"self",
"Size",
"minSize",
")"
] | def SetMinSize(*args, **kwargs):
"""
SetMinSize(self, Size minSize)
A more convenient method than `SetSizeHints` for setting just the
min size.
"""
return _core_.Window_SetMinSize(*args, **kwargs) | [
"def",
"SetMinSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_SetMinSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L9754-L9761 | |
google/tink | 59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14 | python/tink/streaming_aead/_streaming_aead.py | python | StreamingAead.new_decrypting_stream | (self, ciphertext_source: BinaryIO,
associated_data: bytes) | Returns a decrypting stream that reads from ciphertext_source.
The returned stream implements a readable but not seekable io.BufferedIOBase
interface. It only accepts binary data. For text, it needs to be wrapped
with io.TextIOWrapper.
The cipertext_source's read() method is expected to return an empty bytes
object if the stream is already at EOF. In the case where the stream is not
at EOF yet but no data is available at the moment, it is expected to either
block until data is available, return None or raise BlockingIOError.
The standard io.BufferedIOBase and io.RawIOBase base classes exhibit these
behaviours and are hence supported.
Args:
ciphertext_source: A readable binary file object from which ciphertext
will be read.
associated_data: Associated data to be used by the AEAD decryption. It
must match the associated_data supplied for the encryption.
Returns:
A readable implementation of the io.BufferedIOBase interface in blocking
mode that wraps around 'ciphertext_source', such that any bytes read from
the wrapper are AEAD-decrypted using 'associated_data' as associated
authenticated data.
Closing the wrapper also closes the ciphertext_source.
Raises:
tink.TinkError if the creation fails. | Returns a decrypting stream that reads from ciphertext_source. | [
"Returns",
"a",
"decrypting",
"stream",
"that",
"reads",
"from",
"ciphertext_source",
"."
] | def new_decrypting_stream(self, ciphertext_source: BinaryIO,
associated_data: bytes) -> BinaryIO:
"""Returns a decrypting stream that reads from ciphertext_source.
The returned stream implements a readable but not seekable io.BufferedIOBase
interface. It only accepts binary data. For text, it needs to be wrapped
with io.TextIOWrapper.
The cipertext_source's read() method is expected to return an empty bytes
object if the stream is already at EOF. In the case where the stream is not
at EOF yet but no data is available at the moment, it is expected to either
block until data is available, return None or raise BlockingIOError.
The standard io.BufferedIOBase and io.RawIOBase base classes exhibit these
behaviours and are hence supported.
Args:
ciphertext_source: A readable binary file object from which ciphertext
will be read.
associated_data: Associated data to be used by the AEAD decryption. It
must match the associated_data supplied for the encryption.
Returns:
A readable implementation of the io.BufferedIOBase interface in blocking
mode that wraps around 'ciphertext_source', such that any bytes read from
the wrapper are AEAD-decrypted using 'associated_data' as associated
authenticated data.
Closing the wrapper also closes the ciphertext_source.
Raises:
tink.TinkError if the creation fails.
"""
raise NotImplementedError() | [
"def",
"new_decrypting_stream",
"(",
"self",
",",
"ciphertext_source",
":",
"BinaryIO",
",",
"associated_data",
":",
"bytes",
")",
"->",
"BinaryIO",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/streaming_aead/_streaming_aead.py#L70-L100 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/util.py | python | FileOperator.copy_file | (self, infile, outfile, check=True) | Copy a file respecting dry-run and force flags. | Copy a file respecting dry-run and force flags. | [
"Copy",
"a",
"file",
"respecting",
"dry",
"-",
"run",
"and",
"force",
"flags",
"."
] | def copy_file(self, infile, outfile, check=True):
"""Copy a file respecting dry-run and force flags.
"""
self.ensure_dir(os.path.dirname(outfile))
logger.info('Copying %s to %s', infile, outfile)
if not self.dry_run:
msg = None
if check:
if os.path.islink(outfile):
msg = '%s is a symlink' % outfile
elif os.path.exists(outfile) and not os.path.isfile(outfile):
msg = '%s is a non-regular file' % outfile
if msg:
raise ValueError(msg + ' which would be overwritten')
shutil.copyfile(infile, outfile)
self.record_as_written(outfile) | [
"def",
"copy_file",
"(",
"self",
",",
"infile",
",",
"outfile",
",",
"check",
"=",
"True",
")",
":",
"self",
".",
"ensure_dir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"outfile",
")",
")",
"logger",
".",
"info",
"(",
"'Copying %s to %s'",
",",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/util.py#L513-L528 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/plugins/filebrowser/filebrowser/browser.py | python | FileBrowser2.SetMainWindow | (self, mainw) | Set the main window this browser belongs to.
@param mainw: MainWindow or None | Set the main window this browser belongs to.
@param mainw: MainWindow or None | [
"Set",
"the",
"main",
"window",
"this",
"browser",
"belongs",
"to",
".",
"@param",
"mainw",
":",
"MainWindow",
"or",
"None"
] | def SetMainWindow(self, mainw):
"""Set the main window this browser belongs to.
@param mainw: MainWindow or None
"""
self._mw = mainw | [
"def",
"SetMainWindow",
"(",
"self",
",",
"mainw",
")",
":",
"self",
".",
"_mw",
"=",
"mainw"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/filebrowser/filebrowser/browser.py#L961-L966 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/configure.py | python | host_arch_win | () | return matchup.get(arch, 'ia32') | Host architecture check using environ vars (better way to do this?) | Host architecture check using environ vars (better way to do this?) | [
"Host",
"architecture",
"check",
"using",
"environ",
"vars",
"(",
"better",
"way",
"to",
"do",
"this?",
")"
] | def host_arch_win():
"""Host architecture check using environ vars (better way to do this?)"""
observed_arch = os.environ.get('PROCESSOR_ARCHITECTURE', 'x86')
arch = os.environ.get('PROCESSOR_ARCHITEW6432', observed_arch)
matchup = {
'AMD64' : 'x64',
'x86' : 'ia32',
'arm' : 'arm',
'mips' : 'mips',
}
return matchup.get(arch, 'ia32') | [
"def",
"host_arch_win",
"(",
")",
":",
"observed_arch",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PROCESSOR_ARCHITECTURE'",
",",
"'x86'",
")",
"arch",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PROCESSOR_ARCHITEW6432'",
",",
"observed_arch",
")",
"mat... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/configure.py#L973-L986 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_graphs.py | python | DFSGraphTracer.__init__ | (self,
input_lists,
skip_node_names=None,
destination_node_name=None) | Constructor of _DFSGraphTracer.
Args:
input_lists: A list of dicts. Each dict is an adjacency (input) map from
the recipient node name as the key and the list of input node names
as the value.
skip_node_names: Optional: a list of node names to skip tracing.
destination_node_name: Optional: destination node name. If not `None`, it
should be the name of a destination not as a str and the graph tracing
will raise GraphTracingReachedDestination as soon as the node has been
reached.
Raises:
GraphTracingReachedDestination: if stop_at_node_name is not None and
the specified node is reached. | Constructor of _DFSGraphTracer. | [
"Constructor",
"of",
"_DFSGraphTracer",
"."
] | def __init__(self,
input_lists,
skip_node_names=None,
destination_node_name=None):
"""Constructor of _DFSGraphTracer.
Args:
input_lists: A list of dicts. Each dict is an adjacency (input) map from
the recipient node name as the key and the list of input node names
as the value.
skip_node_names: Optional: a list of node names to skip tracing.
destination_node_name: Optional: destination node name. If not `None`, it
should be the name of a destination not as a str and the graph tracing
will raise GraphTracingReachedDestination as soon as the node has been
reached.
Raises:
GraphTracingReachedDestination: if stop_at_node_name is not None and
the specified node is reached.
"""
self._input_lists = input_lists
self._skip_node_names = skip_node_names
self._inputs = []
self._visited_nodes = []
self._depth_count = 0
self._depth_list = []
self._destination_node_name = destination_node_name | [
"def",
"__init__",
"(",
"self",
",",
"input_lists",
",",
"skip_node_names",
"=",
"None",
",",
"destination_node_name",
"=",
"None",
")",
":",
"self",
".",
"_input_lists",
"=",
"input_lists",
"self",
".",
"_skip_node_names",
"=",
"skip_node_names",
"self",
".",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_graphs.py#L149-L178 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/FilterEvents/eventFilterGUI.py | python | MainWindow.load_File | (self) | Load the file by file name or run number | Load the file by file name or run number | [
"Load",
"the",
"file",
"by",
"file",
"name",
"or",
"run",
"number"
] | def load_File(self):
""" Load the file by file name or run number
"""
# Get file name from line editor
filename = str(self.ui.lineEdit.text())
dataws = self._loadFile(str(filename))
if dataws is None:
error_msg = 'Unable to locate run {} in default directory {}.'.format(filename, self._defaultdir)
Logger("Filter_Events").error(error_msg)
self._setErrorMsg(error_msg)
else:
self._importDataWorkspace(dataws)
self._defaultdir = os.path.dirname(str(filename))
# Reset GUI
self._resetGUI(resetfilerun=False) | [
"def",
"load_File",
"(",
"self",
")",
":",
"# Get file name from line editor",
"filename",
"=",
"str",
"(",
"self",
".",
"ui",
".",
"lineEdit",
".",
"text",
"(",
")",
")",
"dataws",
"=",
"self",
".",
"_loadFile",
"(",
"str",
"(",
"filename",
")",
")",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/FilterEvents/eventFilterGUI.py#L587-L603 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextBuffer.ClearEventHandlers | (*args, **kwargs) | return _richtext.RichTextBuffer_ClearEventHandlers(*args, **kwargs) | ClearEventHandlers(self) | ClearEventHandlers(self) | [
"ClearEventHandlers",
"(",
"self",
")"
] | def ClearEventHandlers(*args, **kwargs):
"""ClearEventHandlers(self)"""
return _richtext.RichTextBuffer_ClearEventHandlers(*args, **kwargs) | [
"def",
"ClearEventHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_ClearEventHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L2491-L2493 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | initializeDict | () | return ret | Do the dictionary mutex initialization. this function is
not thread safe, initialization should preferably be done
once at startup | Do the dictionary mutex initialization. this function is
not thread safe, initialization should preferably be done
once at startup | [
"Do",
"the",
"dictionary",
"mutex",
"initialization",
".",
"this",
"function",
"is",
"not",
"thread",
"safe",
"initialization",
"should",
"preferably",
"be",
"done",
"once",
"at",
"startup"
] | def initializeDict():
"""Do the dictionary mutex initialization. this function is
not thread safe, initialization should preferably be done
once at startup """
ret = libxml2mod.xmlInitializeDict()
return ret | [
"def",
"initializeDict",
"(",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlInitializeDict",
"(",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L1043-L1048 | |
lighttransport/nanort | 74063967336311f54ede5dffdfa242123825033b | deps/cpplint.py | python | _IncludeState.FindHeader | (self, header) | return -1 | Check if a header has already been included.
Args:
header: header to check.
Returns:
Line number of previous occurrence, or -1 if the header has not
been seen before. | Check if a header has already been included. | [
"Check",
"if",
"a",
"header",
"has",
"already",
"been",
"included",
"."
] | def FindHeader(self, header):
"""Check if a header has already been included.
Args:
header: header to check.
Returns:
Line number of previous occurrence, or -1 if the header has not
been seen before.
"""
for section_list in self.include_list:
for f in section_list:
if f[0] == header:
return f[1]
return -1 | [
"def",
"FindHeader",
"(",
"self",
",",
"header",
")",
":",
"for",
"section_list",
"in",
"self",
".",
"include_list",
":",
"for",
"f",
"in",
"section_list",
":",
"if",
"f",
"[",
"0",
"]",
"==",
"header",
":",
"return",
"f",
"[",
"1",
"]",
"return",
... | https://github.com/lighttransport/nanort/blob/74063967336311f54ede5dffdfa242123825033b/deps/cpplint.py#L631-L644 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Build.py | python | BuildContext.get_targets | (self) | return (min_grp, to_post) | Return the task generator corresponding to the 'targets' list, used by :py:meth:`waflib.Build.BuildContext.get_build_iterator`::
$ waf --targets=myprogram,myshlib | Return the task generator corresponding to the 'targets' list, used by :py:meth:`waflib.Build.BuildContext.get_build_iterator`:: | [
"Return",
"the",
"task",
"generator",
"corresponding",
"to",
"the",
"targets",
"list",
"used",
"by",
":",
"py",
":",
"meth",
":",
"waflib",
".",
"Build",
".",
"BuildContext",
".",
"get_build_iterator",
"::"
] | def get_targets(self):
"""
Return the task generator corresponding to the 'targets' list, used by :py:meth:`waflib.Build.BuildContext.get_build_iterator`::
$ waf --targets=myprogram,myshlib
"""
to_post = []
min_grp = 0
for name in self.targets.split(','):
tg = self.get_tgen_by_name(name)
if not tg:
raise Errors.WafError('target %r does not exist' % name)
m = self.get_group_idx(tg)
if m > min_grp:
min_grp = m
to_post = [tg]
elif m == min_grp:
to_post.append(tg)
return (min_grp, to_post) | [
"def",
"get_targets",
"(",
"self",
")",
":",
"to_post",
"=",
"[",
"]",
"min_grp",
"=",
"0",
"for",
"name",
"in",
"self",
".",
"targets",
".",
"split",
"(",
"','",
")",
":",
"tg",
"=",
"self",
".",
"get_tgen_by_name",
"(",
"name",
")",
"if",
"not",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Build.py#L716-L735 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/eager/context.py | python | Context.function_call_options | (self) | return self._thread_local_data.function_call_options | Returns function call options for current thread.
Note that the returned object is still referenced by the eager context.
Returns: the FunctionCallOptions for current thread. | Returns function call options for current thread. | [
"Returns",
"function",
"call",
"options",
"for",
"current",
"thread",
"."
] | def function_call_options(self):
"""Returns function call options for current thread.
Note that the returned object is still referenced by the eager context.
Returns: the FunctionCallOptions for current thread.
"""
if self._thread_local_data.function_call_options is None:
config = self.config
# Default to soft placement for functions unless specified
if self._soft_device_placement is None:
config.allow_soft_placement = True
self._thread_local_data.function_call_options = FunctionCallOptions(
config_proto=config)
return self._thread_local_data.function_call_options | [
"def",
"function_call_options",
"(",
"self",
")",
":",
"if",
"self",
".",
"_thread_local_data",
".",
"function_call_options",
"is",
"None",
":",
"config",
"=",
"self",
".",
"config",
"# Default to soft placement for functions unless specified",
"if",
"self",
".",
"_so... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L1236-L1252 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.WriteTarget | (self, spec, configs, deps, link_deps, part_of_all,
write_alias_target) | Write Makefile code to produce the final target of the gyp spec.
spec, configs: input from gyp.
deps, link_deps: dependency lists; see ComputeDeps()
part_of_all: flag indicating this target is part of 'all'
write_alias_target: flag indicating whether to create short aliases for this
target | Write Makefile code to produce the final target of the gyp spec. | [
"Write",
"Makefile",
"code",
"to",
"produce",
"the",
"final",
"target",
"of",
"the",
"gyp",
"spec",
"."
] | def WriteTarget(self, spec, configs, deps, link_deps, part_of_all,
write_alias_target):
"""Write Makefile code to produce the final target of the gyp spec.
spec, configs: input from gyp.
deps, link_deps: dependency lists; see ComputeDeps()
part_of_all: flag indicating this target is part of 'all'
write_alias_target: flag indicating whether to create short aliases for this
target
"""
self.WriteLn('### Rules for final target.')
if self.type != 'none':
self.WriteTargetFlags(spec, configs, link_deps)
settings = spec.get('aosp_build_settings', {})
if settings:
self.WriteLn('### Set directly by aosp_build_settings.')
for k, v in settings.iteritems():
if isinstance(v, list):
self.WriteList(v, k)
else:
self.WriteLn('%s := %s' % (k, make.QuoteIfNecessary(v)))
self.WriteLn('')
# Add to the set of targets which represent the gyp 'all' target. We use the
# name 'gyp_all_modules' as the Android build system doesn't allow the use
# of the Make target 'all' and because 'all_modules' is the equivalent of
# the Make target 'all' on Android.
if part_of_all and write_alias_target:
self.WriteLn('# Add target alias to "gyp_all_modules" target.')
self.WriteLn('.PHONY: gyp_all_modules')
self.WriteLn('gyp_all_modules: %s' % self.android_module)
self.WriteLn('')
# Add an alias from the gyp target name to the Android module name. This
# simplifies manual builds of the target, and is required by the test
# framework.
if self.target != self.android_module and write_alias_target:
self.WriteLn('# Alias gyp target name.')
self.WriteLn('.PHONY: %s' % self.target)
self.WriteLn('%s: %s' % (self.target, self.android_module))
self.WriteLn('')
# Add the command to trigger build of the target type depending
# on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY
# NOTE: This has to come last!
modifier = ''
if self.toolset == 'host':
modifier = 'HOST_'
if self.type == 'static_library':
self.WriteLn('include $(BUILD_%sSTATIC_LIBRARY)' % modifier)
elif self.type == 'shared_library':
self.WriteLn('LOCAL_PRELINK_MODULE := false')
self.WriteLn('include $(BUILD_%sSHARED_LIBRARY)' % modifier)
elif self.type == 'executable':
self.WriteLn('LOCAL_CXX_STL := libc++_static')
# Executables are for build and test purposes only, so they're installed
# to a directory that doesn't get included in the system image.
self.WriteLn('LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)')
self.WriteLn('include $(BUILD_%sEXECUTABLE)' % modifier)
else:
self.WriteLn('LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp')
self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true')
if self.toolset == 'target':
self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_VAR_PREFIX)')
else:
self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_HOST_VAR_PREFIX)')
self.WriteLn()
self.WriteLn('include $(BUILD_SYSTEM)/base_rules.mk')
self.WriteLn()
self.WriteLn('$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)')
self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"')
self.WriteLn('\t$(hide) mkdir -p $(dir $@)')
self.WriteLn('\t$(hide) touch $@')
self.WriteLn()
self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX :=') | [
"def",
"WriteTarget",
"(",
"self",
",",
"spec",
",",
"configs",
",",
"deps",
",",
"link_deps",
",",
"part_of_all",
",",
"write_alias_target",
")",
":",
"self",
".",
"WriteLn",
"(",
"'### Rules for final target.'",
")",
"if",
"self",
".",
"type",
"!=",
"'none... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L822-L898 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/oldnumeric/ma.py | python | MAError.__init__ | (self, args=None) | Create an exception | Create an exception | [
"Create",
"an",
"exception"
] | def __init__ (self, args=None):
"Create an exception"
# The .args attribute must be a tuple.
if not isinstance(args, tuple):
args = (args,)
self.args = args | [
"def",
"__init__",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"# The .args attribute must be a tuple.",
"if",
"not",
"isinstance",
"(",
"args",
",",
"tuple",
")",
":",
"args",
"=",
"(",
"args",
",",
")",
"self",
".",
"args",
"=",
"args"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L34-L40 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | mojo/public/bindings/pylib/parse/mojo_parser.py | python | Parser.p_unary_expression | (self, p) | unary_expression : primary_expression
| unary_operator expression | unary_expression : primary_expression
| unary_operator expression | [
"unary_expression",
":",
"primary_expression",
"|",
"unary_operator",
"expression"
] | def p_unary_expression(self, p):
"""unary_expression : primary_expression
| unary_operator expression"""
p[0] = ListFromConcat(*p[1:]) | [
"def",
"p_unary_expression",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ListFromConcat",
"(",
"*",
"p",
"[",
"1",
":",
"]",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/mojo/public/bindings/pylib/parse/mojo_parser.py#L285-L288 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | AnyButton.ShowsLabel | (*args, **kwargs) | return _controls_.AnyButton_ShowsLabel(*args, **kwargs) | ShowsLabel(self) -> bool | ShowsLabel(self) -> bool | [
"ShowsLabel",
"(",
"self",
")",
"-",
">",
"bool"
] | def ShowsLabel(*args, **kwargs):
"""ShowsLabel(self) -> bool"""
return _controls_.AnyButton_ShowsLabel(*args, **kwargs) | [
"def",
"ShowsLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"AnyButton_ShowsLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L163-L165 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSILLReduction.py | python | SANSILLReduction._check_wavelengths_match | (ws1, ws2) | Checks if the wavelength difference between the data is close enough
@param ws1 : workspace 1
@param ws2 : workspace 2 | Checks if the wavelength difference between the data is close enough | [
"Checks",
"if",
"the",
"wavelength",
"difference",
"between",
"the",
"data",
"is",
"close",
"enough"
] | def _check_wavelengths_match(ws1, ws2):
"""
Checks if the wavelength difference between the data is close enough
@param ws1 : workspace 1
@param ws2 : workspace 2
"""
tolerance = 0.01 # A
wavelength_1 = ws1.getRun().getLogData('wavelength').value
wavelength_2 = ws2.getRun().getLogData('wavelength').value
r1 = ws1.getRunNumber()
r2 = ws2.getRunNumber()
if fabs(wavelength_1 - wavelength_2) > tolerance:
logger.warning('Different wavelengths detected! {0}: {1}, {2}: {3}'.format(r1, wavelength_1,
r2, wavelength_2)) | [
"def",
"_check_wavelengths_match",
"(",
"ws1",
",",
"ws2",
")",
":",
"tolerance",
"=",
"0.01",
"# A",
"wavelength_1",
"=",
"ws1",
".",
"getRun",
"(",
")",
".",
"getLogData",
"(",
"'wavelength'",
")",
".",
"value",
"wavelength_2",
"=",
"ws2",
".",
"getRun",... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSILLReduction.py#L66-L79 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/inline_closurecall.py | python | InlineClosureCallPass._fix_stencil_neighborhood | (self, options) | return True | Extract the two-level tuple representing the stencil neighborhood
from the program IR to provide a tuple to StencilFunc. | Extract the two-level tuple representing the stencil neighborhood
from the program IR to provide a tuple to StencilFunc. | [
"Extract",
"the",
"two",
"-",
"level",
"tuple",
"representing",
"the",
"stencil",
"neighborhood",
"from",
"the",
"program",
"IR",
"to",
"provide",
"a",
"tuple",
"to",
"StencilFunc",
"."
] | def _fix_stencil_neighborhood(self, options):
"""
Extract the two-level tuple representing the stencil neighborhood
from the program IR to provide a tuple to StencilFunc.
"""
# build_tuple node with neighborhood for each dimension
dims_build_tuple = get_definition(self.func_ir, options['neighborhood'])
require(hasattr(dims_build_tuple, 'items'))
res = []
for window_var in dims_build_tuple.items:
win_build_tuple = get_definition(self.func_ir, window_var)
require(hasattr(win_build_tuple, 'items'))
res.append(tuple(win_build_tuple.items))
options['neighborhood'] = tuple(res)
return True | [
"def",
"_fix_stencil_neighborhood",
"(",
"self",
",",
"options",
")",
":",
"# build_tuple node with neighborhood for each dimension",
"dims_build_tuple",
"=",
"get_definition",
"(",
"self",
".",
"func_ir",
",",
"options",
"[",
"'neighborhood'",
"]",
")",
"require",
"(",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/inline_closurecall.py#L202-L216 | |
FlightGear/flightgear | cf4801e11c5b69b107f87191584eefda3c5a9b26 | scripts/python/TerraSync/terrasync/main.py | python | HTTPGetCallback.__init__ | (self, src, callback) | Initialize an HTTPGetCallback instance.
src -- a VirtualPath instance (corresponding to the path on
the server for which a GET request is to be issued)
callback -- a function taking two parameters: the URL (string)
and an http.client.HTTPResponse instance. When
invoked, the callback return value will be returned
by HTTPGetter.get(). | Initialize an HTTPGetCallback instance. | [
"Initialize",
"an",
"HTTPGetCallback",
"instance",
"."
] | def __init__(self, src, callback):
"""Initialize an HTTPGetCallback instance.
src -- a VirtualPath instance (corresponding to the path on
the server for which a GET request is to be issued)
callback -- a function taking two parameters: the URL (string)
and an http.client.HTTPResponse instance. When
invoked, the callback return value will be returned
by HTTPGetter.get().
"""
if callback is not None:
self.callback = callback
self.src = src | [
"def",
"__init__",
"(",
"self",
",",
"src",
",",
"callback",
")",
":",
"if",
"callback",
"is",
"not",
"None",
":",
"self",
".",
"callback",
"=",
"callback",
"self",
".",
"src",
"=",
"src"
] | https://github.com/FlightGear/flightgear/blob/cf4801e11c5b69b107f87191584eefda3c5a9b26/scripts/python/TerraSync/terrasync/main.py#L114-L127 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/shutil.py | python | copyfile | (src, dst, *, follow_symlinks=True) | return dst | Copy data from src to dst.
If follow_symlinks is not set and src is a symbolic link, a new
symlink will be created instead of copying the file it points to. | Copy data from src to dst. | [
"Copy",
"data",
"from",
"src",
"to",
"dst",
"."
] | def copyfile(src, dst, *, follow_symlinks=True):
"""Copy data from src to dst.
If follow_symlinks is not set and src is a symbolic link, a new
symlink will be created instead of copying the file it points to.
"""
if _samefile(src, dst):
raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)
if not follow_symlinks and os.path.islink(src):
os.symlink(os.readlink(src), dst)
else:
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
return dst | [
"def",
"copyfile",
"(",
"src",
",",
"dst",
",",
"*",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"if",
"_samefile",
"(",
"src",
",",
"dst",
")",
":",
"raise",
"SameFileError",
"(",
"\"{!r} and {!r} are the same file\"",
".",
"format",
"(",
"src",
",",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/shutil.py#L96-L123 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/map_fn.py | python | _result_flat_signature_to_batchable_tensor_spec | (result_flat_signature) | return tensor_specs | Converts result_flat_signature -> result_batchable_tensor_specs. | Converts result_flat_signature -> result_batchable_tensor_specs. | [
"Converts",
"result_flat_signature",
"-",
">",
"result_batchable_tensor_specs",
"."
] | def _result_flat_signature_to_batchable_tensor_spec(result_flat_signature):
"""Converts result_flat_signature -> result_batchable_tensor_specs."""
tensor_specs = []
for spec in result_flat_signature:
if not isinstance(spec, type_spec.BatchableTypeSpec):
raise TypeError("map_fn can not generate %s outputs" % (spec,))
tensor_specs.extend(spec._flat_tensor_specs) # pylint: disable=protected-access
return tensor_specs | [
"def",
"_result_flat_signature_to_batchable_tensor_spec",
"(",
"result_flat_signature",
")",
":",
"tensor_specs",
"=",
"[",
"]",
"for",
"spec",
"in",
"result_flat_signature",
":",
"if",
"not",
"isinstance",
"(",
"spec",
",",
"type_spec",
".",
"BatchableTypeSpec",
")",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/map_fn.py#L543-L550 | |
infinit/elle | a8154593c42743f45b9df09daf62b44630c24a02 | drake/src/drake/utils.py | python | camel_case | (s) | return re_map(lambda s: s[1].capitalize(),
re.compile('[-_][a-zA-Z]'), s) | Convert the given indentifier to camel case.
Converts dashes or underscore separated identifiers to camel case.
>>> camel_case('foo')
'foo'
>>> camel_case('foo-bar')
'fooBar'
>>> camel_case('foo_bar_baz_quux')
'fooBarBazQuux' | Convert the given indentifier to camel case. | [
"Convert",
"the",
"given",
"indentifier",
"to",
"camel",
"case",
"."
] | def camel_case(s):
"""Convert the given indentifier to camel case.
Converts dashes or underscore separated identifiers to camel case.
>>> camel_case('foo')
'foo'
>>> camel_case('foo-bar')
'fooBar'
>>> camel_case('foo_bar_baz_quux')
'fooBarBazQuux'
"""
return re_map(lambda s: s[1].capitalize(),
re.compile('[-_][a-zA-Z]'), s) | [
"def",
"camel_case",
"(",
"s",
")",
":",
"return",
"re_map",
"(",
"lambda",
"s",
":",
"s",
"[",
"1",
"]",
".",
"capitalize",
"(",
")",
",",
"re",
".",
"compile",
"(",
"'[-_][a-zA-Z]'",
")",
",",
"s",
")"
] | https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/utils.py#L28-L41 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/pytables.py | python | Table.process_axes | (self, obj, selection: Selection, columns=None) | return obj | process axes filters | process axes filters | [
"process",
"axes",
"filters"
] | def process_axes(self, obj, selection: Selection, columns=None):
"""process axes filters"""
# make a copy to avoid side effects
if columns is not None:
columns = list(columns)
# make sure to include levels if we have them
if columns is not None and self.is_multi_index:
assert isinstance(self.levels, list) # assured by is_multi_index
for n in self.levels:
if n not in columns:
columns.insert(0, n)
# reorder by any non_index_axes & limit to the select columns
for axis, labels in self.non_index_axes:
obj = _reindex_axis(obj, axis, labels, columns)
# apply the selection filters (but keep in the same order)
if selection.filter is not None:
for field, op, filt in selection.filter.format():
def process_filter(field, filt):
for axis_name in obj._AXIS_ORDERS:
axis_number = obj._get_axis_number(axis_name)
axis_values = obj._get_axis(axis_name)
assert axis_number is not None
# see if the field is the name of an axis
if field == axis_name:
# if we have a multi-index, then need to include
# the levels
if self.is_multi_index:
filt = filt.union(Index(self.levels))
takers = op(axis_values, filt)
return obj.loc(axis=axis_number)[takers]
# this might be the name of a file IN an axis
elif field in axis_values:
# we need to filter on this dimension
values = ensure_index(getattr(obj, field).values)
filt = ensure_index(filt)
# hack until we support reversed dim flags
if isinstance(obj, DataFrame):
axis_number = 1 - axis_number
takers = op(values, filt)
return obj.loc(axis=axis_number)[takers]
raise ValueError(f"cannot find the field [{field}] for filtering!")
obj = process_filter(field, filt)
return obj | [
"def",
"process_axes",
"(",
"self",
",",
"obj",
",",
"selection",
":",
"Selection",
",",
"columns",
"=",
"None",
")",
":",
"# make a copy to avoid side effects",
"if",
"columns",
"is",
"not",
"None",
":",
"columns",
"=",
"list",
"(",
"columns",
")",
"# make ... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/pytables.py#L4079-L4135 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | Type.is_restrict_qualified | (self) | return conf.lib.clang_isRestrictQualifiedType(self) | Determine whether a Type has the "restrict" qualifier set.
This does not look through typedefs that may have added "restrict" at
a different level. | Determine whether a Type has the "restrict" qualifier set. | [
"Determine",
"whether",
"a",
"Type",
"has",
"the",
"restrict",
"qualifier",
"set",
"."
] | def is_restrict_qualified(self):
"""Determine whether a Type has the "restrict" qualifier set.
This does not look through typedefs that may have added "restrict" at
a different level.
"""
return conf.lib.clang_isRestrictQualifiedType(self) | [
"def",
"is_restrict_qualified",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isRestrictQualifiedType",
"(",
"self",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L2279-L2285 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/linalg/_solvers.py | python | solve_continuous_lyapunov | (a, q) | return u.dot(y).dot(u.conj().T) | Solves the continuous Lyapunov equation :math:`AX + XA^H = Q`.
Uses the Bartels-Stewart algorithm to find :math:`X`.
Parameters
----------
a : array_like
A square matrix
q : array_like
Right-hand side square matrix
Returns
-------
x : ndarray
Solution to the continuous Lyapunov equation
See Also
--------
solve_discrete_lyapunov : computes the solution to the discrete-time
Lyapunov equation
solve_sylvester : computes the solution to the Sylvester equation
Notes
-----
The continuous Lyapunov equation is a special form of the Sylvester
equation, hence this solver relies on LAPACK routine ?TRSYL.
.. versionadded:: 0.11.0
Examples
--------
Given `a` and `q` solve for `x`:
>>> from scipy import linalg
>>> a = np.array([[-3, -2, 0], [-1, -1, 0], [0, -5, -1]])
>>> b = np.array([2, 4, -1])
>>> q = np.eye(3)
>>> x = linalg.solve_continuous_lyapunov(a, q)
>>> x
array([[ -0.75 , 0.875 , -3.75 ],
[ 0.875 , -1.375 , 5.3125],
[ -3.75 , 5.3125, -27.0625]])
>>> np.allclose(a.dot(x) + x.dot(a.T), q)
True | Solves the continuous Lyapunov equation :math:`AX + XA^H = Q`. | [
"Solves",
"the",
"continuous",
"Lyapunov",
"equation",
":",
"math",
":",
"AX",
"+",
"XA^H",
"=",
"Q",
"."
] | def solve_continuous_lyapunov(a, q):
"""
Solves the continuous Lyapunov equation :math:`AX + XA^H = Q`.
Uses the Bartels-Stewart algorithm to find :math:`X`.
Parameters
----------
a : array_like
A square matrix
q : array_like
Right-hand side square matrix
Returns
-------
x : ndarray
Solution to the continuous Lyapunov equation
See Also
--------
solve_discrete_lyapunov : computes the solution to the discrete-time
Lyapunov equation
solve_sylvester : computes the solution to the Sylvester equation
Notes
-----
The continuous Lyapunov equation is a special form of the Sylvester
equation, hence this solver relies on LAPACK routine ?TRSYL.
.. versionadded:: 0.11.0
Examples
--------
Given `a` and `q` solve for `x`:
>>> from scipy import linalg
>>> a = np.array([[-3, -2, 0], [-1, -1, 0], [0, -5, -1]])
>>> b = np.array([2, 4, -1])
>>> q = np.eye(3)
>>> x = linalg.solve_continuous_lyapunov(a, q)
>>> x
array([[ -0.75 , 0.875 , -3.75 ],
[ 0.875 , -1.375 , 5.3125],
[ -3.75 , 5.3125, -27.0625]])
>>> np.allclose(a.dot(x) + x.dot(a.T), q)
True
"""
a = np.atleast_2d(_asarray_validated(a, check_finite=True))
q = np.atleast_2d(_asarray_validated(q, check_finite=True))
r_or_c = float
for ind, _ in enumerate((a, q)):
if np.iscomplexobj(_):
r_or_c = complex
if not np.equal(*_.shape):
raise ValueError("Matrix {} should be square.".format("aq"[ind]))
# Shape consistency check
if a.shape != q.shape:
raise ValueError("Matrix a and q should have the same shape.")
# Compute the Schur decomp form of a
r, u = schur(a, output='real')
# Construct f = u'*q*u
f = u.conj().T.dot(q.dot(u))
# Call the Sylvester equation solver
trsyl = get_lapack_funcs('trsyl', (r, f))
dtype_string = 'T' if r_or_c == float else 'C'
y, scale, info = trsyl(r, r, f, tranb=dtype_string)
if info < 0:
raise ValueError('?TRSYL exited with the internal error '
'"illegal value in argument number {}.". See '
'LAPACK documentation for the ?TRSYL error codes.'
''.format(-info))
elif info == 1:
warnings.warn('Input "a" has an eigenvalue pair whose sum is '
'very close to or exactly zero. The solution is '
'obtained via perturbing the coefficients.',
RuntimeWarning)
y *= scale
return u.dot(y).dot(u.conj().T) | [
"def",
"solve_continuous_lyapunov",
"(",
"a",
",",
"q",
")",
":",
"a",
"=",
"np",
".",
"atleast_2d",
"(",
"_asarray_validated",
"(",
"a",
",",
"check_finite",
"=",
"True",
")",
")",
"q",
"=",
"np",
".",
"atleast_2d",
"(",
"_asarray_validated",
"(",
"q",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/linalg/_solvers.py#L110-L199 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/factorization/python/ops/factorization_ops.py | python | WALSModel._shard_sizes | (cls, dims, num_shards) | return [shard_size + 1] * residual + [shard_size] * (num_shards - residual) | Helper function to split dims values into num_shards. | Helper function to split dims values into num_shards. | [
"Helper",
"function",
"to",
"split",
"dims",
"values",
"into",
"num_shards",
"."
] | def _shard_sizes(cls, dims, num_shards):
"""Helper function to split dims values into num_shards."""
shard_size, residual = divmod(dims, num_shards)
return [shard_size + 1] * residual + [shard_size] * (num_shards - residual) | [
"def",
"_shard_sizes",
"(",
"cls",
",",
"dims",
",",
"num_shards",
")",
":",
"shard_size",
",",
"residual",
"=",
"divmod",
"(",
"dims",
",",
"num_shards",
")",
"return",
"[",
"shard_size",
"+",
"1",
"]",
"*",
"residual",
"+",
"[",
"shard_size",
"]",
"*... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L274-L277 | |
s9xie/hed | 94fb22f10cbfec8d84fbc0642b224022014b6bd6 | python/caffe/io.py | python | array_to_datum | (arr, label=0) | return datum | Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format. | Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format. | [
"Converts",
"a",
"3",
"-",
"dimensional",
"array",
"to",
"datum",
".",
"If",
"the",
"array",
"has",
"dtype",
"uint8",
"the",
"output",
"data",
"will",
"be",
"encoded",
"as",
"a",
"string",
".",
"Otherwise",
"the",
"output",
"data",
"will",
"be",
"stored"... | def array_to_datum(arr, label=0):
"""Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format.
"""
if arr.ndim != 3:
raise ValueError('Incorrect array shape.')
datum = caffe_pb2.Datum()
datum.channels, datum.height, datum.width = arr.shape
if arr.dtype == np.uint8:
datum.data = arr.tostring()
else:
datum.float_data.extend(arr.flat)
datum.label = label
return datum | [
"def",
"array_to_datum",
"(",
"arr",
",",
"label",
"=",
"0",
")",
":",
"if",
"arr",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'Incorrect array shape.'",
")",
"datum",
"=",
"caffe_pb2",
".",
"Datum",
"(",
")",
"datum",
".",
"channels",
"... | https://github.com/s9xie/hed/blob/94fb22f10cbfec8d84fbc0642b224022014b6bd6/python/caffe/io.py#L63-L77 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/groupby.py | python | GroupBy.tail | (self, n=5) | return self._selected_obj[mask] | Return last n rows of each group.
Similar to ``.apply(lambda x: x.tail(n))``, but it returns a subset of rows
from the original DataFrame with original index and order preserved
(``as_index`` flag is ignored).
Does not work for negative values of `n`.
Returns
-------
Series or DataFrame
%(see_also)s
Examples
--------
>>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]],
... columns=['A', 'B'])
>>> df.groupby('A').tail(1)
A B
1 a 2
3 b 2
>>> df.groupby('A').tail(-1)
Empty DataFrame
Columns: [A, B]
Index: [] | Return last n rows of each group. | [
"Return",
"last",
"n",
"rows",
"of",
"each",
"group",
"."
] | def tail(self, n=5):
"""
Return last n rows of each group.
Similar to ``.apply(lambda x: x.tail(n))``, but it returns a subset of rows
from the original DataFrame with original index and order preserved
(``as_index`` flag is ignored).
Does not work for negative values of `n`.
Returns
-------
Series or DataFrame
%(see_also)s
Examples
--------
>>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]],
... columns=['A', 'B'])
>>> df.groupby('A').tail(1)
A B
1 a 2
3 b 2
>>> df.groupby('A').tail(-1)
Empty DataFrame
Columns: [A, B]
Index: []
"""
self._reset_group_selection()
mask = self._cumcount_array(ascending=False) < n
return self._selected_obj[mask] | [
"def",
"tail",
"(",
"self",
",",
"n",
"=",
"5",
")",
":",
"self",
".",
"_reset_group_selection",
"(",
")",
"mask",
"=",
"self",
".",
"_cumcount_array",
"(",
"ascending",
"=",
"False",
")",
"<",
"n",
"return",
"self",
".",
"_selected_obj",
"[",
"mask",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/groupby.py#L2405-L2435 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | nanoFTPProxy | (host, port, user, passwd, type) | Setup the FTP proxy informations. This can also be done by
using ftp_proxy ftp_proxy_user and ftp_proxy_password
environment variables. | Setup the FTP proxy informations. This can also be done by
using ftp_proxy ftp_proxy_user and ftp_proxy_password
environment variables. | [
"Setup",
"the",
"FTP",
"proxy",
"informations",
".",
"This",
"can",
"also",
"be",
"done",
"by",
"using",
"ftp_proxy",
"ftp_proxy_user",
"and",
"ftp_proxy_password",
"environment",
"variables",
"."
] | def nanoFTPProxy(host, port, user, passwd, type):
"""Setup the FTP proxy informations. This can also be done by
using ftp_proxy ftp_proxy_user and ftp_proxy_password
environment variables. """
libxml2mod.xmlNanoFTPProxy(host, port, user, passwd, type) | [
"def",
"nanoFTPProxy",
"(",
"host",
",",
"port",
",",
"user",
",",
"passwd",
",",
"type",
")",
":",
"libxml2mod",
".",
"xmlNanoFTPProxy",
"(",
"host",
",",
"port",
",",
"user",
",",
"passwd",
",",
"type",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L446-L450 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/dataset/uci_housing.py | python | test | () | return reader | UCI_HOUSING test set creator.
It returns a reader creator, each sample in the reader is features after
normalization and price number.
:return: Test reader creator
:rtype: callable | UCI_HOUSING test set creator. | [
"UCI_HOUSING",
"test",
"set",
"creator",
"."
] | def test():
"""
UCI_HOUSING test set creator.
It returns a reader creator, each sample in the reader is features after
normalization and price number.
:return: Test reader creator
:rtype: callable
"""
global UCI_TEST_DATA
load_data(paddle.dataset.common.download(URL, 'uci_housing', MD5))
def reader():
for d in UCI_TEST_DATA:
yield d[:-1], d[-1:]
return reader | [
"def",
"test",
"(",
")",
":",
"global",
"UCI_TEST_DATA",
"load_data",
"(",
"paddle",
".",
"dataset",
".",
"common",
".",
"download",
"(",
"URL",
",",
"'uci_housing'",
",",
"MD5",
")",
")",
"def",
"reader",
"(",
")",
":",
"for",
"d",
"in",
"UCI_TEST_DAT... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/dataset/uci_housing.py#L117-L134 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter.py | python | PlottingCanvasPresenter.replot_workspace_with_error_state | (self, workspace_name, error_state) | Replot a workspace in the plot with a different error_state | Replot a workspace in the plot with a different error_state | [
"Replot",
"a",
"workspace",
"in",
"the",
"plot",
"with",
"a",
"different",
"error_state"
] | def replot_workspace_with_error_state(self, workspace_name, error_state):
"""Replot a workspace in the plot with a different error_state"""
self._view.replot_workspace_with_error_state(workspace_name, error_state) | [
"def",
"replot_workspace_with_error_state",
"(",
"self",
",",
"workspace_name",
",",
"error_state",
")",
":",
"self",
".",
"_view",
".",
"replot_workspace_with_error_state",
"(",
"workspace_name",
",",
"error_state",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter.py#L54-L56 | ||
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | python/artm/score_tracker.py | python | PerplexityScoreTracker.__init__ | (self, score) | :Properties:
* Note: every field is a list of info about score on all synchronizations.
* value - values of perplexity.
* raw - raw values in formula for perplexity (in case of one class id).
* normalizer - normalizer values in formula for perplexity (in case of one class id).
* zero_tokens - number of zero p(w|d) = sum_t p(w|t) p(t|d) (in case of one class id).
* transaction_typename_info - array of structures, each structure contains raw, normalizer\
zero_tokens and transaction_typename name\
(in case of several transaction types)\
Note, that in the case\
of non-transaction model transaction type is equal @default_transaction.
* Note: every field has a version with prefix 'last_', means retrieving only\
info about the last synchronization. | :Properties:
* Note: every field is a list of info about score on all synchronizations.
* value - values of perplexity.
* raw - raw values in formula for perplexity (in case of one class id).
* normalizer - normalizer values in formula for perplexity (in case of one class id).
* zero_tokens - number of zero p(w|d) = sum_t p(w|t) p(t|d) (in case of one class id).
* transaction_typename_info - array of structures, each structure contains raw, normalizer\
zero_tokens and transaction_typename name\
(in case of several transaction types)\
Note, that in the case\
of non-transaction model transaction type is equal | [
":",
"Properties",
":",
"*",
"Note",
":",
"every",
"field",
"is",
"a",
"list",
"of",
"info",
"about",
"score",
"on",
"all",
"synchronizations",
".",
"*",
"value",
"-",
"values",
"of",
"perplexity",
".",
"*",
"raw",
"-",
"raw",
"values",
"in",
"formula"... | def __init__(self, score):
"""
:Properties:
* Note: every field is a list of info about score on all synchronizations.
* value - values of perplexity.
* raw - raw values in formula for perplexity (in case of one class id).
* normalizer - normalizer values in formula for perplexity (in case of one class id).
* zero_tokens - number of zero p(w|d) = sum_t p(w|t) p(t|d) (in case of one class id).
* transaction_typename_info - array of structures, each structure contains raw, normalizer\
zero_tokens and transaction_typename name\
(in case of several transaction types)\
Note, that in the case\
of non-transaction model transaction type is equal @default_transaction.
* Note: every field has a version with prefix 'last_', means retrieving only\
info about the last synchronization.
"""
BaseScoreTracker.__init__(self, score) | [
"def",
"__init__",
"(",
"self",
",",
"score",
")",
":",
"BaseScoreTracker",
".",
"__init__",
"(",
"self",
",",
"score",
")"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/python/artm/score_tracker.py#L133-L149 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/monitors.py | python | ValidationMonitor.__init__ | (self, x=None, y=None, input_fn=None, batch_size=None,
eval_steps=None,
every_n_steps=100, metrics=None, hooks=None,
early_stopping_rounds=None,
early_stopping_metric="loss",
early_stopping_metric_minimize=True, name=None) | Initializes a ValidationMonitor.
Args:
x: See `BaseEstimator.evaluate`.
y: See `BaseEstimator.evaluate`.
input_fn: See `BaseEstimator.evaluate`.
batch_size: See `BaseEstimator.evaluate`.
eval_steps: See `BaseEstimator.evaluate`.
every_n_steps: Check for new checkpoints to evaluate every N steps. If a
new checkpoint is found, it is evaluated. See `EveryN`.
metrics: See `BaseEstimator.evaluate`.
hooks: A list of `SessionRunHook` hooks to pass to the
`Estimator`'s `evaluate` function.
early_stopping_rounds: `int`. If the metric indicated by
`early_stopping_metric` does not change according to
`early_stopping_metric_minimize` for this many steps, then training
will be stopped.
early_stopping_metric: `string`, name of the metric to check for early
stopping.
early_stopping_metric_minimize: `bool`, True if `early_stopping_metric` is
expected to decrease (thus early stopping occurs when this metric
stops decreasing), False if `early_stopping_metric` is expected to
increase. Typically, `early_stopping_metric_minimize` is True for
loss metrics like mean squared error, and False for performance
metrics like accuracy.
name: See `BaseEstimator.evaluate`.
Raises:
ValueError: If both x and input_fn are provided. | Initializes a ValidationMonitor. | [
"Initializes",
"a",
"ValidationMonitor",
"."
] | def __init__(self, x=None, y=None, input_fn=None, batch_size=None,
eval_steps=None,
every_n_steps=100, metrics=None, hooks=None,
early_stopping_rounds=None,
early_stopping_metric="loss",
early_stopping_metric_minimize=True, name=None):
"""Initializes a ValidationMonitor.
Args:
x: See `BaseEstimator.evaluate`.
y: See `BaseEstimator.evaluate`.
input_fn: See `BaseEstimator.evaluate`.
batch_size: See `BaseEstimator.evaluate`.
eval_steps: See `BaseEstimator.evaluate`.
every_n_steps: Check for new checkpoints to evaluate every N steps. If a
new checkpoint is found, it is evaluated. See `EveryN`.
metrics: See `BaseEstimator.evaluate`.
hooks: A list of `SessionRunHook` hooks to pass to the
`Estimator`'s `evaluate` function.
early_stopping_rounds: `int`. If the metric indicated by
`early_stopping_metric` does not change according to
`early_stopping_metric_minimize` for this many steps, then training
will be stopped.
early_stopping_metric: `string`, name of the metric to check for early
stopping.
early_stopping_metric_minimize: `bool`, True if `early_stopping_metric` is
expected to decrease (thus early stopping occurs when this metric
stops decreasing), False if `early_stopping_metric` is expected to
increase. Typically, `early_stopping_metric_minimize` is True for
loss metrics like mean squared error, and False for performance
metrics like accuracy.
name: See `BaseEstimator.evaluate`.
Raises:
ValueError: If both x and input_fn are provided.
"""
super(ValidationMonitor, self).__init__(every_n_steps=every_n_steps,
first_n_steps=-1)
# TODO(mdan): Checks like this are already done by evaluate.
if x is None and input_fn is None:
raise ValueError("Either x or input_fn should be provided.")
self.x = x
self.y = y
self.input_fn = input_fn
self.batch_size = batch_size
self.eval_steps = eval_steps
self.metrics = metrics
self.hooks = hooks
self.early_stopping_rounds = early_stopping_rounds
self.early_stopping_metric = early_stopping_metric
self.early_stopping_metric_minimize = early_stopping_metric_minimize
self.name = name
self._best_value_step = None
self._best_value = None
self._best_metrics = None
self._early_stopped = False
self._latest_path = None
self._latest_path_step = None | [
"def",
"__init__",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"input_fn",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"eval_steps",
"=",
"None",
",",
"every_n_steps",
"=",
"100",
",",
"metrics",
"=",
"None",
",",
"hooks",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/monitors.py#L564-L621 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozpack/packager/__init__.py | python | SimplePackager.close | (self) | Push all instructions to the formatter. | Push all instructions to the formatter. | [
"Push",
"all",
"instructions",
"to",
"the",
"formatter",
"."
] | def close(self):
'''
Push all instructions to the formatter.
'''
self._closed = True
for base in self.get_bases():
if base:
self.formatter.add_base(base)
self._chrome_queue.execute()
self._queue.execute()
self._file_queue.execute() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_closed",
"=",
"True",
"for",
"base",
"in",
"self",
".",
"get_bases",
"(",
")",
":",
"if",
"base",
":",
"self",
".",
"formatter",
".",
"add_base",
"(",
"base",
")",
"self",
".",
"_chrome_queue",
... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/packager/__init__.py#L289-L299 | ||
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | src/kudu/scripts/backup-perf.py | python | create_table | (opts, stats) | Create a Kudu table via impala-shell | Create a Kudu table via impala-shell | [
"Create",
"a",
"Kudu",
"table",
"via",
"impala",
"-",
"shell"
] | def create_table(opts, stats):
""" Create a Kudu table via impala-shell """
print("--------------------------------------")
print("Creating table %s" % (opts.table_name,))
print("--------------------------------------")
print(timestamp())
create_table_ddl = "CREATE TABLE %s (" % (opts.table_name,)
num_bigint_cols = opts.columns - opts.num_string_columns
assert(num_bigint_cols > 0)
for i in range(opts.columns):
coltype = 'STRING'
if i < num_bigint_cols: coltype = 'BIGINT'
if i > 0: create_table_ddl += ', '
create_table_ddl += "f%d %s" % (i, coltype)
if i == 0: create_table_ddl += ' PRIMARY KEY'
create_table_ddl += ") PARTITION BY HASH(f0) PARTITIONS %d STORED AS KUDU " % \
(opts.partitions, )
create_table_ddl += "TBLPROPERTIES ('kudu.num_tablet_replicas' = '%d')" % \
(opts.replication_factor, )
cmd = 'echo "%s" | impala-shell -i %s -f -' % (create_table_ddl, opts.impalad_address)
run_command(opts, cmd) | [
"def",
"create_table",
"(",
"opts",
",",
"stats",
")",
":",
"print",
"(",
"\"--------------------------------------\"",
")",
"print",
"(",
"\"Creating table %s\"",
"%",
"(",
"opts",
".",
"table_name",
",",
")",
")",
"print",
"(",
"\"---------------------------------... | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/src/kudu/scripts/backup-perf.py#L110-L131 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py | python | _Macro.remove | (self, value) | Remove a value from the macro. It doesn't matter if the value
wasn't present.
value is the value to remove. | Remove a value from the macro. It doesn't matter if the value
wasn't present.
value is the value to remove. | [
"Remove",
"a",
"value",
"from",
"the",
"macro",
".",
"It",
"doesn",
"t",
"matter",
"if",
"the",
"value",
"wasn",
"t",
"present",
".",
"value",
"is",
"the",
"value",
"to",
"remove",
"."
] | def remove(self, value):
"""Remove a value from the macro. It doesn't matter if the value
wasn't present.
value is the value to remove.
"""
try:
self._macro.remove(value)
except:
pass | [
"def",
"remove",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"self",
".",
"_macro",
".",
"remove",
"(",
"value",
")",
"except",
":",
"pass"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L293-L302 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_ENC_SCHEME_OAEP.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(TPMS_ENC_SCHEME_OAEP) | Returns new TPMS_ENC_SCHEME_OAEP object constructed from its
marshaled representation in the given byte buffer | Returns new TPMS_ENC_SCHEME_OAEP object constructed from its
marshaled representation in the given byte buffer | [
"Returns",
"new",
"TPMS_ENC_SCHEME_OAEP",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new TPMS_ENC_SCHEME_OAEP object constructed from its
marshaled representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(TPMS_ENC_SCHEME_OAEP) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"TPMS_ENC_SCHEME_OAEP",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L6679-L6683 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/driver.py | python | Driver.parse_stream | (self, stream, debug=False) | return self.parse_stream_raw(stream, debug) | Parse a stream and return the syntax tree. | Parse a stream and return the syntax tree. | [
"Parse",
"a",
"stream",
"and",
"return",
"the",
"syntax",
"tree",
"."
] | def parse_stream(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
return self.parse_stream_raw(stream, debug) | [
"def",
"parse_stream",
"(",
"self",
",",
"stream",
",",
"debug",
"=",
"False",
")",
":",
"return",
"self",
".",
"parse_stream_raw",
"(",
"stream",
",",
"debug",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/driver.py#L92-L94 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/email/mime/base.py | python | MIMEBase.__init__ | (self, _maintype, _subtype, *, policy=None, **_params) | This constructor adds a Content-Type: and a MIME-Version: header.
The Content-Type: header is taken from the _maintype and _subtype
arguments. Additional parameters for this header are taken from the
keyword arguments. | This constructor adds a Content-Type: and a MIME-Version: header. | [
"This",
"constructor",
"adds",
"a",
"Content",
"-",
"Type",
":",
"and",
"a",
"MIME",
"-",
"Version",
":",
"header",
"."
] | def __init__(self, _maintype, _subtype, *, policy=None, **_params):
"""This constructor adds a Content-Type: and a MIME-Version: header.
The Content-Type: header is taken from the _maintype and _subtype
arguments. Additional parameters for this header are taken from the
keyword arguments.
"""
if policy is None:
policy = email.policy.compat32
message.Message.__init__(self, policy=policy)
ctype = '%s/%s' % (_maintype, _subtype)
self.add_header('Content-Type', ctype, **_params)
self['MIME-Version'] = '1.0' | [
"def",
"__init__",
"(",
"self",
",",
"_maintype",
",",
"_subtype",
",",
"*",
",",
"policy",
"=",
"None",
",",
"*",
"*",
"_params",
")",
":",
"if",
"policy",
"is",
"None",
":",
"policy",
"=",
"email",
".",
"policy",
".",
"compat32",
"message",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/mime/base.py#L18-L30 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | Locale.GetLanguageInfo | (*args, **kwargs) | return _gdi_.Locale_GetLanguageInfo(*args, **kwargs) | GetLanguageInfo(int lang) -> LanguageInfo | GetLanguageInfo(int lang) -> LanguageInfo | [
"GetLanguageInfo",
"(",
"int",
"lang",
")",
"-",
">",
"LanguageInfo"
] | def GetLanguageInfo(*args, **kwargs):
"""GetLanguageInfo(int lang) -> LanguageInfo"""
return _gdi_.Locale_GetLanguageInfo(*args, **kwargs) | [
"def",
"GetLanguageInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Locale_GetLanguageInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3055-L3057 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/shelve.py | python | open | (filename, flag='c', protocol=None, writeback=False) | return DbfilenameShelf(filename, flag, protocol, writeback) | Open a persistent dictionary for reading and writing.
The filename parameter is the base filename for the underlying
database. As a side-effect, an extension may be added to the
filename and more than one file may be created. The optional flag
parameter has the same interpretation as the flag parameter of
anydbm.open(). The optional protocol parameter specifies the
version of the pickle protocol (0, 1, or 2).
See the module's __doc__ string for an overview of the interface. | Open a persistent dictionary for reading and writing. | [
"Open",
"a",
"persistent",
"dictionary",
"for",
"reading",
"and",
"writing",
"."
] | def open(filename, flag='c', protocol=None, writeback=False):
"""Open a persistent dictionary for reading and writing.
The filename parameter is the base filename for the underlying
database. As a side-effect, an extension may be added to the
filename and more than one file may be created. The optional flag
parameter has the same interpretation as the flag parameter of
anydbm.open(). The optional protocol parameter specifies the
version of the pickle protocol (0, 1, or 2).
See the module's __doc__ string for an overview of the interface.
"""
return DbfilenameShelf(filename, flag, protocol, writeback) | [
"def",
"open",
"(",
"filename",
",",
"flag",
"=",
"'c'",
",",
"protocol",
"=",
"None",
",",
"writeback",
"=",
"False",
")",
":",
"return",
"DbfilenameShelf",
"(",
"filename",
",",
"flag",
",",
"protocol",
",",
"writeback",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/shelve.py#L226-L239 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py | python | GenerateOutput | (target_list, target_dicts, data, params) | Generate an XML settings file that can be imported into a CDT project. | Generate an XML settings file that can be imported into a CDT project. | [
"Generate",
"an",
"XML",
"settings",
"file",
"that",
"can",
"be",
"imported",
"into",
"a",
"CDT",
"project",
"."
] | def GenerateOutput(target_list, target_dicts, data, params):
"""Generate an XML settings file that can be imported into a CDT project."""
if params["options"].generator_output:
raise NotImplementedError("--generator_output not implemented for eclipse")
user_config = params.get("generator_flags", {}).get("config", None)
if user_config:
GenerateOutputForConfig(target_list, target_dicts, data, params, user_config)
else:
config_names = target_dicts[target_list[0]]["configurations"]
for config_name in config_names:
GenerateOutputForConfig(
target_list, target_dicts, data, params, config_name
) | [
"def",
"GenerateOutput",
"(",
"target_list",
",",
"target_dicts",
",",
"data",
",",
"params",
")",
":",
"if",
"params",
"[",
"\"options\"",
"]",
".",
"generator_output",
":",
"raise",
"NotImplementedError",
"(",
"\"--generator_output not implemented for eclipse\"",
")... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py#L450-L464 | ||
PaddlePaddle/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | tools/external_converter_v2/parser/tensorflow/parse_med_2_ak.py | python | MedTransAK.Pad | (self, med_attr, param) | fill Pad param in ak graph
:param med_attr:
:param param:
:return: | fill Pad param in ak graph
:param med_attr:
:param param:
:return: | [
"fill",
"Pad",
"param",
"in",
"ak",
"graph",
":",
"param",
"med_attr",
":",
":",
"param",
"param",
":",
":",
"return",
":"
] | def Pad(self, med_attr, param):
'''
fill Pad param in ak graph
:param med_attr:
:param param:
:return:
'''
param.pad_c = med_attr['pad_c']
param.pad_h = med_attr['pad_h']
param.pad_w = med_attr['pad_w'] | [
"def",
"Pad",
"(",
"self",
",",
"med_attr",
",",
"param",
")",
":",
"param",
".",
"pad_c",
"=",
"med_attr",
"[",
"'pad_c'",
"]",
"param",
".",
"pad_h",
"=",
"med_attr",
"[",
"'pad_h'",
"]",
"param",
".",
"pad_w",
"=",
"med_attr",
"[",
"'pad_w'",
"]"
... | https://github.com/PaddlePaddle/Anakin/blob/5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730/tools/external_converter_v2/parser/tensorflow/parse_med_2_ak.py#L213-L222 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode.py | python | _finder | (data, substr, start, end) | return -1 | Left finder. | Left finder. | [
"Left",
"finder",
"."
] | def _finder(data, substr, start, end):
"""Left finder."""
if len(substr) == 0:
return start
for i in range(start, min(len(data), end) - len(substr) + 1):
if _cmp_region(data, i, substr, 0, len(substr)) == 0:
return i
return -1 | [
"def",
"_finder",
"(",
"data",
",",
"substr",
",",
"start",
",",
"end",
")",
":",
"if",
"len",
"(",
"substr",
")",
"==",
"0",
":",
"return",
"start",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"min",
"(",
"len",
"(",
"data",
")",
",",
"end",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode.py#L579-L586 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/skia/tools/copyright/main.py | python | ReadFileIntoString | (filepath) | return contents | Returns the full contents of this file as a string. | Returns the full contents of this file as a string. | [
"Returns",
"the",
"full",
"contents",
"of",
"this",
"file",
"as",
"a",
"string",
"."
] | def ReadFileIntoString(filepath):
"""Returns the full contents of this file as a string.
"""
with open(filepath, 'r') as file_handle:
contents = file_handle.read()
return contents | [
"def",
"ReadFileIntoString",
"(",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"file_handle",
":",
"contents",
"=",
"file_handle",
".",
"read",
"(",
")",
"return",
"contents"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/tools/copyright/main.py#L85-L90 | |
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/virtual_target.py | python | VirtualTarget.path | (self) | If the target is generated one, returns the path where it will be
generated. Otherwise, returns empty list. | If the target is generated one, returns the path where it will be
generated. Otherwise, returns empty list. | [
"If",
"the",
"target",
"is",
"generated",
"one",
"returns",
"the",
"path",
"where",
"it",
"will",
"be",
"generated",
".",
"Otherwise",
"returns",
"empty",
"list",
"."
] | def path (self):
""" If the target is generated one, returns the path where it will be
generated. Otherwise, returns empty list.
"""
raise BaseException ("method should be defined in derived classes") | [
"def",
"path",
"(",
"self",
")",
":",
"raise",
"BaseException",
"(",
"\"method should be defined in derived classes\"",
")"
] | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/virtual_target.py#L361-L365 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/models.py | python | Response.apparent_encoding | (self) | return chardet.detect(self.content)['encoding'] | The apparent encoding, provided by the chardet library | The apparent encoding, provided by the chardet library | [
"The",
"apparent",
"encoding",
"provided",
"by",
"the",
"chardet",
"library"
] | def apparent_encoding(self):
"""The apparent encoding, provided by the chardet library"""
return chardet.detect(self.content)['encoding'] | [
"def",
"apparent_encoding",
"(",
"self",
")",
":",
"return",
"chardet",
".",
"detect",
"(",
"self",
".",
"content",
")",
"[",
"'encoding'",
"]"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/models.py#L637-L639 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/libs/metaparse/tools/benchmark/benchmark.py | python | compiler_info | (compiler) | return compiler | Determine the name + version of the compiler | Determine the name + version of the compiler | [
"Determine",
"the",
"name",
"+",
"version",
"of",
"the",
"compiler"
] | def compiler_info(compiler):
"""Determine the name + version of the compiler"""
(out, err) = subprocess.Popen(
['/bin/sh', '-c', '{0} -v'.format(compiler)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate('')
gcc_clang = re.compile('(gcc|clang) version ([0-9]+(\\.[0-9]+)*)')
for line in (out + err).split('\n'):
mtch = gcc_clang.search(line)
if mtch:
return mtch.group(1) + ' ' + mtch.group(2)
return compiler | [
"def",
"compiler_info",
"(",
"compiler",
")",
":",
"(",
"out",
",",
"err",
")",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'/bin/sh'",
",",
"'-c'",
",",
"'{0} -v'",
".",
"format",
"(",
"compiler",
")",
"]",
",",
"stdin",
"=",
"subprocess",
".",
"PIP... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/libs/metaparse/tools/benchmark/benchmark.py#L76-L92 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | Pen.SetCap | (*args, **kwargs) | return _gdi_.Pen_SetCap(*args, **kwargs) | SetCap(self, int cap_style) | SetCap(self, int cap_style) | [
"SetCap",
"(",
"self",
"int",
"cap_style",
")"
] | def SetCap(*args, **kwargs):
"""SetCap(self, int cap_style)"""
return _gdi_.Pen_SetCap(*args, **kwargs) | [
"def",
"SetCap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Pen_SetCap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L425-L427 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Wm.wm_overrideredirect | (self, boolean=None) | return self._getboolean(self.tk.call(
'wm', 'overrideredirect', self._w, boolean)) | Instruct the window manager to ignore this widget
if BOOLEAN is given with 1. Return the current value if None
is given. | Instruct the window manager to ignore this widget
if BOOLEAN is given with 1. Return the current value if None
is given. | [
"Instruct",
"the",
"window",
"manager",
"to",
"ignore",
"this",
"widget",
"if",
"BOOLEAN",
"is",
"given",
"with",
"1",
".",
"Return",
"the",
"current",
"value",
"if",
"None",
"is",
"given",
"."
] | def wm_overrideredirect(self, boolean=None):
"""Instruct the window manager to ignore this widget
if BOOLEAN is given with 1. Return the current value if None
is given."""
return self._getboolean(self.tk.call(
'wm', 'overrideredirect', self._w, boolean)) | [
"def",
"wm_overrideredirect",
"(",
"self",
",",
"boolean",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getboolean",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'wm'",
",",
"'overrideredirect'",
",",
"self",
".",
"_w",
",",
"boolean",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L1745-L1750 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/algorithm_detail/single_execution.py | python | run_initial_event_slice_reduction | (reduction_alg, reduction_setting_bundle) | return EventSliceSettingBundle(state=reduction_setting_bundle.state,
data_type=reduction_setting_bundle.data_type,
reduction_mode=reduction_setting_bundle.reduction_mode,
output_parts=reduction_setting_bundle.output_parts,
scatter_workspace=output_workspace,
dummy_mask_workspace=mask_workspace,
scatter_monitor_workspace=output_monitor_workspace,
direct_workspace=reduction_setting_bundle.direct_workspace,
transmission_workspace=reduction_setting_bundle.transmission_workspace) | This function runs the initial core reduction for event slice data. This is essentially half
a reduction (either sample or can), and is run before event slicing has been performed.
:param reduction_alg: a handle to the initial event slice reduction algorithm.
:param reduction_setting_bundle: a ReductionSettingBundle tuple
:return: a EventSliceReductionSettingBundle tuple | This function runs the initial core reduction for event slice data. This is essentially half
a reduction (either sample or can), and is run before event slicing has been performed. | [
"This",
"function",
"runs",
"the",
"initial",
"core",
"reduction",
"for",
"event",
"slice",
"data",
".",
"This",
"is",
"essentially",
"half",
"a",
"reduction",
"(",
"either",
"sample",
"or",
"can",
")",
"and",
"is",
"run",
"before",
"event",
"slicing",
"ha... | def run_initial_event_slice_reduction(reduction_alg, reduction_setting_bundle):
"""
This function runs the initial core reduction for event slice data. This is essentially half
a reduction (either sample or can), and is run before event slicing has been performed.
:param reduction_alg: a handle to the initial event slice reduction algorithm.
:param reduction_setting_bundle: a ReductionSettingBundle tuple
:return: a EventSliceReductionSettingBundle tuple
"""
# Get component to reduce
component = get_component_to_reduce(reduction_setting_bundle)
# Set the properties on the reduction algorithms
serialized_state = Serializer.to_json(reduction_setting_bundle.state)
reduction_alg.setProperty("SANSState", serialized_state)
reduction_alg.setProperty("Component", component)
reduction_alg.setProperty("ScatterWorkspace", reduction_setting_bundle.scatter_workspace)
reduction_alg.setProperty("ScatterMonitorWorkspace", reduction_setting_bundle.scatter_monitor_workspace)
reduction_alg.setProperty("DataType", reduction_setting_bundle.data_type.value)
reduction_alg.setProperty("OutputWorkspace", EMPTY_NAME)
reduction_alg.setProperty("OutputMonitorWorkspace", EMPTY_NAME)
# Run the reduction core
reduction_alg.execute()
# Get the results
output_workspace = reduction_alg.getProperty("OutputWorkspace").value
mask_workspace = reduction_alg.getProperty("DummyMaskWorkspace").value
output_monitor_workspace = reduction_alg.getProperty("OutputMonitorWorkspace").value
return EventSliceSettingBundle(state=reduction_setting_bundle.state,
data_type=reduction_setting_bundle.data_type,
reduction_mode=reduction_setting_bundle.reduction_mode,
output_parts=reduction_setting_bundle.output_parts,
scatter_workspace=output_workspace,
dummy_mask_workspace=mask_workspace,
scatter_monitor_workspace=output_monitor_workspace,
direct_workspace=reduction_setting_bundle.direct_workspace,
transmission_workspace=reduction_setting_bundle.transmission_workspace) | [
"def",
"run_initial_event_slice_reduction",
"(",
"reduction_alg",
",",
"reduction_setting_bundle",
")",
":",
"# Get component to reduce",
"component",
"=",
"get_component_to_reduce",
"(",
"reduction_setting_bundle",
")",
"# Set the properties on the reduction algorithms",
"serialized... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/single_execution.py#L25-L63 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Node/__init__.py | python | Node.push_to_cache | (self) | Try to push a node into a cache | Try to push a node into a cache | [
"Try",
"to",
"push",
"a",
"node",
"into",
"a",
"cache"
] | def push_to_cache(self):
"""Try to push a node into a cache
"""
pass | [
"def",
"push_to_cache",
"(",
"self",
")",
":",
"pass"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/__init__.py#L680-L683 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/fractions.py | python | Fraction.__trunc__ | (a) | trunc(a) | trunc(a) | [
"trunc",
"(",
"a",
")"
] | def __trunc__(a):
"""trunc(a)"""
if a._numerator < 0:
return -(-a._numerator // a._denominator)
else:
return a._numerator // a._denominator | [
"def",
"__trunc__",
"(",
"a",
")",
":",
"if",
"a",
".",
"_numerator",
"<",
"0",
":",
"return",
"-",
"(",
"-",
"a",
".",
"_numerator",
"//",
"a",
".",
"_denominator",
")",
"else",
":",
"return",
"a",
".",
"_numerator",
"//",
"a",
".",
"_denominator"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/fractions.py#L489-L494 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/all_reduce/python/all_reduce.py | python | _build_recursive_hd_gather | (input_tensors, devices, red_op) | return chunks | Construct the gather phase of recursive halving-doubling all-reduce.
Args:
input_tensors: list of T @{tf.Tensor} to be elementwise reduced.
devices: a list of strings naming the devices hosting input_tensors,
which will also be used to host the (partial) reduction values.
red_op: a binary elementwise reduction Op.
Returns:
list of T @{tf.Tensor} which are the fully reduced tensor shards.
Raises:
ValueError: num_devices not a power of 2, or tensor len not divisible
by 2 the proper number of times. | Construct the gather phase of recursive halving-doubling all-reduce. | [
"Construct",
"the",
"gather",
"phase",
"of",
"recursive",
"halving",
"-",
"doubling",
"all",
"-",
"reduce",
"."
] | def _build_recursive_hd_gather(input_tensors, devices, red_op):
"""Construct the gather phase of recursive halving-doubling all-reduce.
Args:
input_tensors: list of T @{tf.Tensor} to be elementwise reduced.
devices: a list of strings naming the devices hosting input_tensors,
which will also be used to host the (partial) reduction values.
red_op: a binary elementwise reduction Op.
Returns:
list of T @{tf.Tensor} which are the fully reduced tensor shards.
Raises:
ValueError: num_devices not a power of 2, or tensor len not divisible
by 2 the proper number of times.
"""
num_devices = len(devices)
num_hops = int(math.log(num_devices, 2))
if num_devices != (2 ** num_hops):
raise ValueError("num_devices must be a power of 2")
chunks = input_tensors
for h in range(0, num_hops):
span = 2 ** h
group_size = span * 2
new_chunks = [[] for _ in devices]
for d in range(0, num_devices):
if (d % group_size) >= (group_size / 2):
# skip right half of a pair
continue
left_dev = devices[d]
right_dev = devices[d + span]
left_split = array_ops.split(chunks[d], 2)
right_split = array_ops.split(chunks[d+span], 2)
with ops.device(left_dev):
new_chunks[d] = red_op(left_split[0], right_split[0])
with ops.device(right_dev):
new_chunks[d + span] = red_op(left_split[1], right_split[1])
chunks = new_chunks
return chunks | [
"def",
"_build_recursive_hd_gather",
"(",
"input_tensors",
",",
"devices",
",",
"red_op",
")",
":",
"num_devices",
"=",
"len",
"(",
"devices",
")",
"num_hops",
"=",
"int",
"(",
"math",
".",
"log",
"(",
"num_devices",
",",
"2",
")",
")",
"if",
"num_devices"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/all_reduce/python/all_reduce.py#L474-L512 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/pep425tags.py | python | get_impl_ver | () | return impl_ver | Return implementation version. | Return implementation version. | [
"Return",
"implementation",
"version",
"."
] | def get_impl_ver():
"""Return implementation version."""
impl_ver = get_config_var("py_version_nodot")
if not impl_ver or get_abbr_impl() == 'pp':
impl_ver = ''.join(map(str, get_impl_version_info()))
return impl_ver | [
"def",
"get_impl_ver",
"(",
")",
":",
"impl_ver",
"=",
"get_config_var",
"(",
"\"py_version_nodot\"",
")",
"if",
"not",
"impl_ver",
"or",
"get_abbr_impl",
"(",
")",
"==",
"'pp'",
":",
"impl_ver",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"str",
",",
"get_... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/pep425tags.py#L43-L48 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/expressions/constants/parameter.py | python | is_param_free | (expr) | return not expr.parameters() | Returns true if expression is not parametrized. | Returns true if expression is not parametrized. | [
"Returns",
"true",
"if",
"expression",
"is",
"not",
"parametrized",
"."
] | def is_param_free(expr) -> bool:
"""Returns true if expression is not parametrized."""
return not expr.parameters() | [
"def",
"is_param_free",
"(",
"expr",
")",
"->",
"bool",
":",
"return",
"not",
"expr",
".",
"parameters",
"(",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/expressions/constants/parameter.py#L30-L32 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/spinn/data.py | python | pad_and_reverse_word_ids | (sentences) | return sentences | Pad a list of sentences to the common maximum length + 1.
Args:
sentences: A list of sentences as a list of list of integers. Each integer
is a word ID. Each list of integer corresponds to one sentence.
Returns:
A numpy.ndarray of shape (num_sentences, max_length + 1), wherein max_length
is the maximum sentence length (in # of words). Each sentence is reversed
and then padded with an extra one at head, as required by the model. | Pad a list of sentences to the common maximum length + 1. | [
"Pad",
"a",
"list",
"of",
"sentences",
"to",
"the",
"common",
"maximum",
"length",
"+",
"1",
"."
] | def pad_and_reverse_word_ids(sentences):
"""Pad a list of sentences to the common maximum length + 1.
Args:
sentences: A list of sentences as a list of list of integers. Each integer
is a word ID. Each list of integer corresponds to one sentence.
Returns:
A numpy.ndarray of shape (num_sentences, max_length + 1), wherein max_length
is the maximum sentence length (in # of words). Each sentence is reversed
and then padded with an extra one at head, as required by the model.
"""
max_len = max(len(sent) for sent in sentences)
for sent in sentences:
if len(sent) < max_len:
sent.extend([PAD_CODE] * (max_len - len(sent)))
# Reverse in time order and pad an extra one.
sentences = np.fliplr(np.array(sentences, dtype=np.int64))
sentences = np.concatenate(
[np.ones([sentences.shape[0], 1], dtype=np.int64), sentences], axis=1)
return sentences | [
"def",
"pad_and_reverse_word_ids",
"(",
"sentences",
")",
":",
"max_len",
"=",
"max",
"(",
"len",
"(",
"sent",
")",
"for",
"sent",
"in",
"sentences",
")",
"for",
"sent",
"in",
"sentences",
":",
"if",
"len",
"(",
"sent",
")",
"<",
"max_len",
":",
"sent"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/spinn/data.py#L87-L107 | |
jsupancic/deep_hand_pose | 22cbeae1a8410ff5d37c060c7315719d0a5d608f | scripts/cpp_lint.py | python | _SetCountingStyle | (level) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def _SetCountingStyle(level):
"""Sets the module's counting options."""
_cpplint_state.SetCountingStyle(level) | [
"def",
"_SetCountingStyle",
"(",
"level",
")",
":",
"_cpplint_state",
".",
"SetCountingStyle",
"(",
"level",
")"
] | https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/scripts/cpp_lint.py#L787-L789 | ||
jsupancic/deep_hand_pose | 22cbeae1a8410ff5d37c060c7315719d0a5d608f | tools/extra/parse_log.py | python | parse_line_for_net_output | (regex_obj, row, row_dict_list,
line, iteration, seconds, learning_rate) | return row_dict_list, row | Parse a single line for training or test output
Returns a a tuple with (row_dict_list, row)
row: may be either a new row or an augmented version of the current row
row_dict_list: may be either the current row_dict_list or an augmented
version of the current row_dict_list | Parse a single line for training or test output | [
"Parse",
"a",
"single",
"line",
"for",
"training",
"or",
"test",
"output"
] | def parse_line_for_net_output(regex_obj, row, row_dict_list,
line, iteration, seconds, learning_rate):
"""Parse a single line for training or test output
Returns a a tuple with (row_dict_list, row)
row: may be either a new row or an augmented version of the current row
row_dict_list: may be either the current row_dict_list or an augmented
version of the current row_dict_list
"""
output_match = regex_obj.search(line)
if output_match:
if not row or row['NumIters'] != iteration:
# Push the last row and start a new one
if row:
# If we're on a new iteration, push the last row
# This will probably only happen for the first row; otherwise
# the full row checking logic below will push and clear full
# rows
row_dict_list.append(row)
row = OrderedDict([
('NumIters', iteration),
('Seconds', seconds),
('LearningRate', learning_rate)
])
# output_num is not used; may be used in the future
# output_num = output_match.group(1)
output_name = output_match.group(2)
output_val = output_match.group(3)
row[output_name] = float(output_val)
if row and len(row_dict_list) >= 1 and len(row) == len(row_dict_list[0]):
# The row is full, based on the fact that it has the same number of
# columns as the first row; append it to the list
row_dict_list.append(row)
row = None
return row_dict_list, row | [
"def",
"parse_line_for_net_output",
"(",
"regex_obj",
",",
"row",
",",
"row_dict_list",
",",
"line",
",",
"iteration",
",",
"seconds",
",",
"learning_rate",
")",
":",
"output_match",
"=",
"regex_obj",
".",
"search",
"(",
"line",
")",
"if",
"output_match",
":",... | https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/tools/extra/parse_log.py#L77-L116 | |
vergecurrency/verge | cc5711be0a978bcdc06c62569b129fe6ab4e4d9f | contrib/verify-commits/verify-commits.py | python | tree_sha512sum | (commit='HEAD') | return overall.hexdigest() | Calculate the Tree-sha512 for the commit.
This is copied from github-merge.py. | Calculate the Tree-sha512 for the commit. | [
"Calculate",
"the",
"Tree",
"-",
"sha512",
"for",
"the",
"commit",
"."
] | def tree_sha512sum(commit='HEAD'):
"""Calculate the Tree-sha512 for the commit.
This is copied from github-merge.py."""
# request metadata for entire tree, recursively
files = []
blob_by_name = {}
for line in subprocess.check_output([GIT, 'ls-tree', '--full-tree', '-r', commit]).splitlines():
name_sep = line.index(b'\t')
metadata = line[:name_sep].split() # perms, 'blob', blobid
assert metadata[1] == b'blob'
name = line[name_sep + 1:]
files.append(name)
blob_by_name[name] = metadata[2]
files.sort()
# open connection to git-cat-file in batch mode to request data for all blobs
# this is much faster than launching it per file
p = subprocess.Popen([GIT, 'cat-file', '--batch'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
overall = hashlib.sha512()
for f in files:
blob = blob_by_name[f]
# request blob
p.stdin.write(blob + b'\n')
p.stdin.flush()
# read header: blob, "blob", size
reply = p.stdout.readline().split()
assert reply[0] == blob and reply[1] == b'blob'
size = int(reply[2])
# hash the blob data
intern = hashlib.sha512()
ptr = 0
while ptr < size:
bs = min(65536, size - ptr)
piece = p.stdout.read(bs)
if len(piece) == bs:
intern.update(piece)
else:
raise IOError('Premature EOF reading git cat-file output')
ptr += bs
dig = intern.hexdigest()
assert p.stdout.read(1) == b'\n' # ignore LF that follows blob data
# update overall hash with file hash
overall.update(dig.encode("utf-8"))
overall.update(" ".encode("utf-8"))
overall.update(f)
overall.update("\n".encode("utf-8"))
p.stdin.close()
if p.wait():
raise IOError('Non-zero return value executing git cat-file')
return overall.hexdigest() | [
"def",
"tree_sha512sum",
"(",
"commit",
"=",
"'HEAD'",
")",
":",
"# request metadata for entire tree, recursively",
"files",
"=",
"[",
"]",
"blob_by_name",
"=",
"{",
"}",
"for",
"line",
"in",
"subprocess",
".",
"check_output",
"(",
"[",
"GIT",
",",
"'ls-tree'",
... | https://github.com/vergecurrency/verge/blob/cc5711be0a978bcdc06c62569b129fe6ab4e4d9f/contrib/verify-commits/verify-commits.py#L15-L66 | |
LLNL/lbann | 26083e6c86050302ce33148aea70f62e61cacb92 | applications/nlp/transformer/evaluate.py | python | get_batch | (indices) | return tokens_en, tokens_de | Get a batch of samples from the evaluation dataset.
The sequences are padded to the length of the longest sequence in
the batch. | Get a batch of samples from the evaluation dataset. | [
"Get",
"a",
"batch",
"of",
"samples",
"from",
"the",
"evaluation",
"dataset",
"."
] | def get_batch(indices):
"""Get a batch of samples from the evaluation dataset.
The sequences are padded to the length of the longest sequence in
the batch.
"""
# Get data samples
indices = utils.make_iterable(indices)
tokens_list_en = []
tokens_list_de = []
for index in indices:
tokens_en, tokens_de = dataset.get_val_sample(index)
tokens_list_en.append(tokens_en)
tokens_list_de.append(tokens_de)
# Convert tokens to PyTorch tensors
tokens_en = np.full(
(max(len(seq) for seq in tokens_list_en), len(indices)),
pad_index,
dtype=int,
)
tokens_de = np.full(
(max(len(seq) for seq in tokens_list_de), len(indices)),
pad_index,
dtype=int,
)
for i, seq in enumerate(tokens_list_en):
tokens_en[:len(seq), i] = seq
for i, seq in enumerate(tokens_list_de):
tokens_de[:len(seq), i] = seq
tokens_en = torch.from_numpy(tokens_en)
tokens_de = torch.from_numpy(tokens_de)
return tokens_en, tokens_de | [
"def",
"get_batch",
"(",
"indices",
")",
":",
"# Get data samples",
"indices",
"=",
"utils",
".",
"make_iterable",
"(",
"indices",
")",
"tokens_list_en",
"=",
"[",
"]",
"tokens_list_de",
"=",
"[",
"]",
"for",
"index",
"in",
"indices",
":",
"tokens_en",
",",
... | https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/applications/nlp/transformer/evaluate.py#L56-L90 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/models/_graph_visualization.py | python | _calculate_edges | (cy_nodes, cy_edges, shape_dict=None) | return cy_nodes, cy_edges | Parameters
----------
cy_nodes: list of nodes for graph
cy_edges: list of edges to be updated for graph
shape_dict: shape_dict required for inferring shape information
Returns
-------
cy_nodes: list of nodes for graph
cy_edges: list of edges to be updated for graph | [] | def _calculate_edges(cy_nodes, cy_edges, shape_dict=None):
"""
Parameters
----------
cy_nodes: list of nodes for graph
cy_edges: list of edges to be updated for graph
shape_dict: shape_dict required for inferring shape information
Returns
-------
cy_nodes: list of nodes for graph
cy_edges: list of edges to be updated for graph
"""
node_len = len(cy_nodes)
for upper_index in range(0, node_len):
for lower_index in range(upper_index + 1, node_len):
if (
"outputs" in cy_nodes[upper_index]["data"]["info"].keys()
and "inputs" in cy_nodes[upper_index]["data"]["info"].keys()
and "outputs" in cy_nodes[lower_index]["data"]["info"].keys()
and "inputs" in cy_nodes[lower_index]["data"]["info"].keys()
):
outputs = _ast.literal_eval(
cy_nodes[upper_index]["data"]["info"]["outputs"]
)
inputs = _ast.literal_eval(
cy_nodes[lower_index]["data"]["info"]["inputs"]
)
for output in outputs:
if output in inputs:
if shape_dict is None or output not in shape_dict.keys():
label = None
else:
label = str(shape_dict[output])
cy_edges.append(
{
"data": {
"id": "{}.{}.{}".format(
output,
cy_nodes[upper_index]["data"]["id"],
cy_nodes[lower_index]["data"]["id"],
),
"source": cy_nodes[upper_index]["data"]["id"],
"target": cy_nodes[lower_index]["data"]["id"],
"label": label,
"shape": label,
}
}
)
return cy_nodes, cy_edges | [
"def",
"_calculate_edges",
"(",
"cy_nodes",
",",
"cy_edges",
",",
"shape_dict",
"=",
"None",
")",
":",
"node_len",
"=",
"len",
"(",
"cy_nodes",
")",
"for",
"upper_index",
"in",
"range",
"(",
"0",
",",
"node_len",
")",
":",
"for",
"lower_index",
"in",
"ra... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/_graph_visualization.py#L18-L74 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py | python | array_equiv | (a1, a2) | return bool(asarray(a1 == a2).all()) | Returns True if input arrays are shape consistent and all elements equal.
Shape consistent means they are either the same shape, or one input array
can be broadcasted to create the same shape as the other one.
Parameters
----------
a1, a2 : array_like
Input arrays.
Returns
-------
out : bool
True if equivalent, False otherwise.
Examples
--------
>>> np.array_equiv([1, 2], [1, 2])
True
>>> np.array_equiv([1, 2], [1, 3])
False
Showing the shape equivalence:
>>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
True
>>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
False
>>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
False | Returns True if input arrays are shape consistent and all elements equal. | [
"Returns",
"True",
"if",
"input",
"arrays",
"are",
"shape",
"consistent",
"and",
"all",
"elements",
"equal",
"."
] | def array_equiv(a1, a2):
"""
Returns True if input arrays are shape consistent and all elements equal.
Shape consistent means they are either the same shape, or one input array
can be broadcasted to create the same shape as the other one.
Parameters
----------
a1, a2 : array_like
Input arrays.
Returns
-------
out : bool
True if equivalent, False otherwise.
Examples
--------
>>> np.array_equiv([1, 2], [1, 2])
True
>>> np.array_equiv([1, 2], [1, 3])
False
Showing the shape equivalence:
>>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
True
>>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
False
>>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
False
"""
try:
a1, a2 = asarray(a1), asarray(a2)
except Exception:
return False
try:
multiarray.broadcast(a1, a2)
except Exception:
return False
return bool(asarray(a1 == a2).all()) | [
"def",
"array_equiv",
"(",
"a1",
",",
"a2",
")",
":",
"try",
":",
"a1",
",",
"a2",
"=",
"asarray",
"(",
"a1",
")",
",",
"asarray",
"(",
"a2",
")",
"except",
"Exception",
":",
"return",
"False",
"try",
":",
"multiarray",
".",
"broadcast",
"(",
"a1",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py#L2335-L2379 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/environment.py | python | Template.generate | (self, *args, **kwargs) | For very large templates it can be useful to not render the whole
template at once but evaluate each statement after another and yield
piece for piece. This method basically does exactly that and returns
a generator that yields one item after another as unicode strings.
It accepts the same arguments as :meth:`render`. | For very large templates it can be useful to not render the whole
template at once but evaluate each statement after another and yield
piece for piece. This method basically does exactly that and returns
a generator that yields one item after another as unicode strings. | [
"For",
"very",
"large",
"templates",
"it",
"can",
"be",
"useful",
"to",
"not",
"render",
"the",
"whole",
"template",
"at",
"once",
"but",
"evaluate",
"each",
"statement",
"after",
"another",
"and",
"yield",
"piece",
"for",
"piece",
".",
"This",
"method",
"... | def generate(self, *args, **kwargs):
"""For very large templates it can be useful to not render the whole
template at once but evaluate each statement after another and yield
piece for piece. This method basically does exactly that and returns
a generator that yields one item after another as unicode strings.
It accepts the same arguments as :meth:`render`.
"""
vars = dict(*args, **kwargs)
try:
for event in self.root_render_func(self.new_context(vars)):
yield event
except Exception:
exc_info = sys.exc_info()
else:
return
yield self.environment.handle_exception(exc_info, True) | [
"def",
"generate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"vars",
"=",
"dict",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"for",
"event",
"in",
"self",
".",
"root_render_func",
"(",
"self",
".",
"new_co... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/environment.py#L1029-L1045 | ||
Kitware/VTK | 5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8 | Wrapping/Python/vtkmodules/wx/wxVTKRenderWindowInteractor.py | python | wxVTKRenderWindowInteractor.OnLeave | (self,event) | Handles the wx.EVT_LEAVE_WINDOW event for
wxVTKRenderWindowInteractor. | Handles the wx.EVT_LEAVE_WINDOW event for
wxVTKRenderWindowInteractor. | [
"Handles",
"the",
"wx",
".",
"EVT_LEAVE_WINDOW",
"event",
"for",
"wxVTKRenderWindowInteractor",
"."
] | def OnLeave(self,event):
"""Handles the wx.EVT_LEAVE_WINDOW event for
wxVTKRenderWindowInteractor.
"""
# event processing should continue
event.Skip()
self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
event.ControlDown(),
event.ShiftDown(),
chr(0), 0, None)
self._Iren.LeaveEvent() | [
"def",
"OnLeave",
"(",
"self",
",",
"event",
")",
":",
"# event processing should continue",
"event",
".",
"Skip",
"(",
")",
"self",
".",
"_Iren",
".",
"SetEventInformationFlipY",
"(",
"event",
".",
"GetX",
"(",
")",
",",
"event",
".",
"GetY",
"(",
")",
... | https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/wx/wxVTKRenderWindowInteractor.py#L446-L458 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py | python | _signature_from_callable | (obj, *,
follow_wrapper_chains=True,
skip_bound_arg=True,
sigcls) | Private helper function to get signature for arbitrary
callable objects. | Private helper function to get signature for arbitrary
callable objects. | [
"Private",
"helper",
"function",
"to",
"get",
"signature",
"for",
"arbitrary",
"callable",
"objects",
"."
] | def _signature_from_callable(obj, *,
follow_wrapper_chains=True,
skip_bound_arg=True,
sigcls):
"""Private helper function to get signature for arbitrary
callable objects.
"""
if not callable(obj):
raise TypeError('{!r} is not a callable object'.format(obj))
if isinstance(obj, types.MethodType):
# In this case we skip the first parameter of the underlying
# function (usually `self` or `cls`).
sig = _signature_from_callable(
obj.__func__,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
if skip_bound_arg:
return _signature_bound_method(sig)
else:
return sig
# Was this function wrapped by a decorator?
if follow_wrapper_chains:
obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
if isinstance(obj, types.MethodType):
# If the unwrapped object is a *method*, we might want to
# skip its first parameter (self).
# See test_signature_wrapped_bound_method for details.
return _signature_from_callable(
obj,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
try:
sig = obj.__signature__
except AttributeError:
pass
else:
if sig is not None:
if not isinstance(sig, Signature):
raise TypeError(
'unexpected object {!r} in __signature__ '
'attribute'.format(sig))
return sig
try:
partialmethod = obj._partialmethod
except AttributeError:
pass
else:
if isinstance(partialmethod, functools.partialmethod):
# Unbound partialmethod (see functools.partialmethod)
# This means, that we need to calculate the signature
# as if it's a regular partial object, but taking into
# account that the first positional argument
# (usually `self`, or `cls`) will not be passed
# automatically (as for boundmethods)
wrapped_sig = _signature_from_callable(
partialmethod.func,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:
# First argument of the wrapped callable is `*args`, as in
# `partialmethod(lambda *args)`.
return sig
else:
sig_params = tuple(sig.parameters.values())
assert (not sig_params or
first_wrapped_param is not sig_params[0])
new_params = (first_wrapped_param,) + sig_params
return sig.replace(parameters=new_params)
if isfunction(obj) or _signature_is_functionlike(obj):
# If it's a pure Python function, or an object that is duck type
# of a Python function (Cython functions, for instance), then:
return _signature_from_function(sigcls, obj)
if _signature_is_builtin(obj):
return _signature_from_builtin(sigcls, obj,
skip_bound_arg=skip_bound_arg)
if isinstance(obj, functools.partial):
wrapped_sig = _signature_from_callable(
obj.func,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
return _signature_get_partial(wrapped_sig, obj)
sig = None
if isinstance(obj, type):
# obj is a class or a metaclass
# First, let's see if it has an overloaded __call__ defined
# in its metaclass
call = _signature_get_user_defined_method(type(obj), '__call__')
if call is not None:
sig = _signature_from_callable(
call,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
else:
# Now we check if the 'obj' class has a '__new__' method
new = _signature_get_user_defined_method(obj, '__new__')
if new is not None:
sig = _signature_from_callable(
new,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
else:
# Finally, we should have at least __init__ implemented
init = _signature_get_user_defined_method(obj, '__init__')
if init is not None:
sig = _signature_from_callable(
init,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
if sig is None:
# At this point we know, that `obj` is a class, with no user-
# defined '__init__', '__new__', or class-level '__call__'
for base in obj.__mro__[:-1]:
# Since '__text_signature__' is implemented as a
# descriptor that extracts text signature from the
# class docstring, if 'obj' is derived from a builtin
# class, its own '__text_signature__' may be 'None'.
# Therefore, we go through the MRO (except the last
# class in there, which is 'object') to find the first
# class with non-empty text signature.
try:
text_sig = base.__text_signature__
except AttributeError:
pass
else:
if text_sig:
# If 'obj' class has a __text_signature__ attribute:
# return a signature based on it
return _signature_fromstr(sigcls, obj, text_sig)
# No '__text_signature__' was found for the 'obj' class.
# Last option is to check if its '__init__' is
# object.__init__ or type.__init__.
if type not in obj.__mro__:
# We have a class (not metaclass), but no user-defined
# __init__ or __new__ for it
if (obj.__init__ is object.__init__ and
obj.__new__ is object.__new__):
# Return a signature of 'object' builtin.
return sigcls.from_callable(object)
else:
raise ValueError(
'no signature found for builtin type {!r}'.format(obj))
elif not isinstance(obj, _NonUserDefinedCallables):
# An object with __call__
# We also check that the 'obj' is not an instance of
# _WrapperDescriptor or _MethodWrapper to avoid
# infinite recursion (and even potential segfault)
call = _signature_get_user_defined_method(type(obj), '__call__')
if call is not None:
try:
sig = _signature_from_callable(
call,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
except ValueError as ex:
msg = 'no signature found for {!r}'.format(obj)
raise ValueError(msg) from ex
if sig is not None:
# For classes and objects we skip the first parameter of their
# __call__, __new__, or __init__ methods
if skip_bound_arg:
return _signature_bound_method(sig)
else:
return sig
if isinstance(obj, types.BuiltinFunctionType):
# Raise a nicer error message for builtins
msg = 'no signature found for builtin function {!r}'.format(obj)
raise ValueError(msg)
raise ValueError('callable {!r} is not supported by signature'.format(obj)) | [
"def",
"_signature_from_callable",
"(",
"obj",
",",
"*",
",",
"follow_wrapper_chains",
"=",
"True",
",",
"skip_bound_arg",
"=",
"True",
",",
"sigcls",
")",
":",
"if",
"not",
"callable",
"(",
"obj",
")",
":",
"raise",
"TypeError",
"(",
"'{!r} is not a callable ... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L2198-L2396 | ||
fossephate/JoyCon-Driver | 857e4e76e26f05d72400ae5d9f2a22cae88f3548 | joycon-driver/full/wxWidgets-3.0.3/build/bakefiles/wxwin.py | python | getVersion | () | return wxVersion | Returns wxWidgets version as a tuple: (major,minor,release). | Returns wxWidgets version as a tuple: (major,minor,release). | [
"Returns",
"wxWidgets",
"version",
"as",
"a",
"tuple",
":",
"(",
"major",
"minor",
"release",
")",
"."
] | def getVersion():
"""Returns wxWidgets version as a tuple: (major,minor,release)."""
global wxVersion
if wxVersion == None:
f = open(VERSION_FILE, 'rt')
lines = f.readlines()
f.close()
major = minor = release = None
for l in lines:
if not l.startswith('#define'): continue
splitline = l.strip().split()
if splitline[0] != '#define': continue
if len(splitline) < 3: continue
name = splitline[1]
value = splitline[2]
if value == None: continue
if name == 'wxMAJOR_VERSION': major = int(value)
if name == 'wxMINOR_VERSION': minor = int(value)
if name == 'wxRELEASE_NUMBER': release = int(value)
if major != None and minor != None and release != None:
break
wxVersion = (major, minor, release)
return wxVersion | [
"def",
"getVersion",
"(",
")",
":",
"global",
"wxVersion",
"if",
"wxVersion",
"==",
"None",
":",
"f",
"=",
"open",
"(",
"VERSION_FILE",
",",
"'rt'",
")",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"f",
".",
"close",
"(",
")",
"major",
"=",
"min... | https://github.com/fossephate/JoyCon-Driver/blob/857e4e76e26f05d72400ae5d9f2a22cae88f3548/joycon-driver/full/wxWidgets-3.0.3/build/bakefiles/wxwin.py#L103-L125 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/xml/sax/xmlreader.py | python | XMLReader.getFeature | (self, name) | Looks up and returns the state of a SAX2 feature. | Looks up and returns the state of a SAX2 feature. | [
"Looks",
"up",
"and",
"returns",
"the",
"state",
"of",
"a",
"SAX2",
"feature",
"."
] | def getFeature(self, name):
"Looks up and returns the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name) | [
"def",
"getFeature",
"(",
"self",
",",
"name",
")",
":",
"raise",
"SAXNotRecognizedException",
"(",
"\"Feature '%s' not recognized\"",
"%",
"name",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/xml/sax/xmlreader.py#L75-L77 | ||
clementine-player/Clementine | 111379dfd027802b59125829fcf87e3e1d0ad73b | dist/cpplint.py | python | NestingState.InAsmBlock | (self) | return self.stack and self.stack[-1].inline_asm != _NO_ASM | Check if we are currently one level inside an inline ASM block.
Returns:
True if the top of the stack is a block containing inline ASM. | Check if we are currently one level inside an inline ASM block. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"an",
"inline",
"ASM",
"block",
"."
] | def InAsmBlock(self):
"""Check if we are currently one level inside an inline ASM block.
Returns:
True if the top of the stack is a block containing inline ASM.
"""
return self.stack and self.stack[-1].inline_asm != _NO_ASM | [
"def",
"InAsmBlock",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"inline_asm",
"!=",
"_NO_ASM"
] | https://github.com/clementine-player/Clementine/blob/111379dfd027802b59125829fcf87e3e1d0ad73b/dist/cpplint.py#L2193-L2199 | |
lukasmonk/lucaschess | 13e2e5cb13b38a720ccf897af649054a64bcb914 | Code/SQL/DBFcache.py | python | DBFcache.skip | (self, num=1) | return self.goto(num + self.recno) | Salta un registro. | Salta un registro. | [
"Salta",
"un",
"registro",
"."
] | def skip(self, num=1):
"""
Salta un registro.
"""
return self.goto(num + self.recno) | [
"def",
"skip",
"(",
"self",
",",
"num",
"=",
"1",
")",
":",
"return",
"self",
".",
"goto",
"(",
"num",
"+",
"self",
".",
"recno",
")"
] | https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/SQL/DBFcache.py#L198-L202 | |
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/llvm/bindings/python/llvm/object.py | python | Relocation.cache | (self) | Cache all cacheable properties on this instance. | Cache all cacheable properties on this instance. | [
"Cache",
"all",
"cacheable",
"properties",
"on",
"this",
"instance",
"."
] | def cache(self):
"""Cache all cacheable properties on this instance."""
getattr(self, 'address')
getattr(self, 'offset')
getattr(self, 'symbol')
getattr(self, 'type')
getattr(self, 'type_name')
getattr(self, 'value_string') | [
"def",
"cache",
"(",
"self",
")",
":",
"getattr",
"(",
"self",
",",
"'address'",
")",
"getattr",
"(",
"self",
",",
"'offset'",
")",
"getattr",
"(",
"self",
",",
"'symbol'",
")",
"getattr",
"(",
"self",
",",
"'type'",
")",
"getattr",
"(",
"self",
",",... | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/llvm/bindings/python/llvm/object.py#L417-L424 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py | python | Filterer.removeFilter | (self, filter) | Remove the specified filter from this handler. | Remove the specified filter from this handler. | [
"Remove",
"the",
"specified",
"filter",
"from",
"this",
"handler",
"."
] | def removeFilter(self, filter):
"""
Remove the specified filter from this handler.
"""
if filter in self.filters:
self.filters.remove(filter) | [
"def",
"removeFilter",
"(",
"self",
",",
"filter",
")",
":",
"if",
"filter",
"in",
"self",
".",
"filters",
":",
"self",
".",
"filters",
".",
"remove",
"(",
"filter",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py#L729-L734 | ||
WeitaoVan/L-GM-loss | 598582f0631bac876b3eeb8d6c4cd1d780269e03 | scripts/cpp_lint.py | python | _CppLintState.SetOutputFormat | (self, output_format) | Sets the output format for errors. | Sets the output format for errors. | [
"Sets",
"the",
"output",
"format",
"for",
"errors",
"."
] | def SetOutputFormat(self, output_format):
"""Sets the output format for errors."""
self.output_format = output_format | [
"def",
"SetOutputFormat",
"(",
"self",
",",
"output_format",
")",
":",
"self",
".",
"output_format",
"=",
"output_format"
] | https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/scripts/cpp_lint.py#L703-L705 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | NativeFontInfo.GetUnderlined | (*args, **kwargs) | return _gdi_.NativeFontInfo_GetUnderlined(*args, **kwargs) | GetUnderlined(self) -> bool | GetUnderlined(self) -> bool | [
"GetUnderlined",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetUnderlined(*args, **kwargs):
"""GetUnderlined(self) -> bool"""
return _gdi_.NativeFontInfo_GetUnderlined(*args, **kwargs) | [
"def",
"GetUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"NativeFontInfo_GetUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L1889-L1891 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/secrets.py | python | token_hex | (nbytes=None) | return binascii.hexlify(token_bytes(nbytes)).decode('ascii') | Return a random text string, in hexadecimal.
The string has *nbytes* random bytes, each byte converted to two
hex digits. If *nbytes* is ``None`` or not supplied, a reasonable
default is used.
>>> token_hex(16) #doctest:+SKIP
'f9bf78b9a18ce6d46a0cd2b0b86df9da' | Return a random text string, in hexadecimal. | [
"Return",
"a",
"random",
"text",
"string",
"in",
"hexadecimal",
"."
] | def token_hex(nbytes=None):
"""Return a random text string, in hexadecimal.
The string has *nbytes* random bytes, each byte converted to two
hex digits. If *nbytes* is ``None`` or not supplied, a reasonable
default is used.
>>> token_hex(16) #doctest:+SKIP
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
"""
return binascii.hexlify(token_bytes(nbytes)).decode('ascii') | [
"def",
"token_hex",
"(",
"nbytes",
"=",
"None",
")",
":",
"return",
"binascii",
".",
"hexlify",
"(",
"token_bytes",
"(",
"nbytes",
")",
")",
".",
"decode",
"(",
"'ascii'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/secrets.py#L48-L59 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py | python | LabeledScale._get_value | (self) | return self._variable.get() | Return current scale value. | Return current scale value. | [
"Return",
"current",
"scale",
"value",
"."
] | def _get_value(self):
"""Return current scale value."""
return self._variable.get() | [
"def",
"_get_value",
"(",
"self",
")",
":",
"return",
"self",
".",
"_variable",
".",
"get",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py#L1540-L1542 | |
microsoft/EdgeML | ef9f8a77f096acbdeb941014791f8eda1c1bc35b | examples/tf/Bonsai/helpermethods.py | python | getQuantArgs | () | return parser.parse_args() | Function to parse arguments for Model Quantisation | Function to parse arguments for Model Quantisation | [
"Function",
"to",
"parse",
"arguments",
"for",
"Model",
"Quantisation"
] | def getQuantArgs():
'''
Function to parse arguments for Model Quantisation
'''
parser = argparse.ArgumentParser(
description='Arguments for quantizing Fast models. ' +
'Works only for piece-wise linear non-linearities, ' +
'like relu, quantTanh, quantSigm (check rnn.py for the definitions)')
parser.add_argument('-dir', '--model-dir', required=True,
help='model directory containing' +
'*.npy weight files dumped from the trained model')
parser.add_argument('-m', '--max-val', type=checkIntNneg, default=127,
help='this represents the maximum possible value ' +
'in model, essentially the byte complexity, ' +
'127=> 1 byte is default')
return parser.parse_args() | [
"def",
"getQuantArgs",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Arguments for quantizing Fast models. '",
"+",
"'Works only for piece-wise linear non-linearities, '",
"+",
"'like relu, quantTanh, quantSigm (check rnn.py for the def... | https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/examples/tf/Bonsai/helpermethods.py#L123-L139 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Wm.wm_attributes | (self, *args) | return self.tk.call(args) | This subcommand returns or sets platform specific attributes
The first form returns a list of the platform specific flags and
their values. The second form returns the value for the specific
option. The third form sets one or more of the values. The values
are as follows:
On Windows, -disabled gets or sets whether the window is in a
disabled state. -toolwindow gets or sets the style of the window
to toolwindow (as defined in the MSDN). -topmost gets or sets
whether this is a topmost window (displays above all other
windows).
On Macintosh, XXXXX
On Unix, there are currently no special attribute values. | This subcommand returns or sets platform specific attributes | [
"This",
"subcommand",
"returns",
"or",
"sets",
"platform",
"specific",
"attributes"
] | def wm_attributes(self, *args):
"""This subcommand returns or sets platform specific attributes
The first form returns a list of the platform specific flags and
their values. The second form returns the value for the specific
option. The third form sets one or more of the values. The values
are as follows:
On Windows, -disabled gets or sets whether the window is in a
disabled state. -toolwindow gets or sets the style of the window
to toolwindow (as defined in the MSDN). -topmost gets or sets
whether this is a topmost window (displays above all other
windows).
On Macintosh, XXXXX
On Unix, there are currently no special attribute values.
"""
args = ('wm', 'attributes', self._w) + args
return self.tk.call(args) | [
"def",
"wm_attributes",
"(",
"self",
",",
"*",
"args",
")",
":",
"args",
"=",
"(",
"'wm'",
",",
"'attributes'",
",",
"self",
".",
"_w",
")",
"+",
"args",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"args",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L1611-L1630 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | MemoizedZipManifests.load | (self, path) | return self[path].manifest | Load a manifest at path or return a suitable manifest already loaded. | Load a manifest at path or return a suitable manifest already loaded. | [
"Load",
"a",
"manifest",
"at",
"path",
"or",
"return",
"a",
"suitable",
"manifest",
"already",
"loaded",
"."
] | def load(self, path):
"""
Load a manifest at path or return a suitable manifest already loaded.
"""
path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if path not in self or self[path].mtime != mtime:
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
return self[path].manifest | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"mtime",
"=",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mtime",
"if",
"path",
"not",
"in",
"self",
"or",
"self",
"[",
"pat... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L1669-L1680 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/os2emxpath.py | python | join | (a, *p) | return path | Join two or more pathname components, inserting sep as needed | Join two or more pathname components, inserting sep as needed | [
"Join",
"two",
"or",
"more",
"pathname",
"components",
"inserting",
"sep",
"as",
"needed"
] | def join(a, *p):
"""Join two or more pathname components, inserting sep as needed"""
path = a
for b in p:
if isabs(b):
path = b
elif path == '' or path[-1:] in '/\\:':
path = path + b
else:
path = path + '/' + b
return path | [
"def",
"join",
"(",
"a",
",",
"*",
"p",
")",
":",
"path",
"=",
"a",
"for",
"b",
"in",
"p",
":",
"if",
"isabs",
"(",
"b",
")",
":",
"path",
"=",
"b",
"elif",
"path",
"==",
"''",
"or",
"path",
"[",
"-",
"1",
":",
"]",
"in",
"'/\\\\:'",
":",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/os2emxpath.py#L45-L55 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | GridEditorCreatedEvent.__init__ | (self, *args, **kwargs) | __init__(self, int id, EventType type, Object obj, int row, int col,
Control ctrl) -> GridEditorCreatedEvent | __init__(self, int id, EventType type, Object obj, int row, int col,
Control ctrl) -> GridEditorCreatedEvent | [
"__init__",
"(",
"self",
"int",
"id",
"EventType",
"type",
"Object",
"obj",
"int",
"row",
"int",
"col",
"Control",
"ctrl",
")",
"-",
">",
"GridEditorCreatedEvent"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, int id, EventType type, Object obj, int row, int col,
Control ctrl) -> GridEditorCreatedEvent
"""
_grid.GridEditorCreatedEvent_swiginit(self,_grid.new_GridEditorCreatedEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_grid",
".",
"GridEditorCreatedEvent_swiginit",
"(",
"self",
",",
"_grid",
".",
"new_GridEditorCreatedEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L2461-L2466 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site.py | python | getsitepackages | (prefixes=None) | return sitepackages | Returns a list containing all global site-packages directories.
For each directory present in ``prefixes`` (or the global ``PREFIXES``),
this function will find its `site-packages` subdirectory depending on the
system environment, and will return a list of full paths. | Returns a list containing all global site-packages directories. | [
"Returns",
"a",
"list",
"containing",
"all",
"global",
"site",
"-",
"packages",
"directories",
"."
] | def getsitepackages(prefixes=None):
"""Returns a list containing all global site-packages directories.
For each directory present in ``prefixes`` (or the global ``PREFIXES``),
this function will find its `site-packages` subdirectory depending on the
system environment, and will return a list of full paths.
"""
sitepackages = []
seen = set()
if prefixes is None:
prefixes = PREFIXES
for prefix in prefixes:
if not prefix or prefix in seen:
continue
seen.add(prefix)
if os.sep == '/':
sitepackages.append(os.path.join(prefix, "lib",
"python%d.%d" % sys.version_info[:2],
"site-packages"))
else:
sitepackages.append(prefix)
sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
return sitepackages | [
"def",
"getsitepackages",
"(",
"prefixes",
"=",
"None",
")",
":",
"sitepackages",
"=",
"[",
"]",
"seen",
"=",
"set",
"(",
")",
"if",
"prefixes",
"is",
"None",
":",
"prefixes",
"=",
"PREFIXES",
"for",
"prefix",
"in",
"prefixes",
":",
"if",
"not",
"prefi... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site.py#L318-L343 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/sdist.py | python | sdist._cs_path_exists | (fspath) | return filename in os.listdir(directory) | Case-sensitive path existence check
>>> sdist._cs_path_exists(__file__)
True
>>> sdist._cs_path_exists(__file__.upper())
False | Case-sensitive path existence check | [
"Case",
"-",
"sensitive",
"path",
"existence",
"check"
] | def _cs_path_exists(fspath):
"""
Case-sensitive path existence check
>>> sdist._cs_path_exists(__file__)
True
>>> sdist._cs_path_exists(__file__.upper())
False
"""
if not os.path.exists(fspath):
return False
# make absolute so we always have a directory
abspath = os.path.abspath(fspath)
directory, filename = os.path.split(abspath)
return filename in os.listdir(directory) | [
"def",
"_cs_path_exists",
"(",
"fspath",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fspath",
")",
":",
"return",
"False",
"# make absolute so we always have a directory",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"fspath",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/sdist.py#L233-L247 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/mac_tool.py | python | MacTool.ExecMergeInfoPlist | (self, output, *inputs) | Merge multiple .plist files into a single .plist file. | Merge multiple .plist files into a single .plist file. | [
"Merge",
"multiple",
".",
"plist",
"files",
"into",
"a",
"single",
".",
"plist",
"file",
"."
] | def ExecMergeInfoPlist(self, output, *inputs):
"""Merge multiple .plist files into a single .plist file."""
merged_plist = {}
for path in inputs:
plist = self._LoadPlistMaybeBinary(path)
self._MergePlist(merged_plist, plist)
plistlib.writePlist(merged_plist, output) | [
"def",
"ExecMergeInfoPlist",
"(",
"self",
",",
"output",
",",
"*",
"inputs",
")",
":",
"merged_plist",
"=",
"{",
"}",
"for",
"path",
"in",
"inputs",
":",
"plist",
"=",
"self",
".",
"_LoadPlistMaybeBinary",
"(",
"path",
")",
"self",
".",
"_MergePlist",
"(... | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/mac_tool.py#L363-L369 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/llvm/bindings/python/llvm/object.py | python | Section.cache | (self) | Cache properties of this Section.
This can be called as a workaround to the single active Section
limitation. When called, the properties of the Section are fetched so
they are still available after the Section has been marked inactive. | Cache properties of this Section. | [
"Cache",
"properties",
"of",
"this",
"Section",
"."
] | def cache(self):
"""Cache properties of this Section.
This can be called as a workaround to the single active Section
limitation. When called, the properties of the Section are fetched so
they are still available after the Section has been marked inactive.
"""
getattr(self, 'name')
getattr(self, 'size')
getattr(self, 'contents')
getattr(self, 'address') | [
"def",
"cache",
"(",
"self",
")",
":",
"getattr",
"(",
"self",
",",
"'name'",
")",
"getattr",
"(",
"self",
",",
"'size'",
")",
"getattr",
"(",
"self",
",",
"'contents'",
")",
"getattr",
"(",
"self",
",",
"'address'",
")"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/llvm/bindings/python/llvm/object.py#L270-L280 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py | python | RawTurtle._update | (self) | Perform a Turtle-data update. | Perform a Turtle-data update. | [
"Perform",
"a",
"Turtle",
"-",
"data",
"update",
"."
] | def _update(self):
"""Perform a Turtle-data update.
"""
screen = self.screen
if screen._tracing == 0:
return
elif screen._tracing == 1:
self._update_data()
self._drawturtle()
screen._update() # TurtleScreenBase
screen._delay(screen._delayvalue) # TurtleScreenBase
else:
self._update_data()
if screen._updatecounter == 0:
for t in screen.turtles():
t._drawturtle()
screen._update() | [
"def",
"_update",
"(",
"self",
")",
":",
"screen",
"=",
"self",
".",
"screen",
"if",
"screen",
".",
"_tracing",
"==",
"0",
":",
"return",
"elif",
"screen",
".",
"_tracing",
"==",
"1",
":",
"self",
".",
"_update_data",
"(",
")",
"self",
".",
"_drawtur... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L2557-L2573 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | Decimal.is_signed | (self) | return self._sign == 1 | Return True if self is negative; otherwise return False. | Return True if self is negative; otherwise return False. | [
"Return",
"True",
"if",
"self",
"is",
"negative",
";",
"otherwise",
"return",
"False",
"."
] | def is_signed(self):
"""Return True if self is negative; otherwise return False."""
return self._sign == 1 | [
"def",
"is_signed",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sign",
"==",
"1"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L3043-L3045 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/command/explore.py | python | CompoundExplorer.explore_expr | (expr, value, is_child) | return False | Function to explore structs/classes and union values.
See Explorer.explore_expr for more information. | Function to explore structs/classes and union values.
See Explorer.explore_expr for more information. | [
"Function",
"to",
"explore",
"structs",
"/",
"classes",
"and",
"union",
"values",
".",
"See",
"Explorer",
".",
"explore_expr",
"for",
"more",
"information",
"."
] | def explore_expr(expr, value, is_child):
"""Function to explore structs/classes and union values.
See Explorer.explore_expr for more information.
"""
datatype = value.type
type_code = datatype.code
fields = datatype.fields()
if type_code == gdb.TYPE_CODE_STRUCT:
type_desc = "struct/class"
else:
type_desc = "union"
if CompoundExplorer._get_real_field_count(fields) == 0:
print ("The value of '%s' is a %s of type '%s' with no fields." %
(expr, type_desc, str(value.type)))
if is_child:
Explorer.return_to_parent_value_prompt()
return False
print ("The value of '%s' is a %s of type '%s' with the following "
"fields:\n" % (expr, type_desc, str(value.type)))
has_explorable_fields = False
choice_to_compound_field_map = { }
current_choice = 0
print_list = [ ]
for field in fields:
if field.artificial:
continue
field_full_name = Explorer.guard_expr(expr) + "." + field.name
if field.is_base_class:
field_value = value.cast(field.type)
else:
field_value = value[field.name]
literal_value = ""
if type_code == gdb.TYPE_CODE_UNION:
literal_value = ("<Enter %d to explore this field of type "
"'%s'>" % (current_choice, str(field.type)))
has_explorable_fields = True
else:
if Explorer.is_scalar_type(field.type):
literal_value = ("%s .. (Value of type '%s')" %
(str(field_value), str(field.type)))
else:
if field.is_base_class:
field_desc = "base class"
else:
field_desc = "field"
literal_value = ("<Enter %d to explore this %s of type "
"'%s'>" %
(current_choice, field_desc,
str(field.type)))
has_explorable_fields = True
choice_to_compound_field_map[str(current_choice)] = (
field_full_name, field_value)
current_choice = current_choice + 1
print_list.append((field.name, literal_value))
CompoundExplorer._print_fields(print_list)
print ("")
if has_explorable_fields:
choice = raw_input("Enter the field number of choice: ")
if choice in choice_to_compound_field_map:
Explorer.explore_expr(choice_to_compound_field_map[choice][0],
choice_to_compound_field_map[choice][1],
True)
return True
else:
if is_child:
Explorer.return_to_parent_value()
else:
if is_child:
Explorer.return_to_parent_value_prompt()
return False | [
"def",
"explore_expr",
"(",
"expr",
",",
"value",
",",
"is_child",
")",
":",
"datatype",
"=",
"value",
".",
"type",
"type_code",
"=",
"datatype",
".",
"code",
"fields",
"=",
"datatype",
".",
"fields",
"(",
")",
"if",
"type_code",
"==",
"gdb",
".",
"TYP... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/command/explore.py#L392-L470 | |
linyouhappy/kongkongxiyou | 7a69b2913eb29f4be77f9a62fb90cdd72c4160f1 | cocosjs/frameworks/runtime-src/proj.android/build_native.py | python | check_environment_variables | () | return NDK_ROOT | Checking the environment NDK_ROOT, which will be used for building | Checking the environment NDK_ROOT, which will be used for building | [
"Checking",
"the",
"environment",
"NDK_ROOT",
"which",
"will",
"be",
"used",
"for",
"building"
] | def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building
'''
try:
NDK_ROOT = os.environ['NDK_ROOT']
except Exception:
print "NDK_ROOT not defined. Please define NDK_ROOT in your environment"
sys.exit(1)
return NDK_ROOT | [
"def",
"check_environment_variables",
"(",
")",
":",
"try",
":",
"NDK_ROOT",
"=",
"os",
".",
"environ",
"[",
"'NDK_ROOT'",
"]",
"except",
"Exception",
":",
"print",
"\"NDK_ROOT not defined. Please define NDK_ROOT in your environment\"",
"sys",
".",
"exit",
"(",
"1",
... | https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/runtime-src/proj.android/build_native.py#L30-L40 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/svm/base.py | python | BaseLibSVM.decision_function | (self, X) | return self._decision_function(X) | Distance of the samples X to the separating hyperplane.
Parameters
----------
X : array-like, shape (n_samples, n_features)
For kernel="precomputed", the expected shape of X is
[n_samples_test, n_samples_train].
Returns
-------
X : array-like, shape (n_samples, n_class * (n_class-1) / 2)
Returns the decision function of the sample for each class
in the model. | Distance of the samples X to the separating hyperplane. | [
"Distance",
"of",
"the",
"samples",
"X",
"to",
"the",
"separating",
"hyperplane",
"."
] | def decision_function(self, X):
"""Distance of the samples X to the separating hyperplane.
Parameters
----------
X : array-like, shape (n_samples, n_features)
For kernel="precomputed", the expected shape of X is
[n_samples_test, n_samples_train].
Returns
-------
X : array-like, shape (n_samples, n_class * (n_class-1) / 2)
Returns the decision function of the sample for each class
in the model.
"""
return self._decision_function(X) | [
"def",
"decision_function",
"(",
"self",
",",
"X",
")",
":",
"return",
"self",
".",
"_decision_function",
"(",
"X",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/svm/base.py#L372-L387 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py | python | _GatherDropNegatives | (params,
ids,
zero_clipped_indices=None,
is_positive=None) | return (array_ops.where(is_positive, gathered, zero_slice),
zero_clipped_indices, is_positive) | Helper function for unsorted segment ops.
Gathers params for
positive segment ids and gathers 0 for inputs with negative segment id.
Also returns the clipped indices and a boolean mask with the same shape
as ids where a positive id is masked as true. With this, the latter two
can be passed as arguments to this function to reuse them. | Helper function for unsorted segment ops. | [
"Helper",
"function",
"for",
"unsorted",
"segment",
"ops",
"."
] | def _GatherDropNegatives(params,
ids,
zero_clipped_indices=None,
is_positive=None):
""" Helper function for unsorted segment ops.
Gathers params for
positive segment ids and gathers 0 for inputs with negative segment id.
Also returns the clipped indices and a boolean mask with the same shape
as ids where a positive id is masked as true. With this, the latter two
can be passed as arguments to this function to reuse them.
"""
if zero_clipped_indices is None:
zero_clipped_indices = math_ops.maximum(ids, array_ops.zeros_like(ids))
gathered = array_ops.gather(params, zero_clipped_indices)
if is_positive is None:
is_positive = math_ops.greater_equal(ids, 0)
# tf.where(condition, x, y) requires condition to have the same shape as x
# and y.
# todo(philjd): remove this if tf.where supports broadcasting (#9284)
for _ in range(gathered.shape.ndims - is_positive.shape.ndims):
is_positive = array_ops.expand_dims(is_positive, -1)
is_positive = (
is_positive & array_ops.ones_like(gathered, dtype=dtypes.bool))
# replace gathered params of negative indices with 0
zero_slice = array_ops.zeros_like(gathered)
return (array_ops.where(is_positive, gathered, zero_slice),
zero_clipped_indices, is_positive) | [
"def",
"_GatherDropNegatives",
"(",
"params",
",",
"ids",
",",
"zero_clipped_indices",
"=",
"None",
",",
"is_positive",
"=",
"None",
")",
":",
"if",
"zero_clipped_indices",
"is",
"None",
":",
"zero_clipped_indices",
"=",
"math_ops",
".",
"maximum",
"(",
"ids",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py#L398-L425 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.