nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | PyPanel.DoSetSize | (*args, **kwargs) | return _windows_.PyPanel_DoSetSize(*args, **kwargs) | DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO) | DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO) | [
"DoSetSize",
"(",
"self",
"int",
"x",
"int",
"y",
"int",
"width",
"int",
"height",
"int",
"sizeFlags",
"=",
"SIZE_AUTO",
")"
] | def DoSetSize(*args, **kwargs):
"""DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO)"""
return _windows_.PyPanel_DoSetSize(*args, **kwargs) | [
"def",
"DoSetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PyPanel_DoSetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L4333-L4335 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/matlib.py | python | rand | (*args) | return asmatrix(np.random.rand(*args)) | Return a matrix of random values with given shape.
Create a matrix of the given shape and propagate it with
random samples from a uniform distribution over ``[0, 1)``.
Parameters
----------
\\*args : Arguments
Shape of the output.
If given as N integers, each integer specifies the size of one
dimension.
If given as a tuple, this tuple gives the complete shape.
Returns
-------
out : ndarray
The matrix of random values with shape given by `\\*args`.
See Also
--------
randn, numpy.random.rand
Examples
--------
>>> import numpy.matlib
>>> np.matlib.rand(2, 3)
matrix([[ 0.68340382, 0.67926887, 0.83271405],
[ 0.00793551, 0.20468222, 0.95253525]]) #random
>>> np.matlib.rand((2, 3))
matrix([[ 0.84682055, 0.73626594, 0.11308016],
[ 0.85429008, 0.3294825 , 0.89139555]]) #random
If the first argument is a tuple, other arguments are ignored:
>>> np.matlib.rand((2, 3), 4)
matrix([[ 0.46898646, 0.15163588, 0.95188261],
[ 0.59208621, 0.09561818, 0.00583606]]) #random | Return a matrix of random values with given shape. | [
"Return",
"a",
"matrix",
"of",
"random",
"values",
"with",
"given",
"shape",
"."
] | def rand(*args):
"""
Return a matrix of random values with given shape.
Create a matrix of the given shape and propagate it with
random samples from a uniform distribution over ``[0, 1)``.
Parameters
----------
\\*args : Arguments
Shape of the output.
If given as N integers, each integer specifies the size of one
dimension.
If given as a tuple, this tuple gives the complete shape.
Returns
-------
out : ndarray
The matrix of random values with shape given by `\\*args`.
See Also
--------
randn, numpy.random.rand
Examples
--------
>>> import numpy.matlib
>>> np.matlib.rand(2, 3)
matrix([[ 0.68340382, 0.67926887, 0.83271405],
[ 0.00793551, 0.20468222, 0.95253525]]) #random
>>> np.matlib.rand((2, 3))
matrix([[ 0.84682055, 0.73626594, 0.11308016],
[ 0.85429008, 0.3294825 , 0.89139555]]) #random
If the first argument is a tuple, other arguments are ignored:
>>> np.matlib.rand((2, 3), 4)
matrix([[ 0.46898646, 0.15163588, 0.95188261],
[ 0.59208621, 0.09561818, 0.00583606]]) #random
"""
if isinstance(args[0], tuple):
args = args[0]
return asmatrix(np.random.rand(*args)) | [
"def",
"rand",
"(",
"*",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"tuple",
")",
":",
"args",
"=",
"args",
"[",
"0",
"]",
"return",
"asmatrix",
"(",
"np",
".",
"random",
".",
"rand",
"(",
"*",
"args",
")",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/matlib.py#L213-L256 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arraylike.py | python | _is_aligned | (frame, other) | Helper to check if a DataFrame is aligned with another DataFrame or Series. | Helper to check if a DataFrame is aligned with another DataFrame or Series. | [
"Helper",
"to",
"check",
"if",
"a",
"DataFrame",
"is",
"aligned",
"with",
"another",
"DataFrame",
"or",
"Series",
"."
] | def _is_aligned(frame, other):
"""
Helper to check if a DataFrame is aligned with another DataFrame or Series.
"""
from pandas import DataFrame
if isinstance(other, DataFrame):
return frame._indexed_same(other)
else:
# Series -> match index
return frame.columns.equals(other.index) | [
"def",
"_is_aligned",
"(",
"frame",
",",
"other",
")",
":",
"from",
"pandas",
"import",
"DataFrame",
"if",
"isinstance",
"(",
"other",
",",
"DataFrame",
")",
":",
"return",
"frame",
".",
"_indexed_same",
"(",
"other",
")",
"else",
":",
"# Series -> match index",
"return",
"frame",
".",
"columns",
".",
"equals",
"(",
"other",
".",
"index",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arraylike.py#L159-L169 | ||
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/mapshow/libs/map.py | python | Map._draw_stop_line | (line_segment, label, ax, label_color_val) | draw a signal | draw a signal | [
"draw",
"a",
"signal"
] | def _draw_stop_line(line_segment, label, ax, label_color_val):
"""draw a signal"""
px = []
py = []
for p in line_segment.point:
px.append(float(p.x))
py.append(float(p.y))
ax.plot(px, py, 'o-')
lxy = [random.randint(20, 80) * random.sample([-1, 1], 1)[0],
random.randint(20, 80) * random.sample([-1, 1], 1)[0]]
xy = (sum(px) // len(px), sum(py) // len(py))
plt.annotate(
label,
xy=xy, xytext=lxy,
textcoords='offset points',
bbox=dict(boxstyle='round,pad=0.5', fc=label_color_val, alpha=0.5),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')) | [
"def",
"_draw_stop_line",
"(",
"line_segment",
",",
"label",
",",
"ax",
",",
"label_color_val",
")",
":",
"px",
"=",
"[",
"]",
"py",
"=",
"[",
"]",
"for",
"p",
"in",
"line_segment",
".",
"point",
":",
"px",
".",
"append",
"(",
"float",
"(",
"p",
".",
"x",
")",
")",
"py",
".",
"append",
"(",
"float",
"(",
"p",
".",
"y",
")",
")",
"ax",
".",
"plot",
"(",
"px",
",",
"py",
",",
"'o-'",
")",
"lxy",
"=",
"[",
"random",
".",
"randint",
"(",
"20",
",",
"80",
")",
"*",
"random",
".",
"sample",
"(",
"[",
"-",
"1",
",",
"1",
"]",
",",
"1",
")",
"[",
"0",
"]",
",",
"random",
".",
"randint",
"(",
"20",
",",
"80",
")",
"*",
"random",
".",
"sample",
"(",
"[",
"-",
"1",
",",
"1",
"]",
",",
"1",
")",
"[",
"0",
"]",
"]",
"xy",
"=",
"(",
"sum",
"(",
"px",
")",
"//",
"len",
"(",
"px",
")",
",",
"sum",
"(",
"py",
")",
"//",
"len",
"(",
"py",
")",
")",
"plt",
".",
"annotate",
"(",
"label",
",",
"xy",
"=",
"xy",
",",
"xytext",
"=",
"lxy",
",",
"textcoords",
"=",
"'offset points'",
",",
"bbox",
"=",
"dict",
"(",
"boxstyle",
"=",
"'round,pad=0.5'",
",",
"fc",
"=",
"label_color_val",
",",
"alpha",
"=",
"0.5",
")",
",",
"arrowprops",
"=",
"dict",
"(",
"arrowstyle",
"=",
"'->'",
",",
"connectionstyle",
"=",
"'arc3,rad=0'",
")",
")"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/mapshow/libs/map.py#L273-L289 | ||
NVIDIA/MDL-SDK | aa9642b2546ad7b6236b5627385d882c2ed83c5d | src/mdl/jit/llvm/dist/examples/Kaleidoscope/MCJIT/complete/genk-timing.py | python | KScriptGenerator.setCallWeighting | (self, weight) | Sets the probably of generating a function call | Sets the probably of generating a function call | [
"Sets",
"the",
"probably",
"of",
"generating",
"a",
"function",
"call"
] | def setCallWeighting(self, weight):
""" Sets the probably of generating a function call"""
self.callWeighting = weight | [
"def",
"setCallWeighting",
"(",
"self",
",",
"weight",
")",
":",
"self",
".",
"callWeighting",
"=",
"weight"
] | https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/llvm/dist/examples/Kaleidoscope/MCJIT/complete/genk-timing.py#L85-L87 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py | python | TarFile.close | (self) | Close the TarFile. In write-mode, two finishing zero blocks are
appended to the archive. | Close the TarFile. In write-mode, two finishing zero blocks are
appended to the archive. | [
"Close",
"the",
"TarFile",
".",
"In",
"write",
"-",
"mode",
"two",
"finishing",
"zero",
"blocks",
"are",
"appended",
"to",
"the",
"archive",
"."
] | def close(self):
"""Close the TarFile. In write-mode, two finishing zero blocks are
appended to the archive.
"""
if self.closed:
return
if self.mode in "aw":
self.fileobj.write(NUL * (BLOCKSIZE * 2))
self.offset += (BLOCKSIZE * 2)
# fill up the end with zero-blocks
# (like option -b20 for tar does)
blocks, remainder = divmod(self.offset, RECORDSIZE)
if remainder > 0:
self.fileobj.write(NUL * (RECORDSIZE - remainder))
if not self._extfileobj:
self.fileobj.close()
self.closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"return",
"if",
"self",
".",
"mode",
"in",
"\"aw\"",
":",
"self",
".",
"fileobj",
".",
"write",
"(",
"NUL",
"*",
"(",
"BLOCKSIZE",
"*",
"2",
")",
")",
"self",
".",
"offset",
"+=",
"(",
"BLOCKSIZE",
"*",
"2",
")",
"# fill up the end with zero-blocks",
"# (like option -b20 for tar does)",
"blocks",
",",
"remainder",
"=",
"divmod",
"(",
"self",
".",
"offset",
",",
"RECORDSIZE",
")",
"if",
"remainder",
">",
"0",
":",
"self",
".",
"fileobj",
".",
"write",
"(",
"NUL",
"*",
"(",
"RECORDSIZE",
"-",
"remainder",
")",
")",
"if",
"not",
"self",
".",
"_extfileobj",
":",
"self",
".",
"fileobj",
".",
"close",
"(",
")",
"self",
".",
"closed",
"=",
"True"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py#L1864-L1882 | ||
facebook/hhvm | cd8d20db628e93583fffa0194aaca937af9b2692 | hphp/tools/gdb/hhbc.py | python | HHBC.op_name | (op) | return op_table(table_name).cast(table_type)[as_idx(op)] | Return the name of HPHP::Op `op'. | Return the name of HPHP::Op `op'. | [
"Return",
"the",
"name",
"of",
"HPHP",
"::",
"Op",
"op",
"."
] | def op_name(op):
"""Return the name of HPHP::Op `op'."""
table_name = 'HPHP::opcodeToNameTable'
table_type = T('char').pointer().pointer()
return op_table(table_name).cast(table_type)[as_idx(op)] | [
"def",
"op_name",
"(",
"op",
")",
":",
"table_name",
"=",
"'HPHP::opcodeToNameTable'",
"table_type",
"=",
"T",
"(",
"'char'",
")",
".",
"pointer",
"(",
")",
".",
"pointer",
"(",
")",
"return",
"op_table",
"(",
"table_name",
")",
".",
"cast",
"(",
"table_type",
")",
"[",
"as_idx",
"(",
"op",
")",
"]"
] | https://github.com/facebook/hhvm/blob/cd8d20db628e93583fffa0194aaca937af9b2692/hphp/tools/gdb/hhbc.py#L177-L182 | |
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/site_packages/ordered_dict.py | python | OrderedDict.keys | (self) | return list(self) | od.keys() -> list of keys in od | od.keys() -> list of keys in od | [
"od",
".",
"keys",
"()",
"-",
">",
"list",
"of",
"keys",
"in",
"od"
] | def keys(self):
'od.keys() -> list of keys in od'
return list(self) | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
")"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/ordered_dict.py#L116-L118 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py | python | EmacsMode.reverse_search_history | (self, e) | Search backward starting at the current line and moving up
through the history as necessary. This is an incremental search. | Search backward starting at the current line and moving up
through the history as necessary. This is an incremental search. | [
"Search",
"backward",
"starting",
"at",
"the",
"current",
"line",
"and",
"moving",
"up",
"through",
"the",
"history",
"as",
"necessary",
".",
"This",
"is",
"an",
"incremental",
"search",
"."
] | def reverse_search_history(self, e): # (C-r)
'''Search backward starting at the current line and moving up
through the history as necessary. This is an incremental search.'''
self._i_search(self._history.reverse_search_history, -1, e) | [
"def",
"reverse_search_history",
"(",
"self",
",",
"e",
")",
":",
"# (C-r)",
"self",
".",
"_i_search",
"(",
"self",
".",
"_history",
".",
"reverse_search_history",
",",
"-",
"1",
",",
"e",
")"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py#L203-L206 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/v8/third_party/jinja2/compiler.py | python | CodeGenerator.return_buffer_contents | (self, frame, force_unescaped=False) | Return the buffer contents of the frame. | Return the buffer contents of the frame. | [
"Return",
"the",
"buffer",
"contents",
"of",
"the",
"frame",
"."
] | def return_buffer_contents(self, frame, force_unescaped=False):
"""Return the buffer contents of the frame."""
if not force_unescaped:
if frame.eval_ctx.volatile:
self.writeline('if context.eval_ctx.autoescape:')
self.indent()
self.writeline('return Markup(concat(%s))' % frame.buffer)
self.outdent()
self.writeline('else:')
self.indent()
self.writeline('return concat(%s)' % frame.buffer)
self.outdent()
return
elif frame.eval_ctx.autoescape:
self.writeline('return Markup(concat(%s))' % frame.buffer)
return
self.writeline('return concat(%s)' % frame.buffer) | [
"def",
"return_buffer_contents",
"(",
"self",
",",
"frame",
",",
"force_unescaped",
"=",
"False",
")",
":",
"if",
"not",
"force_unescaped",
":",
"if",
"frame",
".",
"eval_ctx",
".",
"volatile",
":",
"self",
".",
"writeline",
"(",
"'if context.eval_ctx.autoescape:'",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"writeline",
"(",
"'return Markup(concat(%s))'",
"%",
"frame",
".",
"buffer",
")",
"self",
".",
"outdent",
"(",
")",
"self",
".",
"writeline",
"(",
"'else:'",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"writeline",
"(",
"'return concat(%s)'",
"%",
"frame",
".",
"buffer",
")",
"self",
".",
"outdent",
"(",
")",
"return",
"elif",
"frame",
".",
"eval_ctx",
".",
"autoescape",
":",
"self",
".",
"writeline",
"(",
"'return Markup(concat(%s))'",
"%",
"frame",
".",
"buffer",
")",
"return",
"self",
".",
"writeline",
"(",
"'return concat(%s)'",
"%",
"frame",
".",
"buffer",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/compiler.py#L327-L343 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_SCHEME_MGF1.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(TPMS_SCHEME_MGF1) | Returns new TPMS_SCHEME_MGF1 object constructed from its marshaled
representation in the given byte buffer | Returns new TPMS_SCHEME_MGF1 object constructed from its marshaled
representation in the given byte buffer | [
"Returns",
"new",
"TPMS_SCHEME_MGF1",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new TPMS_SCHEME_MGF1 object constructed from its marshaled
representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(TPMS_SCHEME_MGF1) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"TPMS_SCHEME_MGF1",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L17909-L17913 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/core.py | python | parse_rosrpc_uri | (uri) | return dest_addr, dest_port | utility function for parsing ROS-RPC URIs
@param uri: ROSRPC URI
@type uri: str
@return: address, port
@rtype: (str, int)
@raise ParameterInvalid: if uri is not a valid ROSRPC URI | utility function for parsing ROS-RPC URIs | [
"utility",
"function",
"for",
"parsing",
"ROS",
"-",
"RPC",
"URIs"
] | def parse_rosrpc_uri(uri):
"""
utility function for parsing ROS-RPC URIs
@param uri: ROSRPC URI
@type uri: str
@return: address, port
@rtype: (str, int)
@raise ParameterInvalid: if uri is not a valid ROSRPC URI
"""
if uri.startswith(ROSRPC):
dest_addr = uri[len(ROSRPC):]
else:
raise ParameterInvalid("Invalid protocol for ROS service URL: %s"%uri)
try:
if '/' in dest_addr:
dest_addr = dest_addr[:dest_addr.find('/')]
dest_addr, dest_port = dest_addr.split(':')
dest_port = int(dest_port)
except:
raise ParameterInvalid("ROS service URL is invalid: %s"%uri)
return dest_addr, dest_port | [
"def",
"parse_rosrpc_uri",
"(",
"uri",
")",
":",
"if",
"uri",
".",
"startswith",
"(",
"ROSRPC",
")",
":",
"dest_addr",
"=",
"uri",
"[",
"len",
"(",
"ROSRPC",
")",
":",
"]",
"else",
":",
"raise",
"ParameterInvalid",
"(",
"\"Invalid protocol for ROS service URL: %s\"",
"%",
"uri",
")",
"try",
":",
"if",
"'/'",
"in",
"dest_addr",
":",
"dest_addr",
"=",
"dest_addr",
"[",
":",
"dest_addr",
".",
"find",
"(",
"'/'",
")",
"]",
"dest_addr",
",",
"dest_port",
"=",
"dest_addr",
".",
"split",
"(",
"':'",
")",
"dest_port",
"=",
"int",
"(",
"dest_port",
")",
"except",
":",
"raise",
"ParameterInvalid",
"(",
"\"ROS service URL is invalid: %s\"",
"%",
"uri",
")",
"return",
"dest_addr",
",",
"dest_port"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/core.py#L102-L122 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/traceback.py | python | walk_stack | (f) | Walk a stack yielding the frame and line number for each frame.
This will follow f.f_back from the given frame. If no frame is given, the
current stack is used. Usually used with StackSummary.extract. | Walk a stack yielding the frame and line number for each frame. | [
"Walk",
"a",
"stack",
"yielding",
"the",
"frame",
"and",
"line",
"number",
"for",
"each",
"frame",
"."
] | def walk_stack(f):
"""Walk a stack yielding the frame and line number for each frame.
This will follow f.f_back from the given frame. If no frame is given, the
current stack is used. Usually used with StackSummary.extract.
"""
if f is None:
f = sys._getframe().f_back.f_back
while f is not None:
yield f, f.f_lineno
f = f.f_back | [
"def",
"walk_stack",
"(",
"f",
")",
":",
"if",
"f",
"is",
"None",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
".",
"f_back",
"while",
"f",
"is",
"not",
"None",
":",
"yield",
"f",
",",
"f",
".",
"f_lineno",
"f",
"=",
"f",
".",
"f_back"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/traceback.py#L292-L302 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/metrics/python/metrics/classification.py | python | accuracy | (predictions, labels, weights=None) | Computes the percentage of times that predictions matches labels.
Args:
predictions: the predicted values, a `Tensor` whose dtype and shape
matches 'labels'.
labels: the ground truth values, a `Tensor` of any shape and
bool, integer, or string dtype.
weights: None or `Tensor` of float values to reweight the accuracy.
Returns:
Accuracy `Tensor`.
Raises:
ValueError: if dtypes don't match or
if dtype is not bool, integer, or string. | Computes the percentage of times that predictions matches labels. | [
"Computes",
"the",
"percentage",
"of",
"times",
"that",
"predictions",
"matches",
"labels",
"."
] | def accuracy(predictions, labels, weights=None):
"""Computes the percentage of times that predictions matches labels.
Args:
predictions: the predicted values, a `Tensor` whose dtype and shape
matches 'labels'.
labels: the ground truth values, a `Tensor` of any shape and
bool, integer, or string dtype.
weights: None or `Tensor` of float values to reweight the accuracy.
Returns:
Accuracy `Tensor`.
Raises:
ValueError: if dtypes don't match or
if dtype is not bool, integer, or string.
"""
if not (labels.dtype.is_integer or
labels.dtype in (dtypes.bool, dtypes.string)):
raise ValueError(
'Labels should have bool, integer, or string dtype, not %r' %
labels.dtype)
if not labels.dtype.is_compatible_with(predictions.dtype):
raise ValueError('Dtypes of predictions and labels should match. '
'Given: predictions (%r) and labels (%r)' %
(predictions.dtype, labels.dtype))
with ops.op_scope([predictions, labels], 'accuracy'):
is_correct = math_ops.cast(
math_ops.equal(predictions, labels), dtypes.float32)
if weights is not None:
is_correct = math_ops.mul(is_correct, weights)
return math_ops.reduce_mean(is_correct) | [
"def",
"accuracy",
"(",
"predictions",
",",
"labels",
",",
"weights",
"=",
"None",
")",
":",
"if",
"not",
"(",
"labels",
".",
"dtype",
".",
"is_integer",
"or",
"labels",
".",
"dtype",
"in",
"(",
"dtypes",
".",
"bool",
",",
"dtypes",
".",
"string",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Labels should have bool, integer, or string dtype, not %r'",
"%",
"labels",
".",
"dtype",
")",
"if",
"not",
"labels",
".",
"dtype",
".",
"is_compatible_with",
"(",
"predictions",
".",
"dtype",
")",
":",
"raise",
"ValueError",
"(",
"'Dtypes of predictions and labels should match. '",
"'Given: predictions (%r) and labels (%r)'",
"%",
"(",
"predictions",
".",
"dtype",
",",
"labels",
".",
"dtype",
")",
")",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"predictions",
",",
"labels",
"]",
",",
"'accuracy'",
")",
":",
"is_correct",
"=",
"math_ops",
".",
"cast",
"(",
"math_ops",
".",
"equal",
"(",
"predictions",
",",
"labels",
")",
",",
"dtypes",
".",
"float32",
")",
"if",
"weights",
"is",
"not",
"None",
":",
"is_correct",
"=",
"math_ops",
".",
"mul",
"(",
"is_correct",
",",
"weights",
")",
"return",
"math_ops",
".",
"reduce_mean",
"(",
"is_correct",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/metrics/python/metrics/classification.py#L28-L59 | ||
HKUST-Aerial-Robotics/Fast-Planner | 2ddd7793eecd573dbb5b47e2c985aa06606df3cf | uav_simulator/Utils/multi_map_server/quadrotor_msgs/src/quadrotor_msgs/msg/_AuxCommand.py | python | AuxCommand.serialize | (self, buff) | serialize message into buffer
:param buff: buffer, ``StringIO`` | serialize message into buffer
:param buff: buffer, ``StringIO`` | [
"serialize",
"message",
"into",
"buffer",
":",
"param",
"buff",
":",
"buffer",
"StringIO"
] | def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self
buff.write(_struct_2d.pack(_x.current_yaw, _x.kf_correction))
buff.write(_struct_2d.pack(*self.angle_corrections))
_x = self
buff.write(_struct_2B.pack(_x.enable_motors, _x.use_external_yaw))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x)))) | [
"def",
"serialize",
"(",
"self",
",",
"buff",
")",
":",
"try",
":",
"_x",
"=",
"self",
"buff",
".",
"write",
"(",
"_struct_2d",
".",
"pack",
"(",
"_x",
".",
"current_yaw",
",",
"_x",
".",
"kf_correction",
")",
")",
"buff",
".",
"write",
"(",
"_struct_2d",
".",
"pack",
"(",
"*",
"self",
".",
"angle_corrections",
")",
")",
"_x",
"=",
"self",
"buff",
".",
"write",
"(",
"_struct_2B",
".",
"pack",
"(",
"_x",
".",
"enable_motors",
",",
"_x",
".",
"use_external_yaw",
")",
")",
"except",
"struct",
".",
"error",
"as",
"se",
":",
"self",
".",
"_check_types",
"(",
"struct",
".",
"error",
"(",
"\"%s: '%s' when writing '%s'\"",
"%",
"(",
"type",
"(",
"se",
")",
",",
"str",
"(",
"se",
")",
",",
"str",
"(",
"_x",
")",
")",
")",
")",
"except",
"TypeError",
"as",
"te",
":",
"self",
".",
"_check_types",
"(",
"ValueError",
"(",
"\"%s: '%s' when writing '%s'\"",
"%",
"(",
"type",
"(",
"te",
")",
",",
"str",
"(",
"te",
")",
",",
"str",
"(",
"_x",
")",
")",
")",
")"
] | https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/multi_map_server/quadrotor_msgs/src/quadrotor_msgs/msg/_AuxCommand.py#L62-L74 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/third_party/jinja2/nodes.py | python | Node.find | (self, node_type) | Find the first node of a given type. If no such node exists the
return value is `None`. | Find the first node of a given type. If no such node exists the
return value is `None`. | [
"Find",
"the",
"first",
"node",
"of",
"a",
"given",
"type",
".",
"If",
"no",
"such",
"node",
"exists",
"the",
"return",
"value",
"is",
"None",
"."
] | def find(self, node_type):
"""Find the first node of a given type. If no such node exists the
return value is `None`.
"""
for result in self.find_all(node_type):
return result | [
"def",
"find",
"(",
"self",
",",
"node_type",
")",
":",
"for",
"result",
"in",
"self",
".",
"find_all",
"(",
"node_type",
")",
":",
"return",
"result"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/nodes.py#L177-L182 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/codecs.py | python | StreamWriter.__getattr__ | (self, name,
getattr=getattr) | return getattr(self.stream, name) | Inherit all other methods from the underlying stream. | Inherit all other methods from the underlying stream. | [
"Inherit",
"all",
"other",
"methods",
"from",
"the",
"underlying",
"stream",
"."
] | def __getattr__(self, name,
getattr=getattr):
""" Inherit all other methods from the underlying stream.
"""
return getattr(self.stream, name) | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
",",
"getattr",
"=",
"getattr",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"stream",
",",
"name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/codecs.py#L404-L409 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/futures.py | python | TransferCoordinator.add_failure_cleanup | (self, function, *args, **kwargs) | Adds a callback to call upon failure | Adds a callback to call upon failure | [
"Adds",
"a",
"callback",
"to",
"call",
"upon",
"failure"
] | def add_failure_cleanup(self, function, *args, **kwargs):
"""Adds a callback to call upon failure"""
with self._failure_cleanups_lock:
self._failure_cleanups.append(
FunctionContainer(function, *args, **kwargs)) | [
"def",
"add_failure_cleanup",
"(",
"self",
",",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_failure_cleanups_lock",
":",
"self",
".",
"_failure_cleanups",
".",
"append",
"(",
"FunctionContainer",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/futures.py#L353-L357 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py | python | KScriptGenerator.updateCalledFunctionList | (self, callee) | Maintains a list of functions that will actually be called | Maintains a list of functions that will actually be called | [
"Maintains",
"a",
"list",
"of",
"functions",
"that",
"will",
"actually",
"be",
"called"
] | def updateCalledFunctionList(self, callee):
"""Maintains a list of functions that will actually be called"""
# Update the total call count
self.updateTotalCallCount(callee)
# If this function is already in the list, don't do anything else
if callee in self.calledFunctions:
return
# Add this function to the list of those that will be called.
self.calledFunctions.append(callee)
# If this function calls other functions, add them too
if callee in self.calledFunctionTable:
for subCallee in self.calledFunctionTable[callee]:
self.updateCalledFunctionList(subCallee) | [
"def",
"updateCalledFunctionList",
"(",
"self",
",",
"callee",
")",
":",
"# Update the total call count",
"self",
".",
"updateTotalCallCount",
"(",
"callee",
")",
"# If this function is already in the list, don't do anything else",
"if",
"callee",
"in",
"self",
".",
"calledFunctions",
":",
"return",
"# Add this function to the list of those that will be called.",
"self",
".",
"calledFunctions",
".",
"append",
"(",
"callee",
")",
"# If this function calls other functions, add them too",
"if",
"callee",
"in",
"self",
".",
"calledFunctionTable",
":",
"for",
"subCallee",
"in",
"self",
".",
"calledFunctionTable",
"[",
"callee",
"]",
":",
"self",
".",
"updateCalledFunctionList",
"(",
"subCallee",
")"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py#L73-L85 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | TreeCtrl.ItemHasChildren | (*args, **kwargs) | return _controls_.TreeCtrl_ItemHasChildren(*args, **kwargs) | ItemHasChildren(self, TreeItemId item) -> bool | ItemHasChildren(self, TreeItemId item) -> bool | [
"ItemHasChildren",
"(",
"self",
"TreeItemId",
"item",
")",
"-",
">",
"bool"
] | def ItemHasChildren(*args, **kwargs):
"""ItemHasChildren(self, TreeItemId item) -> bool"""
return _controls_.TreeCtrl_ItemHasChildren(*args, **kwargs) | [
"def",
"ItemHasChildren",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_ItemHasChildren",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5335-L5337 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/managers.py | python | BaseManager.start | (self, initializer=None, initargs=()) | Spawn a server process for this manager object | Spawn a server process for this manager object | [
"Spawn",
"a",
"server",
"process",
"for",
"this",
"manager",
"object"
] | def start(self, initializer=None, initargs=()):
'''
Spawn a server process for this manager object
'''
if self._state.value != State.INITIAL:
if self._state.value == State.STARTED:
raise ProcessError("Already started server")
elif self._state.value == State.SHUTDOWN:
raise ProcessError("Manager has shut down")
else:
raise ProcessError(
"Unknown state {!r}".format(self._state.value))
if initializer is not None and not callable(initializer):
raise TypeError('initializer must be a callable')
# pipe over which we will retrieve address of server
reader, writer = connection.Pipe(duplex=False)
# spawn process which runs a server
self._process = self._ctx.Process(
target=type(self)._run_server,
args=(self._registry, self._address, self._authkey,
self._serializer, writer, initializer, initargs),
)
ident = ':'.join(str(i) for i in self._process._identity)
self._process.name = type(self).__name__ + '-' + ident
self._process.start()
# get address of server
writer.close()
self._address = reader.recv()
reader.close()
# register a finalizer
self._state.value = State.STARTED
self.shutdown = util.Finalize(
self, type(self)._finalize_manager,
args=(self._process, self._address, self._authkey,
self._state, self._Client),
exitpriority=0
) | [
"def",
"start",
"(",
"self",
",",
"initializer",
"=",
"None",
",",
"initargs",
"=",
"(",
")",
")",
":",
"if",
"self",
".",
"_state",
".",
"value",
"!=",
"State",
".",
"INITIAL",
":",
"if",
"self",
".",
"_state",
".",
"value",
"==",
"State",
".",
"STARTED",
":",
"raise",
"ProcessError",
"(",
"\"Already started server\"",
")",
"elif",
"self",
".",
"_state",
".",
"value",
"==",
"State",
".",
"SHUTDOWN",
":",
"raise",
"ProcessError",
"(",
"\"Manager has shut down\"",
")",
"else",
":",
"raise",
"ProcessError",
"(",
"\"Unknown state {!r}\"",
".",
"format",
"(",
"self",
".",
"_state",
".",
"value",
")",
")",
"if",
"initializer",
"is",
"not",
"None",
"and",
"not",
"callable",
"(",
"initializer",
")",
":",
"raise",
"TypeError",
"(",
"'initializer must be a callable'",
")",
"# pipe over which we will retrieve address of server",
"reader",
",",
"writer",
"=",
"connection",
".",
"Pipe",
"(",
"duplex",
"=",
"False",
")",
"# spawn process which runs a server",
"self",
".",
"_process",
"=",
"self",
".",
"_ctx",
".",
"Process",
"(",
"target",
"=",
"type",
"(",
"self",
")",
".",
"_run_server",
",",
"args",
"=",
"(",
"self",
".",
"_registry",
",",
"self",
".",
"_address",
",",
"self",
".",
"_authkey",
",",
"self",
".",
"_serializer",
",",
"writer",
",",
"initializer",
",",
"initargs",
")",
",",
")",
"ident",
"=",
"':'",
".",
"join",
"(",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"self",
".",
"_process",
".",
"_identity",
")",
"self",
".",
"_process",
".",
"name",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
"+",
"'-'",
"+",
"ident",
"self",
".",
"_process",
".",
"start",
"(",
")",
"# get address of server",
"writer",
".",
"close",
"(",
")",
"self",
".",
"_address",
"=",
"reader",
".",
"recv",
"(",
")",
"reader",
".",
"close",
"(",
")",
"# register a finalizer",
"self",
".",
"_state",
".",
"value",
"=",
"State",
".",
"STARTED",
"self",
".",
"shutdown",
"=",
"util",
".",
"Finalize",
"(",
"self",
",",
"type",
"(",
"self",
")",
".",
"_finalize_manager",
",",
"args",
"=",
"(",
"self",
".",
"_process",
",",
"self",
".",
"_address",
",",
"self",
".",
"_authkey",
",",
"self",
".",
"_state",
",",
"self",
".",
"_Client",
")",
",",
"exitpriority",
"=",
"0",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/managers.py#L536-L577 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py | python | ServerConnection.notice | (self, target, text) | Send a NOTICE command. | Send a NOTICE command. | [
"Send",
"a",
"NOTICE",
"command",
"."
] | def notice(self, target, text):
"""Send a NOTICE command."""
# Should limit len(text) here!
self.send_raw("NOTICE %s :%s" % (target, text)) | [
"def",
"notice",
"(",
"self",
",",
"target",
",",
"text",
")",
":",
"# Should limit len(text) here!",
"self",
".",
"send_raw",
"(",
"\"NOTICE %s :%s\"",
"%",
"(",
"target",
",",
"text",
")",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L735-L738 | ||
faasm/faasm | b3bc196d887adbd0bb9802bcb93323543bad59cb | faasmcli/faasmcli/tasks/docker_tasks.py | python | purge | (context) | Purge docker images | Purge docker images | [
"Purge",
"docker",
"images"
] | def purge(context):
"""
Purge docker images
"""
images_cmd = ["docker", "images", "-q", "-f", "dangling=true"]
cmd_out = run(images_cmd, stdout=PIPE, stderr=PIPE, check=True)
image_list = cmd_out.stdout
for img in image_list.decode().split("\n"):
if not img.strip():
continue
print("Removing {}".format(img))
cmd = ["docker", "rmi", "-f", img]
run(cmd, check=True) | [
"def",
"purge",
"(",
"context",
")",
":",
"images_cmd",
"=",
"[",
"\"docker\"",
",",
"\"images\"",
",",
"\"-q\"",
",",
"\"-f\"",
",",
"\"dangling=true\"",
"]",
"cmd_out",
"=",
"run",
"(",
"images_cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"check",
"=",
"True",
")",
"image_list",
"=",
"cmd_out",
".",
"stdout",
"for",
"img",
"in",
"image_list",
".",
"decode",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"not",
"img",
".",
"strip",
"(",
")",
":",
"continue",
"print",
"(",
"\"Removing {}\"",
".",
"format",
"(",
"img",
")",
")",
"cmd",
"=",
"[",
"\"docker\"",
",",
"\"rmi\"",
",",
"\"-f\"",
",",
"img",
"]",
"run",
"(",
"cmd",
",",
"check",
"=",
"True",
")"
] | https://github.com/faasm/faasm/blob/b3bc196d887adbd0bb9802bcb93323543bad59cb/faasmcli/faasmcli/tasks/docker_tasks.py#L16-L30 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/tbb_2020.3/python/tbb/pool.py | python | Job.__call__ | (self) | Call the function with the args/kwds and tell the ApplyResult
that its result is ready. Correctly handles the exceptions
happening during the execution of the function | Call the function with the args/kwds and tell the ApplyResult
that its result is ready. Correctly handles the exceptions
happening during the execution of the function | [
"Call",
"the",
"function",
"with",
"the",
"args",
"/",
"kwds",
"and",
"tell",
"the",
"ApplyResult",
"that",
"its",
"result",
"is",
"ready",
".",
"Correctly",
"handles",
"the",
"exceptions",
"happening",
"during",
"the",
"execution",
"of",
"the",
"function"
] | def __call__(self):
"""
Call the function with the args/kwds and tell the ApplyResult
that its result is ready. Correctly handles the exceptions
happening during the execution of the function
"""
try:
result = self._func(*self._args, **self._kwds)
except:
self._result._set_exception()
else:
self._result._set_value(result) | [
"def",
"__call__",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"_func",
"(",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwds",
")",
"except",
":",
"self",
".",
"_result",
".",
"_set_exception",
"(",
")",
"else",
":",
"self",
".",
"_result",
".",
"_set_value",
"(",
"result",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/tbb_2020.3/python/tbb/pool.py#L282-L293 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/backends/chrome/crx_id.py | python | HexToMPDecimal | (hex_chars) | return result | Convert bytes to an MPDecimal string. Example \x00 -> "aa"
This gives us the AppID for a chrome extension. | Convert bytes to an MPDecimal string. Example \x00 -> "aa"
This gives us the AppID for a chrome extension. | [
"Convert",
"bytes",
"to",
"an",
"MPDecimal",
"string",
".",
"Example",
"\\",
"x00",
"-",
">",
"aa",
"This",
"gives",
"us",
"the",
"AppID",
"for",
"a",
"chrome",
"extension",
"."
] | def HexToMPDecimal(hex_chars):
""" Convert bytes to an MPDecimal string. Example \x00 -> "aa"
This gives us the AppID for a chrome extension.
"""
result = ''
base = ord('a')
for i in xrange(len(hex_chars)):
value = ord(hex_chars[i])
dig1 = value / 16
dig2 = value % 16
result += chr(dig1 + base)
result += chr(dig2 + base)
return result | [
"def",
"HexToMPDecimal",
"(",
"hex_chars",
")",
":",
"result",
"=",
"''",
"base",
"=",
"ord",
"(",
"'a'",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"hex_chars",
")",
")",
":",
"value",
"=",
"ord",
"(",
"hex_chars",
"[",
"i",
"]",
")",
"dig1",
"=",
"value",
"/",
"16",
"dig2",
"=",
"value",
"%",
"16",
"result",
"+=",
"chr",
"(",
"dig1",
"+",
"base",
")",
"result",
"+=",
"chr",
"(",
"dig2",
"+",
"base",
")",
"return",
"result"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/chrome/crx_id.py#L27-L39 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | cyber/tools/cyber_channel/cyber_channel.py | python | _channel_cmd_info | (argv) | Command-line parsing for 'cyber_channel info' command. | Command-line parsing for 'cyber_channel info' command. | [
"Command",
"-",
"line",
"parsing",
"for",
"cyber_channel",
"info",
"command",
"."
] | def _channel_cmd_info(argv):
"""
Command-line parsing for 'cyber_channel info' command.
"""
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(
usage="usage: cyber_channel info channelname ")
parser.add_option("-a", "--all",
dest="all_channels", default=False,
action="store_true",
help="display all channels info")
(options, args) = parser.parse_args(args)
if len(args) == 0 and not options.all_channels:
parser.error("channelname must be specified")
elif len(args) > 1:
parser.error("you may only specify one topic name")
elif len(args) == 1:
channel_info(args[0])
elif len(args) == 0 and options.all_channels:
channel_info("") | [
"def",
"_channel_cmd_info",
"(",
"argv",
")",
":",
"args",
"=",
"argv",
"[",
"2",
":",
"]",
"from",
"optparse",
"import",
"OptionParser",
"parser",
"=",
"OptionParser",
"(",
"usage",
"=",
"\"usage: cyber_channel info channelname \"",
")",
"parser",
".",
"add_option",
"(",
"\"-a\"",
",",
"\"--all\"",
",",
"dest",
"=",
"\"all_channels\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"display all channels info\"",
")",
"(",
"options",
",",
"args",
")",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"and",
"not",
"options",
".",
"all_channels",
":",
"parser",
".",
"error",
"(",
"\"channelname must be specified\"",
")",
"elif",
"len",
"(",
"args",
")",
">",
"1",
":",
"parser",
".",
"error",
"(",
"\"you may only specify one topic name\"",
")",
"elif",
"len",
"(",
"args",
")",
"==",
"1",
":",
"channel_info",
"(",
"args",
"[",
"0",
"]",
")",
"elif",
"len",
"(",
"args",
")",
"==",
"0",
"and",
"options",
".",
"all_channels",
":",
"channel_info",
"(",
"\"\"",
")"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/cyber/tools/cyber_channel/cyber_channel.py#L288-L309 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/parser/_parser.py | python | parser._ampm_valid | (self, hour, ampm, fuzzy) | return val_is_ampm | For fuzzy parsing, 'a' or 'am' (both valid English words)
may erroneously trigger the AM/PM flag. Deal with that
here. | For fuzzy parsing, 'a' or 'am' (both valid English words)
may erroneously trigger the AM/PM flag. Deal with that
here. | [
"For",
"fuzzy",
"parsing",
"a",
"or",
"am",
"(",
"both",
"valid",
"English",
"words",
")",
"may",
"erroneously",
"trigger",
"the",
"AM",
"/",
"PM",
"flag",
".",
"Deal",
"with",
"that",
"here",
"."
] | def _ampm_valid(self, hour, ampm, fuzzy):
"""
For fuzzy parsing, 'a' or 'am' (both valid English words)
may erroneously trigger the AM/PM flag. Deal with that
here.
"""
val_is_ampm = True
# If there's already an AM/PM flag, this one isn't one.
if fuzzy and ampm is not None:
val_is_ampm = False
# If AM/PM is found and hour is not, raise a ValueError
if hour is None:
if fuzzy:
val_is_ampm = False
else:
raise ValueError('No hour specified with AM or PM flag.')
elif not 0 <= hour <= 12:
# If AM/PM is found, it's a 12 hour clock, so raise
# an error for invalid range
if fuzzy:
val_is_ampm = False
else:
raise ValueError('Invalid hour specified for 12-hour clock.')
return val_is_ampm | [
"def",
"_ampm_valid",
"(",
"self",
",",
"hour",
",",
"ampm",
",",
"fuzzy",
")",
":",
"val_is_ampm",
"=",
"True",
"# If there's already an AM/PM flag, this one isn't one.",
"if",
"fuzzy",
"and",
"ampm",
"is",
"not",
"None",
":",
"val_is_ampm",
"=",
"False",
"# If AM/PM is found and hour is not, raise a ValueError",
"if",
"hour",
"is",
"None",
":",
"if",
"fuzzy",
":",
"val_is_ampm",
"=",
"False",
"else",
":",
"raise",
"ValueError",
"(",
"'No hour specified with AM or PM flag.'",
")",
"elif",
"not",
"0",
"<=",
"hour",
"<=",
"12",
":",
"# If AM/PM is found, it's a 12 hour clock, so raise",
"# an error for invalid range",
"if",
"fuzzy",
":",
"val_is_ampm",
"=",
"False",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid hour specified for 12-hour clock.'",
")",
"return",
"val_is_ampm"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/parser/_parser.py#L1070-L1096 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewTreeCtrl.SetItemData | (*args, **kwargs) | return _dataview.DataViewTreeCtrl_SetItemData(*args, **kwargs) | SetItemData(self, DataViewItem item, wxClientData data) | SetItemData(self, DataViewItem item, wxClientData data) | [
"SetItemData",
"(",
"self",
"DataViewItem",
"item",
"wxClientData",
"data",
")"
] | def SetItemData(*args, **kwargs):
"""SetItemData(self, DataViewItem item, wxClientData data)"""
return _dataview.DataViewTreeCtrl_SetItemData(*args, **kwargs) | [
"def",
"SetItemData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewTreeCtrl_SetItemData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L2556-L2558 | |
xhzdeng/crpn | a5aef0f80dbe486103123f740c634fb01e6cc9a1 | caffe-fast-rcnn/scripts/download_model_binary.py | python | reporthook | (count, block_size, total_size) | From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ | From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ | [
"From",
"http",
":",
"//",
"blog",
".",
"moleculea",
".",
"com",
"/",
"2012",
"/",
"10",
"/",
"04",
"/",
"urlretrieve",
"-",
"progres",
"-",
"indicator",
"/"
] | def reporthook(count, block_size, total_size):
"""
From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/
"""
global start_time
if count == 0:
start_time = time.time()
return
duration = (time.time() - start_time) or 0.01
progress_size = int(count * block_size)
speed = int(progress_size / (1024 * duration))
percent = int(count * block_size * 100 / total_size)
sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" %
(percent, progress_size / (1024 * 1024), speed, duration))
sys.stdout.flush() | [
"def",
"reporthook",
"(",
"count",
",",
"block_size",
",",
"total_size",
")",
":",
"global",
"start_time",
"if",
"count",
"==",
"0",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"return",
"duration",
"=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"or",
"0.01",
"progress_size",
"=",
"int",
"(",
"count",
"*",
"block_size",
")",
"speed",
"=",
"int",
"(",
"progress_size",
"/",
"(",
"1024",
"*",
"duration",
")",
")",
"percent",
"=",
"int",
"(",
"count",
"*",
"block_size",
"*",
"100",
"/",
"total_size",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"\\r...%d%%, %d MB, %d KB/s, %d seconds passed\"",
"%",
"(",
"percent",
",",
"progress_size",
"/",
"(",
"1024",
"*",
"1024",
")",
",",
"speed",
",",
"duration",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/scripts/download_model_binary.py#L14-L28 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/cygwinccompiler.py | python | CygwinCCompiler._compile | (self, obj, src, ext, cc_args, extra_postargs, pp_opts) | Compiles the source by spawning GCC and windres if needed. | Compiles the source by spawning GCC and windres if needed. | [
"Compiles",
"the",
"source",
"by",
"spawning",
"GCC",
"and",
"windres",
"if",
"needed",
"."
] | def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
"""Compiles the source by spawning GCC and windres if needed."""
if ext == '.rc' or ext == '.res':
# gcc needs '.res' and '.rc' compiled to object files !!!
try:
self.spawn(["windres", "-i", src, "-o", obj])
except DistutilsExecError as msg:
raise CompileError(msg)
else: # for other files use the C-compiler
try:
self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +
extra_postargs)
except DistutilsExecError as msg:
raise CompileError(msg) | [
"def",
"_compile",
"(",
"self",
",",
"obj",
",",
"src",
",",
"ext",
",",
"cc_args",
",",
"extra_postargs",
",",
"pp_opts",
")",
":",
"if",
"ext",
"==",
"'.rc'",
"or",
"ext",
"==",
"'.res'",
":",
"# gcc needs '.res' and '.rc' compiled to object files !!!",
"try",
":",
"self",
".",
"spawn",
"(",
"[",
"\"windres\"",
",",
"\"-i\"",
",",
"src",
",",
"\"-o\"",
",",
"obj",
"]",
")",
"except",
"DistutilsExecError",
"as",
"msg",
":",
"raise",
"CompileError",
"(",
"msg",
")",
"else",
":",
"# for other files use the C-compiler",
"try",
":",
"self",
".",
"spawn",
"(",
"self",
".",
"compiler_so",
"+",
"cc_args",
"+",
"[",
"src",
",",
"'-o'",
",",
"obj",
"]",
"+",
"extra_postargs",
")",
"except",
"DistutilsExecError",
"as",
"msg",
":",
"raise",
"CompileError",
"(",
"msg",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/cygwinccompiler.py#L157-L170 | ||
mickem/nscp | 79f89fdbb6da63f91bc9dedb7aea202fe938f237 | scripts/python/lib/google/protobuf/service.py | python | RpcController.NotifyOnCancel | (self, callback) | Sets a callback to invoke on cancel.
Asks that the given callback be called when the RPC is canceled. The
callback will always be called exactly once. If the RPC completes without
being canceled, the callback will be called after completion. If the RPC
has already been canceled when NotifyOnCancel() is called, the callback
will be called immediately.
NotifyOnCancel() must be called no more than once per request. | Sets a callback to invoke on cancel. | [
"Sets",
"a",
"callback",
"to",
"invoke",
"on",
"cancel",
"."
] | def NotifyOnCancel(self, callback):
"""Sets a callback to invoke on cancel.
Asks that the given callback be called when the RPC is canceled. The
callback will always be called exactly once. If the RPC completes without
being canceled, the callback will be called after completion. If the RPC
has already been canceled when NotifyOnCancel() is called, the callback
will be called immediately.
NotifyOnCancel() must be called no more than once per request.
"""
raise NotImplementedError | [
"def",
"NotifyOnCancel",
"(",
"self",
",",
"callback",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/service.py#L187-L198 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/neighbors/_base.py | python | SupervisedFloatMixin.fit | (self, X, y) | return self._fit(X) | Fit the model using X as training data and y as target values
Parameters
----------
X : {array-like, sparse matrix, BallTree, KDTree}
Training data. If array or matrix, shape [n_samples, n_features],
or [n_samples, n_samples] if metric='precomputed'.
y : {array-like, sparse matrix}
Target values, array of float values, shape = [n_samples]
or [n_samples, n_outputs] | Fit the model using X as training data and y as target values | [
"Fit",
"the",
"model",
"using",
"X",
"as",
"training",
"data",
"and",
"y",
"as",
"target",
"values"
] | def fit(self, X, y):
"""Fit the model using X as training data and y as target values
Parameters
----------
X : {array-like, sparse matrix, BallTree, KDTree}
Training data. If array or matrix, shape [n_samples, n_features],
or [n_samples, n_samples] if metric='precomputed'.
y : {array-like, sparse matrix}
Target values, array of float values, shape = [n_samples]
or [n_samples, n_outputs]
"""
if not isinstance(X, (KDTree, BallTree)):
X, y = check_X_y(X, y, "csr", multi_output=True)
self._y = y
return self._fit(X) | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"if",
"not",
"isinstance",
"(",
"X",
",",
"(",
"KDTree",
",",
"BallTree",
")",
")",
":",
"X",
",",
"y",
"=",
"check_X_y",
"(",
"X",
",",
"y",
",",
"\"csr\"",
",",
"multi_output",
"=",
"True",
")",
"self",
".",
"_y",
"=",
"y",
"return",
"self",
".",
"_fit",
"(",
"X",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/neighbors/_base.py#L1092-L1108 | |
Ewenwan/MVision | 97b394dfa48cb21c82cd003b1a952745e413a17f | darknect/tensorflow/yolo_v2/utils.py | python | bboxes_nms | (classes, scores, bboxes, nms_threshold=0.5) | return classes[idxes], scores[idxes], bboxes[idxes] | Apply non-maximum selection to bounding boxes. | Apply non-maximum selection to bounding boxes. | [
"Apply",
"non",
"-",
"maximum",
"selection",
"to",
"bounding",
"boxes",
"."
] | def bboxes_nms(classes, scores, bboxes, nms_threshold=0.5):
"""Apply non-maximum selection to bounding boxes.
"""
keep_bboxes = np.ones(scores.shape, dtype=np.bool)# 边框是否保留的标志
for i in range(scores.size-1):
if keep_bboxes[i]:#剩余的边框
# Computer overlap with bboxes which are following.
overlap = bboxes_iou(bboxes[i], bboxes[(i+1):])#计算交并比
# Overlap threshold for keeping + checking part of the same class
keep_overlap = np.logical_or(overlap < nms_threshold, classes[(i+1):] != classes[i])
keep_bboxes[(i+1):] = np.logical_and(keep_bboxes[(i+1):], keep_overlap)
idxes = np.where(keep_bboxes)
return classes[idxes], scores[idxes], bboxes[idxes] | [
"def",
"bboxes_nms",
"(",
"classes",
",",
"scores",
",",
"bboxes",
",",
"nms_threshold",
"=",
"0.5",
")",
":",
"keep_bboxes",
"=",
"np",
".",
"ones",
"(",
"scores",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"# 边框是否保留的标志",
"for",
"i",
"in",
"range",
"(",
"scores",
".",
"size",
"-",
"1",
")",
":",
"if",
"keep_bboxes",
"[",
"i",
"]",
":",
"#剩余的边框",
"# Computer overlap with bboxes which are following.",
"overlap",
"=",
"bboxes_iou",
"(",
"bboxes",
"[",
"i",
"]",
",",
"bboxes",
"[",
"(",
"i",
"+",
"1",
")",
":",
"]",
")",
"#计算交并比",
"# Overlap threshold for keeping + checking part of the same class",
"keep_overlap",
"=",
"np",
".",
"logical_or",
"(",
"overlap",
"<",
"nms_threshold",
",",
"classes",
"[",
"(",
"i",
"+",
"1",
")",
":",
"]",
"!=",
"classes",
"[",
"i",
"]",
")",
"keep_bboxes",
"[",
"(",
"i",
"+",
"1",
")",
":",
"]",
"=",
"np",
".",
"logical_and",
"(",
"keep_bboxes",
"[",
"(",
"i",
"+",
"1",
")",
":",
"]",
",",
"keep_overlap",
")",
"idxes",
"=",
"np",
".",
"where",
"(",
"keep_bboxes",
")",
"return",
"classes",
"[",
"idxes",
"]",
",",
"scores",
"[",
"idxes",
"]",
",",
"bboxes",
"[",
"idxes",
"]"
] | https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/darknect/tensorflow/yolo_v2/utils.py#L156-L169 | |
ablab/spades | 3a754192b88540524ce6fb69eef5ea9273a38465 | assembler/ext/src/python_libs/joblib3/hashing.py | python | NumpyHasher.save | (self, obj) | Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class. | Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class. | [
"Subclass",
"the",
"save",
"method",
"to",
"hash",
"ndarray",
"subclass",
"rather",
"than",
"pickling",
"them",
".",
"Off",
"course",
"this",
"is",
"a",
"total",
"abuse",
"of",
"the",
"Pickler",
"class",
"."
] | def save(self, obj):
""" Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class.
"""
if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
# Compute a hash of the object:
try:
# memoryview is not supported for some dtypes,
# e.g. datetime64, see
# https://github.com/numpy/numpy/issues/4983. The
# workaround is to view the array as bytes before
# taking the memoryview
obj_bytes_view = obj.view(self.np.uint8)
self._hash.update(self._getbuffer(obj_bytes_view))
# ValueError is raised by .view when the array is not contiguous
# BufferError is raised by Python 3 in the hash update if
# the array is Fortran rather than C contiguous
except (ValueError, BufferError):
# Cater for non-single-segment arrays: this creates a
# copy, and thus aleviates this issue.
# XXX: There might be a more efficient way of doing this
obj_bytes_view = obj.flatten().view(self.np.uint8)
self._hash.update(self._getbuffer(obj_bytes_view))
# We store the class, to be able to distinguish between
# Objects with the same binary content, but different
# classes.
if self.coerce_mmap and isinstance(obj, self.np.memmap):
# We don't make the difference between memmap and
# normal ndarrays, to be able to reload previously
# computed results with memmap.
klass = self.np.ndarray
else:
klass = obj.__class__
# We also return the dtype and the shape, to distinguish
# different views on the same data with different dtypes.
# The object will be pickled by the pickler hashed at the end.
obj = (klass, ('HASHED', obj.dtype, obj.shape, obj.strides))
elif isinstance(obj, self.np.dtype):
# Atomic dtype objects are interned by their default constructor:
# np.dtype('f8') is np.dtype('f8')
# This interning is not maintained by a
# pickle.loads + pickle.dumps cycle, because __reduce__
# uses copy=True in the dtype constructor. This
# non-deterministic behavior causes the internal memoizer
# of the hasher to generate different hash values
# depending on the history of the dtype object.
# To prevent the hash from being sensitive to this, we use
# .descr which is a full (and never interned) description of
# the array dtype according to the numpy doc.
klass = obj.__class__
obj = (klass, ('HASHED', obj.descr))
Hasher.save(self, obj) | [
"def",
"save",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"self",
".",
"np",
".",
"ndarray",
")",
"and",
"not",
"obj",
".",
"dtype",
".",
"hasobject",
":",
"# Compute a hash of the object:",
"try",
":",
"# memoryview is not supported for some dtypes,",
"# e.g. datetime64, see",
"# https://github.com/numpy/numpy/issues/4983. The",
"# workaround is to view the array as bytes before",
"# taking the memoryview",
"obj_bytes_view",
"=",
"obj",
".",
"view",
"(",
"self",
".",
"np",
".",
"uint8",
")",
"self",
".",
"_hash",
".",
"update",
"(",
"self",
".",
"_getbuffer",
"(",
"obj_bytes_view",
")",
")",
"# ValueError is raised by .view when the array is not contiguous",
"# BufferError is raised by Python 3 in the hash update if",
"# the array is Fortran rather than C contiguous",
"except",
"(",
"ValueError",
",",
"BufferError",
")",
":",
"# Cater for non-single-segment arrays: this creates a",
"# copy, and thus aleviates this issue.",
"# XXX: There might be a more efficient way of doing this",
"obj_bytes_view",
"=",
"obj",
".",
"flatten",
"(",
")",
".",
"view",
"(",
"self",
".",
"np",
".",
"uint8",
")",
"self",
".",
"_hash",
".",
"update",
"(",
"self",
".",
"_getbuffer",
"(",
"obj_bytes_view",
")",
")",
"# We store the class, to be able to distinguish between",
"# Objects with the same binary content, but different",
"# classes.",
"if",
"self",
".",
"coerce_mmap",
"and",
"isinstance",
"(",
"obj",
",",
"self",
".",
"np",
".",
"memmap",
")",
":",
"# We don't make the difference between memmap and",
"# normal ndarrays, to be able to reload previously",
"# computed results with memmap.",
"klass",
"=",
"self",
".",
"np",
".",
"ndarray",
"else",
":",
"klass",
"=",
"obj",
".",
"__class__",
"# We also return the dtype and the shape, to distinguish",
"# different views on the same data with different dtypes.",
"# The object will be pickled by the pickler hashed at the end.",
"obj",
"=",
"(",
"klass",
",",
"(",
"'HASHED'",
",",
"obj",
".",
"dtype",
",",
"obj",
".",
"shape",
",",
"obj",
".",
"strides",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"self",
".",
"np",
".",
"dtype",
")",
":",
"# Atomic dtype objects are interned by their default constructor:",
"# np.dtype('f8') is np.dtype('f8')",
"# This interning is not maintained by a",
"# pickle.loads + pickle.dumps cycle, because __reduce__",
"# uses copy=True in the dtype constructor. This",
"# non-deterministic behavior causes the internal memoizer",
"# of the hasher to generate different hash values",
"# depending on the history of the dtype object.",
"# To prevent the hash from being sensitive to this, we use",
"# .descr which is a full (and never interned) description of",
"# the array dtype according to the numpy doc.",
"klass",
"=",
"obj",
".",
"__class__",
"obj",
"=",
"(",
"klass",
",",
"(",
"'HASHED'",
",",
"obj",
".",
"descr",
")",
")",
"Hasher",
".",
"save",
"(",
"self",
",",
"obj",
")"
] | https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/assembler/ext/src/python_libs/joblib3/hashing.py#L165-L219 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/kmeans.py | python | KMeansClustering.predict | (self, x, batch_size=None) | return super(KMeansClustering, self).predict(
x=x, batch_size=batch_size)[KMeansClustering.CLUSTER_IDX] | Predict cluster id for each element in x.
Args:
x: 2-D matrix or iterator.
batch_size: size to use for batching up x for querying the model.
Returns:
Array with same number of rows as x, containing cluster ids. | Predict cluster id for each element in x. | [
"Predict",
"cluster",
"id",
"for",
"each",
"element",
"in",
"x",
"."
] | def predict(self, x, batch_size=None):
"""Predict cluster id for each element in x.
Args:
x: 2-D matrix or iterator.
batch_size: size to use for batching up x for querying the model.
Returns:
Array with same number of rows as x, containing cluster ids.
"""
return super(KMeansClustering, self).predict(
x=x, batch_size=batch_size)[KMeansClustering.CLUSTER_IDX] | [
"def",
"predict",
"(",
"self",
",",
"x",
",",
"batch_size",
"=",
"None",
")",
":",
"return",
"super",
"(",
"KMeansClustering",
",",
"self",
")",
".",
"predict",
"(",
"x",
"=",
"x",
",",
"batch_size",
"=",
"batch_size",
")",
"[",
"KMeansClustering",
".",
"CLUSTER_IDX",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/kmeans.py#L170-L181 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/kfac/examples/convnet.py | python | _is_gradient_task | (task_id, num_tasks) | return 0 <= task_id < 0.6 * num_tasks | Returns True if this task should update the weights. | Returns True if this task should update the weights. | [
"Returns",
"True",
"if",
"this",
"task",
"should",
"update",
"the",
"weights",
"."
] | def _is_gradient_task(task_id, num_tasks):
"""Returns True if this task should update the weights."""
if num_tasks < 3:
return True
return 0 <= task_id < 0.6 * num_tasks | [
"def",
"_is_gradient_task",
"(",
"task_id",
",",
"num_tasks",
")",
":",
"if",
"num_tasks",
"<",
"3",
":",
"return",
"True",
"return",
"0",
"<=",
"task_id",
"<",
"0.6",
"*",
"num_tasks"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/kfac/examples/convnet.py#L226-L230 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | xpcom/typelib/xpt/tools/xpt.py | python | Constant.write_name | (self, file, data_pool_offset) | Write this constants's name to |file|.
Assumes that |file| is currently seeked to an unused portion
of the data pool. | Write this constants's name to |file|.
Assumes that |file| is currently seeked to an unused portion
of the data pool. | [
"Write",
"this",
"constants",
"s",
"name",
"to",
"|file|",
".",
"Assumes",
"that",
"|file|",
"is",
"currently",
"seeked",
"to",
"an",
"unused",
"portion",
"of",
"the",
"data",
"pool",
"."
] | def write_name(self, file, data_pool_offset):
"""
Write this constants's name to |file|.
Assumes that |file| is currently seeked to an unused portion
of the data pool.
"""
if self.name:
self._name_offset = file.tell() - data_pool_offset + 1
file.write(self.name + "\x00")
else:
self._name_offset = 0 | [
"def",
"write_name",
"(",
"self",
",",
"file",
",",
"data_pool_offset",
")",
":",
"if",
"self",
".",
"name",
":",
"self",
".",
"_name_offset",
"=",
"file",
".",
"tell",
"(",
")",
"-",
"data_pool_offset",
"+",
"1",
"file",
".",
"write",
"(",
"self",
".",
"name",
"+",
"\"\\x00\"",
")",
"else",
":",
"self",
".",
"_name_offset",
"=",
"0"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/xpcom/typelib/xpt/tools/xpt.py#L821-L832 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py | python | add_move | (move) | Add an item to six.moves. | Add an item to six.moves. | [
"Add",
"an",
"item",
"to",
"six",
".",
"moves",
"."
] | def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move) | [
"def",
"add_move",
"(",
"move",
")",
":",
"setattr",
"(",
"_MovedItems",
",",
"move",
".",
"name",
",",
"move",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py#L189-L191 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | VersionInfo.GetCopyright | (*args, **kwargs) | return _core_.VersionInfo_GetCopyright(*args, **kwargs) | GetCopyright(self) -> String | GetCopyright(self) -> String | [
"GetCopyright",
"(",
"self",
")",
"-",
">",
"String"
] | def GetCopyright(*args, **kwargs):
"""GetCopyright(self) -> String"""
return _core_.VersionInfo_GetCopyright(*args, **kwargs) | [
"def",
"GetCopyright",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"VersionInfo_GetCopyright",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L16597-L16599 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlDoc.validNormalizeAttributeValue | (self, elem, name, value) | return ret | Does the validation related extra step of the normalization
of attribute values: If the declared value is not CDATA,
then the XML processor must further process the normalized
attribute value by discarding any leading and trailing
space (#x20) characters, and by replacing sequences of
space (#x20) characters by single space (#x20) character. | Does the validation related extra step of the normalization
of attribute values: If the declared value is not CDATA,
then the XML processor must further process the normalized
attribute value by discarding any leading and trailing
space (#x20) characters, and by replacing sequences of
space (#x20) characters by single space (#x20) character. | [
"Does",
"the",
"validation",
"related",
"extra",
"step",
"of",
"the",
"normalization",
"of",
"attribute",
"values",
":",
"If",
"the",
"declared",
"value",
"is",
"not",
"CDATA",
"then",
"the",
"XML",
"processor",
"must",
"further",
"process",
"the",
"normalized",
"attribute",
"value",
"by",
"discarding",
"any",
"leading",
"and",
"trailing",
"space",
"(",
"#x20",
")",
"characters",
"and",
"by",
"replacing",
"sequences",
"of",
"space",
"(",
"#x20",
")",
"characters",
"by",
"single",
"space",
"(",
"#x20",
")",
"character",
"."
] | def validNormalizeAttributeValue(self, elem, name, value):
"""Does the validation related extra step of the normalization
of attribute values: If the declared value is not CDATA,
then the XML processor must further process the normalized
attribute value by discarding any leading and trailing
space (#x20) characters, and by replacing sequences of
space (#x20) characters by single space (#x20) character. """
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlValidNormalizeAttributeValue(self._o, elem__o, name, value)
return ret | [
"def",
"validNormalizeAttributeValue",
"(",
"self",
",",
"elem",
",",
"name",
",",
"value",
")",
":",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"else",
":",
"elem__o",
"=",
"elem",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidNormalizeAttributeValue",
"(",
"self",
".",
"_o",
",",
"elem__o",
",",
"name",
",",
"value",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4605-L4615 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/wsgiref/util.py | python | request_uri | (environ, include_query=1) | return url | Return the full request URI, optionally including the query string | Return the full request URI, optionally including the query string | [
"Return",
"the",
"full",
"request",
"URI",
"optionally",
"including",
"the",
"query",
"string"
] | def request_uri(environ, include_query=1):
"""Return the full request URI, optionally including the query string"""
url = application_uri(environ)
from urllib import quote
path_info = quote(environ.get('PATH_INFO',''),safe='/;=,')
if not environ.get('SCRIPT_NAME'):
url += path_info[1:]
else:
url += path_info
if include_query and environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
return url | [
"def",
"request_uri",
"(",
"environ",
",",
"include_query",
"=",
"1",
")",
":",
"url",
"=",
"application_uri",
"(",
"environ",
")",
"from",
"urllib",
"import",
"quote",
"path_info",
"=",
"quote",
"(",
"environ",
".",
"get",
"(",
"'PATH_INFO'",
",",
"''",
")",
",",
"safe",
"=",
"'/;=,'",
")",
"if",
"not",
"environ",
".",
"get",
"(",
"'SCRIPT_NAME'",
")",
":",
"url",
"+=",
"path_info",
"[",
"1",
":",
"]",
"else",
":",
"url",
"+=",
"path_info",
"if",
"include_query",
"and",
"environ",
".",
"get",
"(",
"'QUERY_STRING'",
")",
":",
"url",
"+=",
"'?'",
"+",
"environ",
"[",
"'QUERY_STRING'",
"]",
"return",
"url"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/wsgiref/util.py#L63-L74 | |
Tencent/PhoenixGo | fbf67f9aec42531bff9569c44b85eb4c3f37b7be | configure.py | python | create_android_ndk_rule | (environ_cp) | Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule. | Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule. | [
"Set",
"ANDROID_NDK_HOME",
"and",
"write",
"Android",
"NDK",
"WORKSPACE",
"rule",
"."
] | def create_android_ndk_rule(environ_cp):
"""Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
if is_windows() or is_cygwin():
default_ndk_path = cygpath(
'%s/Android/Sdk/ndk-bundle' % environ_cp['APPDATA'])
elif is_macos():
default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
else:
default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
def valid_ndk_path(path):
return (os.path.exists(path) and
os.path.exists(os.path.join(path, 'source.properties')))
android_ndk_home_path = prompt_loop_or_load_from_env(
environ_cp,
var_name='ANDROID_NDK_HOME',
var_default=default_ndk_path,
ask_for_var='Please specify the home path of the Android NDK to use.',
check_success=valid_ndk_path,
error_msg=('The path %s or its child file "source.properties" '
'does not exist.'))
write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
write_action_env_to_bazelrc('ANDROID_NDK_API_LEVEL',
check_ndk_level(android_ndk_home_path)) | [
"def",
"create_android_ndk_rule",
"(",
"environ_cp",
")",
":",
"if",
"is_windows",
"(",
")",
"or",
"is_cygwin",
"(",
")",
":",
"default_ndk_path",
"=",
"cygpath",
"(",
"'%s/Android/Sdk/ndk-bundle'",
"%",
"environ_cp",
"[",
"'APPDATA'",
"]",
")",
"elif",
"is_macos",
"(",
")",
":",
"default_ndk_path",
"=",
"'%s/library/Android/Sdk/ndk-bundle'",
"%",
"environ_cp",
"[",
"'HOME'",
"]",
"else",
":",
"default_ndk_path",
"=",
"'%s/Android/Sdk/ndk-bundle'",
"%",
"environ_cp",
"[",
"'HOME'",
"]",
"def",
"valid_ndk_path",
"(",
"path",
")",
":",
"return",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'source.properties'",
")",
")",
")",
"android_ndk_home_path",
"=",
"prompt_loop_or_load_from_env",
"(",
"environ_cp",
",",
"var_name",
"=",
"'ANDROID_NDK_HOME'",
",",
"var_default",
"=",
"default_ndk_path",
",",
"ask_for_var",
"=",
"'Please specify the home path of the Android NDK to use.'",
",",
"check_success",
"=",
"valid_ndk_path",
",",
"error_msg",
"=",
"(",
"'The path %s or its child file \"source.properties\" '",
"'does not exist.'",
")",
")",
"write_action_env_to_bazelrc",
"(",
"'ANDROID_NDK_HOME'",
",",
"android_ndk_home_path",
")",
"write_action_env_to_bazelrc",
"(",
"'ANDROID_NDK_API_LEVEL'",
",",
"check_ndk_level",
"(",
"android_ndk_home_path",
")",
")"
] | https://github.com/Tencent/PhoenixGo/blob/fbf67f9aec42531bff9569c44b85eb4c3f37b7be/configure.py#L660-L684 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextCtrl.SelectWord | (*args, **kwargs) | return _richtext.RichTextCtrl_SelectWord(*args, **kwargs) | SelectWord(self, long position) -> bool
Select the word at the given character position | SelectWord(self, long position) -> bool | [
"SelectWord",
"(",
"self",
"long",
"position",
")",
"-",
">",
"bool"
] | def SelectWord(*args, **kwargs):
"""
SelectWord(self, long position) -> bool
Select the word at the given character position
"""
return _richtext.RichTextCtrl_SelectWord(*args, **kwargs) | [
"def",
"SelectWord",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_SelectWord",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L3641-L3647 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/gdb/mongo_printers.py | python | WtSessionImplPrinter.__init__ | (self, val) | Initializer. | Initializer. | [
"Initializer",
"."
] | def __init__(self, val):
"""Initializer."""
self.val = val | [
"def",
"__init__",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"val",
"=",
"val"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/gdb/mongo_printers.py#L398-L400 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/check_ops.py | python | assert_proper_iterable | (values) | Static assert that values is a "proper" iterable.
`Ops` that expect iterables of `Tensor` can call this to validate input.
Useful since `Tensor`, `ndarray`, byte/text type are all iterables themselves.
Args:
values: Object to be checked.
Raises:
TypeError: If `values` is not iterable or is one of
`Tensor`, `SparseTensor`, `np.array`, `tf.compat.bytes_or_text_types`. | Static assert that values is a "proper" iterable. | [
"Static",
"assert",
"that",
"values",
"is",
"a",
"proper",
"iterable",
"."
] | def assert_proper_iterable(values):
"""Static assert that values is a "proper" iterable.
`Ops` that expect iterables of `Tensor` can call this to validate input.
Useful since `Tensor`, `ndarray`, byte/text type are all iterables themselves.
Args:
values: Object to be checked.
Raises:
TypeError: If `values` is not iterable or is one of
`Tensor`, `SparseTensor`, `np.array`, `tf.compat.bytes_or_text_types`.
"""
unintentional_iterables = (
(ops.Tensor, sparse_tensor.SparseTensor, np.ndarray)
+ compat.bytes_or_text_types
)
if isinstance(values, unintentional_iterables):
raise TypeError(
'Expected argument "values" to be a "proper" iterable. Found: %s' %
type(values))
if not hasattr(values, '__iter__'):
raise TypeError(
'Expected argument "values" to be iterable. Found: %s' % type(values)) | [
"def",
"assert_proper_iterable",
"(",
"values",
")",
":",
"unintentional_iterables",
"=",
"(",
"(",
"ops",
".",
"Tensor",
",",
"sparse_tensor",
".",
"SparseTensor",
",",
"np",
".",
"ndarray",
")",
"+",
"compat",
".",
"bytes_or_text_types",
")",
"if",
"isinstance",
"(",
"values",
",",
"unintentional_iterables",
")",
":",
"raise",
"TypeError",
"(",
"'Expected argument \"values\" to be a \"proper\" iterable. Found: %s'",
"%",
"type",
"(",
"values",
")",
")",
"if",
"not",
"hasattr",
"(",
"values",
",",
"'__iter__'",
")",
":",
"raise",
"TypeError",
"(",
"'Expected argument \"values\" to be iterable. Found: %s'",
"%",
"type",
"(",
"values",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/check_ops.py#L435-L459 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/auto_bisect/math_utils.py | python | PooledStandardError | (work_sets) | return math.sqrt(numerator / denominator1) * math.sqrt(denominator2) | Calculates the pooled sample standard error for a set of samples.
Args:
work_sets: A collection of collections of numbers.
Returns:
Pooled sample standard error. | Calculates the pooled sample standard error for a set of samples. | [
"Calculates",
"the",
"pooled",
"sample",
"standard",
"error",
"for",
"a",
"set",
"of",
"samples",
"."
] | def PooledStandardError(work_sets):
"""Calculates the pooled sample standard error for a set of samples.
Args:
work_sets: A collection of collections of numbers.
Returns:
Pooled sample standard error.
"""
numerator = 0.0
denominator1 = 0.0
denominator2 = 0.0
for current_set in work_sets:
std_dev = StandardDeviation(current_set)
numerator += (len(current_set) - 1) * std_dev ** 2
denominator1 += len(current_set) - 1
if len(current_set) > 0:
denominator2 += 1.0 / len(current_set)
if denominator1 == 0:
return 0.0
return math.sqrt(numerator / denominator1) * math.sqrt(denominator2) | [
"def",
"PooledStandardError",
"(",
"work_sets",
")",
":",
"numerator",
"=",
"0.0",
"denominator1",
"=",
"0.0",
"denominator2",
"=",
"0.0",
"for",
"current_set",
"in",
"work_sets",
":",
"std_dev",
"=",
"StandardDeviation",
"(",
"current_set",
")",
"numerator",
"+=",
"(",
"len",
"(",
"current_set",
")",
"-",
"1",
")",
"*",
"std_dev",
"**",
"2",
"denominator1",
"+=",
"len",
"(",
"current_set",
")",
"-",
"1",
"if",
"len",
"(",
"current_set",
")",
">",
"0",
":",
"denominator2",
"+=",
"1.0",
"/",
"len",
"(",
"current_set",
")",
"if",
"denominator1",
"==",
"0",
":",
"return",
"0.0",
"return",
"math",
".",
"sqrt",
"(",
"numerator",
"/",
"denominator1",
")",
"*",
"math",
".",
"sqrt",
"(",
"denominator2",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/math_utils.py#L103-L126 | |
deepmind/streetlearn | ccf1d60b9c45154894d45a897748aee85d7eb69b | streetlearn/python/environment/instructions_base.py | python | InstructionsBase.done | (self) | Returns a flag indicating the end of the current episode.
This game ends only at the end of the episode or if the goal is reached. | Returns a flag indicating the end of the current episode. | [
"Returns",
"a",
"flag",
"indicating",
"the",
"end",
"of",
"the",
"current",
"episode",
"."
] | def done(self):
"""Returns a flag indicating the end of the current episode.
This game ends only at the end of the episode or if the goal is reached.
"""
if self._reached_goal:
self._reached_goal = False
return True
else:
return False | [
"def",
"done",
"(",
"self",
")",
":",
"if",
"self",
".",
"_reached_goal",
":",
"self",
".",
"_reached_goal",
"=",
"False",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/deepmind/streetlearn/blob/ccf1d60b9c45154894d45a897748aee85d7eb69b/streetlearn/python/environment/instructions_base.py#L448-L457 | ||
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/ki/xMarkerBrainUser.py | python | UCMarkerGame.AddMarker | (self, age, pos, desc) | return idx | Adds a new marker to this game | Adds a new marker to this game | [
"Adds",
"a",
"new",
"marker",
"to",
"this",
"game"
] | def AddMarker(self, age, pos, desc):
""""Adds a new marker to this game"""
idx = self._nextMarkerID
self._nextMarkerID += 1
self._markers.append((idx, age, pos, desc))
if self._showingMarkers and age.lower() == PtGetAgeName().lower():
ptMarkerMgr().addMarker(pos, idx, True)
return idx | [
"def",
"AddMarker",
"(",
"self",
",",
"age",
",",
"pos",
",",
"desc",
")",
":",
"idx",
"=",
"self",
".",
"_nextMarkerID",
"self",
".",
"_nextMarkerID",
"+=",
"1",
"self",
".",
"_markers",
".",
"append",
"(",
"(",
"idx",
",",
"age",
",",
"pos",
",",
"desc",
")",
")",
"if",
"self",
".",
"_showingMarkers",
"and",
"age",
".",
"lower",
"(",
")",
"==",
"PtGetAgeName",
"(",
")",
".",
"lower",
"(",
")",
":",
"ptMarkerMgr",
"(",
")",
".",
"addMarker",
"(",
"pos",
",",
"idx",
",",
"True",
")",
"return",
"idx"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/ki/xMarkerBrainUser.py#L64-L72 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/_channel.py | python | _MultiThreadedRendezvous.exception | (self, timeout=None) | Return the exception raised by the computation.
See grpc.Future.exception for the full API contract. | Return the exception raised by the computation. | [
"Return",
"the",
"exception",
"raised",
"by",
"the",
"computation",
"."
] | def exception(self, timeout=None):
"""Return the exception raised by the computation.
See grpc.Future.exception for the full API contract.
"""
with self._state.condition:
timed_out = _common.wait(self._state.condition.wait,
self._is_complete,
timeout=timeout)
if timed_out:
raise grpc.FutureTimeoutError()
else:
if self._state.code is grpc.StatusCode.OK:
return None
elif self._state.cancelled:
raise grpc.FutureCancelledError()
else:
return self | [
"def",
"exception",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"self",
".",
"_state",
".",
"condition",
":",
"timed_out",
"=",
"_common",
".",
"wait",
"(",
"self",
".",
"_state",
".",
"condition",
".",
"wait",
",",
"self",
".",
"_is_complete",
",",
"timeout",
"=",
"timeout",
")",
"if",
"timed_out",
":",
"raise",
"grpc",
".",
"FutureTimeoutError",
"(",
")",
"else",
":",
"if",
"self",
".",
"_state",
".",
"code",
"is",
"grpc",
".",
"StatusCode",
".",
"OK",
":",
"return",
"None",
"elif",
"self",
".",
"_state",
".",
"cancelled",
":",
"raise",
"grpc",
".",
"FutureCancelledError",
"(",
")",
"else",
":",
"return",
"self"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/_channel.py#L746-L763 | ||
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/mac/Build/cpplint.py | python | IsBlankLine | (line) | return not line or line.isspace() | Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank. | Returns true if the given line is blank. | [
"Returns",
"true",
"if",
"the",
"given",
"line",
"is",
"blank",
"."
] | def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() | [
"def",
"IsBlankLine",
"(",
"line",
")",
":",
"return",
"not",
"line",
"or",
"line",
".",
"isspace",
"(",
")"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/mac/Build/cpplint.py#L1324-L1336 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/common.py | python | BuildFileTargets | (target_list, build_file) | return [p for p in target_list if BuildFile(p) == build_file] | From a target_list, returns the subset from the specified build_file. | From a target_list, returns the subset from the specified build_file. | [
"From",
"a",
"target_list",
"returns",
"the",
"subset",
"from",
"the",
"specified",
"build_file",
"."
] | def BuildFileTargets(target_list, build_file):
"""From a target_list, returns the subset from the specified build_file.
"""
return [p for p in target_list if BuildFile(p) == build_file] | [
"def",
"BuildFileTargets",
"(",
"target_list",
",",
"build_file",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"target_list",
"if",
"BuildFile",
"(",
"p",
")",
"==",
"build_file",
"]"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/common.py#L315-L318 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/toolchain/ios/compile_xcassets.py | python | CompileAssetCatalog | (output, platform, product_type, min_deployment_target,
inputs, compress_pngs, partial_info_plist) | Compile the .xcassets bundles to an asset catalog using actool.
Args:
output: absolute path to the containing bundle
platform: the targeted platform
product_type: the bundle type
min_deployment_target: minimum deployment target
inputs: list of absolute paths to .xcassets bundles
compress_pngs: whether to enable compression of pngs
partial_info_plist: path to partial Info.plist to generate | Compile the .xcassets bundles to an asset catalog using actool. | [
"Compile",
"the",
".",
"xcassets",
"bundles",
"to",
"an",
"asset",
"catalog",
"using",
"actool",
"."
] | def CompileAssetCatalog(output, platform, product_type, min_deployment_target,
inputs, compress_pngs, partial_info_plist):
"""Compile the .xcassets bundles to an asset catalog using actool.
Args:
output: absolute path to the containing bundle
platform: the targeted platform
product_type: the bundle type
min_deployment_target: minimum deployment target
inputs: list of absolute paths to .xcassets bundles
compress_pngs: whether to enable compression of pngs
partial_info_plist: path to partial Info.plist to generate
"""
command = [
'xcrun',
'actool',
'--output-format=human-readable-text',
'--notices',
'--warnings',
'--errors',
'--platform',
platform,
'--minimum-deployment-target',
min_deployment_target,
]
if compress_pngs:
command.extend(['--compress-pngs'])
if product_type != '':
command.extend(['--product-type', product_type])
if platform == 'macosx':
command.extend(['--target-device', 'mac'])
else:
command.extend(['--target-device', 'iphone', '--target-device', 'ipad'])
# Scan the input directories for the presence of asset catalog types that
# require special treatment, and if so, add them to the actool command-line.
for relative_path in inputs:
if not os.path.isdir(relative_path):
continue
for file_or_dir_name in os.listdir(relative_path):
if not os.path.isdir(os.path.join(relative_path, file_or_dir_name)):
continue
asset_name, asset_type = os.path.splitext(file_or_dir_name)
if asset_type not in ACTOOL_FLAG_FOR_ASSET_TYPE:
continue
command.extend([ACTOOL_FLAG_FOR_ASSET_TYPE[asset_type], asset_name])
# Always ask actool to generate a partial Info.plist file. If no path
# has been given by the caller, use a temporary file name.
temporary_file = None
if not partial_info_plist:
temporary_file = tempfile.NamedTemporaryFile(suffix='.plist')
partial_info_plist = temporary_file.name
command.extend(['--output-partial-info-plist', partial_info_plist])
# Dictionary used to convert absolute paths back to their relative form
# in the output of actool.
relative_paths = {}
# actool crashes if paths are relative, so convert input and output paths
# to absolute paths, and record the relative paths to fix them back when
# filtering the output.
absolute_output = os.path.abspath(output)
relative_paths[output] = absolute_output
relative_paths[os.path.dirname(output)] = os.path.dirname(absolute_output)
command.extend(['--compile', os.path.dirname(os.path.abspath(output))])
for relative_path in inputs:
absolute_path = os.path.abspath(relative_path)
relative_paths[absolute_path] = relative_path
command.append(absolute_path)
try:
# Run actool and redirect stdout and stderr to the same pipe (as actool
# is confused about what should go to stderr/stdout).
process = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout = process.communicate()[0].decode('utf-8')
# If the invocation of `actool` failed, copy all the compiler output to
# the standard error stream and exit. See https://crbug.com/1205775 for
# example of compilation that failed with no error message due to filter.
if process.returncode:
for line in stdout.splitlines():
fixed_line = FixAbsolutePathInLine(line, relative_paths)
sys.stderr.write(fixed_line + '\n')
sys.exit(1)
# Filter the output to remove all garbage and to fix the paths. If the
# output is not empty after filtering, then report the compilation as a
# failure (as some version of `actool` report error to stdout, yet exit
# with an return code of zero).
stdout = FilterCompilerOutput(stdout, relative_paths)
if stdout:
sys.stderr.write(stdout)
sys.exit(1)
finally:
if temporary_file:
temporary_file.close() | [
"def",
"CompileAssetCatalog",
"(",
"output",
",",
"platform",
",",
"product_type",
",",
"min_deployment_target",
",",
"inputs",
",",
"compress_pngs",
",",
"partial_info_plist",
")",
":",
"command",
"=",
"[",
"'xcrun'",
",",
"'actool'",
",",
"'--output-format=human-readable-text'",
",",
"'--notices'",
",",
"'--warnings'",
",",
"'--errors'",
",",
"'--platform'",
",",
"platform",
",",
"'--minimum-deployment-target'",
",",
"min_deployment_target",
",",
"]",
"if",
"compress_pngs",
":",
"command",
".",
"extend",
"(",
"[",
"'--compress-pngs'",
"]",
")",
"if",
"product_type",
"!=",
"''",
":",
"command",
".",
"extend",
"(",
"[",
"'--product-type'",
",",
"product_type",
"]",
")",
"if",
"platform",
"==",
"'macosx'",
":",
"command",
".",
"extend",
"(",
"[",
"'--target-device'",
",",
"'mac'",
"]",
")",
"else",
":",
"command",
".",
"extend",
"(",
"[",
"'--target-device'",
",",
"'iphone'",
",",
"'--target-device'",
",",
"'ipad'",
"]",
")",
"# Scan the input directories for the presence of asset catalog types that",
"# require special treatment, and if so, add them to the actool command-line.",
"for",
"relative_path",
"in",
"inputs",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"relative_path",
")",
":",
"continue",
"for",
"file_or_dir_name",
"in",
"os",
".",
"listdir",
"(",
"relative_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"relative_path",
",",
"file_or_dir_name",
")",
")",
":",
"continue",
"asset_name",
",",
"asset_type",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_or_dir_name",
")",
"if",
"asset_type",
"not",
"in",
"ACTOOL_FLAG_FOR_ASSET_TYPE",
":",
"continue",
"command",
".",
"extend",
"(",
"[",
"ACTOOL_FLAG_FOR_ASSET_TYPE",
"[",
"asset_type",
"]",
",",
"asset_name",
"]",
")",
"# Always ask actool to generate a partial Info.plist file. If no path",
"# has been given by the caller, use a temporary file name.",
"temporary_file",
"=",
"None",
"if",
"not",
"partial_info_plist",
":",
"temporary_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.plist'",
")",
"partial_info_plist",
"=",
"temporary_file",
".",
"name",
"command",
".",
"extend",
"(",
"[",
"'--output-partial-info-plist'",
",",
"partial_info_plist",
"]",
")",
"# Dictionary used to convert absolute paths back to their relative form",
"# in the output of actool.",
"relative_paths",
"=",
"{",
"}",
"# actool crashes if paths are relative, so convert input and output paths",
"# to absolute paths, and record the relative paths to fix them back when",
"# filtering the output.",
"absolute_output",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"output",
")",
"relative_paths",
"[",
"output",
"]",
"=",
"absolute_output",
"relative_paths",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"output",
")",
"]",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"absolute_output",
")",
"command",
".",
"extend",
"(",
"[",
"'--compile'",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"output",
")",
")",
"]",
")",
"for",
"relative_path",
"in",
"inputs",
":",
"absolute_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"relative_path",
")",
"relative_paths",
"[",
"absolute_path",
"]",
"=",
"relative_path",
"command",
".",
"append",
"(",
"absolute_path",
")",
"try",
":",
"# Run actool and redirect stdout and stderr to the same pipe (as actool",
"# is confused about what should go to stderr/stdout).",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"stdout",
"=",
"process",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
"# If the invocation of `actool` failed, copy all the compiler output to",
"# the standard error stream and exit. See https://crbug.com/1205775 for",
"# example of compilation that failed with no error message due to filter.",
"if",
"process",
".",
"returncode",
":",
"for",
"line",
"in",
"stdout",
".",
"splitlines",
"(",
")",
":",
"fixed_line",
"=",
"FixAbsolutePathInLine",
"(",
"line",
",",
"relative_paths",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"fixed_line",
"+",
"'\\n'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# Filter the output to remove all garbage and to fix the paths. If the",
"# output is not empty after filtering, then report the compilation as a",
"# failure (as some version of `actool` report error to stdout, yet exit",
"# with an return code of zero).",
"stdout",
"=",
"FilterCompilerOutput",
"(",
"stdout",
",",
"relative_paths",
")",
"if",
"stdout",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"stdout",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"finally",
":",
"if",
"temporary_file",
":",
"temporary_file",
".",
"close",
"(",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/toolchain/ios/compile_xcassets.py#L97-L205 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | ContactParameters.__init__ | (self) | __init__(ContactParameters self) -> ContactParameters | __init__(ContactParameters self) -> ContactParameters | [
"__init__",
"(",
"ContactParameters",
"self",
")",
"-",
">",
"ContactParameters"
] | def __init__(self):
"""
__init__(ContactParameters self) -> ContactParameters
"""
this = _robotsim.new_ContactParameters()
try:
self.this.append(this)
except Exception:
self.this = this | [
"def",
"__init__",
"(",
"self",
")",
":",
"this",
"=",
"_robotsim",
".",
"new_ContactParameters",
"(",
")",
"try",
":",
"self",
".",
"this",
".",
"append",
"(",
"this",
")",
"except",
"Exception",
":",
"self",
".",
"this",
"=",
"this"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L3596-L3607 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py | python | NameValueListToDict | (name_value_list) | return result | Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary
of the pairs. If a string is simply NAME, then the value in the dictionary
is set to True. If VALUE can be converted to an integer, it is. | Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary
of the pairs. If a string is simply NAME, then the value in the dictionary
is set to True. If VALUE can be converted to an integer, it is. | [
"Takes",
"an",
"array",
"of",
"strings",
"of",
"the",
"form",
"NAME",
"=",
"VALUE",
"and",
"creates",
"a",
"dictionary",
"of",
"the",
"pairs",
".",
"If",
"a",
"string",
"is",
"simply",
"NAME",
"then",
"the",
"value",
"in",
"the",
"dictionary",
"is",
"set",
"to",
"True",
".",
"If",
"VALUE",
"can",
"be",
"converted",
"to",
"an",
"integer",
"it",
"is",
"."
] | def NameValueListToDict(name_value_list):
"""
Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary
of the pairs. If a string is simply NAME, then the value in the dictionary
is set to True. If VALUE can be converted to an integer, it is.
"""
result = { }
for item in name_value_list:
tokens = item.split('=', 1)
if len(tokens) == 2:
# If we can make it an int, use that, otherwise, use the string.
try:
token_value = int(tokens[1])
except ValueError:
token_value = tokens[1]
# Set the variable to the supplied value.
result[tokens[0]] = token_value
else:
# No value supplied, treat it as a boolean and set it.
result[tokens[0]] = True
return result | [
"def",
"NameValueListToDict",
"(",
"name_value_list",
")",
":",
"result",
"=",
"{",
"}",
"for",
"item",
"in",
"name_value_list",
":",
"tokens",
"=",
"item",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"len",
"(",
"tokens",
")",
"==",
"2",
":",
"# If we can make it an int, use that, otherwise, use the string.",
"try",
":",
"token_value",
"=",
"int",
"(",
"tokens",
"[",
"1",
"]",
")",
"except",
"ValueError",
":",
"token_value",
"=",
"tokens",
"[",
"1",
"]",
"# Set the variable to the supplied value.",
"result",
"[",
"tokens",
"[",
"0",
"]",
"]",
"=",
"token_value",
"else",
":",
"# No value supplied, treat it as a boolean and set it.",
"result",
"[",
"tokens",
"[",
"0",
"]",
"]",
"=",
"True",
"return",
"result"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py#L133-L153 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/menus.py | python | get_menu_item_tuple | (dad, name) | return (subdict["sk"], subdict["sd"], kb_shortcut, subdict["dn"], subdict["cb"]) | Returns the Tuple for a Menu Item | Returns the Tuple for a Menu Item | [
"Returns",
"the",
"Tuple",
"for",
"a",
"Menu",
"Item"
] | def get_menu_item_tuple(dad, name):
"""Returns the Tuple for a Menu Item"""
subdict = dad.menudict[name]
kb_shortcut = get_menu_item_kb_shortcut(dad, name)
return (subdict["sk"], subdict["sd"], kb_shortcut, subdict["dn"], subdict["cb"]) | [
"def",
"get_menu_item_tuple",
"(",
"dad",
",",
"name",
")",
":",
"subdict",
"=",
"dad",
".",
"menudict",
"[",
"name",
"]",
"kb_shortcut",
"=",
"get_menu_item_kb_shortcut",
"(",
"dad",
",",
"name",
")",
"return",
"(",
"subdict",
"[",
"\"sk\"",
"]",
",",
"subdict",
"[",
"\"sd\"",
"]",
",",
"kb_shortcut",
",",
"subdict",
"[",
"\"dn\"",
"]",
",",
"subdict",
"[",
"\"cb\"",
"]",
")"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/menus.py#L371-L375 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/driver.py | python | Function._read_func_attr | (self, attrid) | return retval.value | Read CUfunction attributes | Read CUfunction attributes | [
"Read",
"CUfunction",
"attributes"
] | def _read_func_attr(self, attrid):
"""
Read CUfunction attributes
"""
retval = c_int()
driver.cuFuncGetAttribute(byref(retval), attrid, self.handle)
return retval.value | [
"def",
"_read_func_attr",
"(",
"self",
",",
"attrid",
")",
":",
"retval",
"=",
"c_int",
"(",
")",
"driver",
".",
"cuFuncGetAttribute",
"(",
"byref",
"(",
"retval",
")",
",",
"attrid",
",",
"self",
".",
"handle",
")",
"return",
"retval",
".",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/driver.py#L1584-L1590 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_FirmwareRead_REQUEST.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(TPM2_FirmwareRead_REQUEST) | Returns new TPM2_FirmwareRead_REQUEST object constructed from its
marshaled representation in the given byte buffer | Returns new TPM2_FirmwareRead_REQUEST object constructed from its
marshaled representation in the given byte buffer | [
"Returns",
"new",
"TPM2_FirmwareRead_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new TPM2_FirmwareRead_REQUEST object constructed from its
marshaled representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(TPM2_FirmwareRead_REQUEST) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"TPM2_FirmwareRead_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16026-L16030 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/database.py | python | DistributionPath.clear_cache | (self) | Clears the internal cache. | Clears the internal cache. | [
"Clears",
"the",
"internal",
"cache",
"."
] | def clear_cache(self):
"""
Clears the internal cache.
"""
self._cache.clear()
self._cache_egg.clear() | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"self",
".",
"_cache",
".",
"clear",
"(",
")",
"self",
".",
"_cache_egg",
".",
"clear",
"(",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/database.py#L106-L111 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py | python | URLopener.retrieve | (self, url, filename=None, reporthook=None, data=None) | return result | retrieve(url) returns (filename, headers) for a local object
or (tempfilename, headers) for a remote object. | retrieve(url) returns (filename, headers) for a local object
or (tempfilename, headers) for a remote object. | [
"retrieve",
"(",
"url",
")",
"returns",
"(",
"filename",
"headers",
")",
"for",
"a",
"local",
"object",
"or",
"(",
"tempfilename",
"headers",
")",
"for",
"a",
"remote",
"object",
"."
] | def retrieve(self, url, filename=None, reporthook=None, data=None):
"""retrieve(url) returns (filename, headers) for a local object
or (tempfilename, headers) for a remote object."""
url = unwrap(toBytes(url))
if self.tempcache and url in self.tempcache:
return self.tempcache[url]
type, url1 = splittype(url)
if filename is None and (not type or type == 'file'):
try:
fp = self.open_local_file(url1)
hdrs = fp.info()
fp.close()
return url2pathname(splithost(url1)[1]), hdrs
except IOError:
pass
fp = self.open(url, data)
try:
headers = fp.info()
if filename:
tfp = open(filename, 'wb')
else:
import tempfile
garbage, path = splittype(url)
garbage, path = splithost(path or "")
path, garbage = splitquery(path or "")
path, garbage = splitattr(path or "")
suffix = os.path.splitext(path)[1]
(fd, filename) = tempfile.mkstemp(suffix)
self.__tempfiles.append(filename)
tfp = os.fdopen(fd, 'wb')
try:
result = filename, headers
if self.tempcache is not None:
self.tempcache[url] = result
bs = 1024*8
size = -1
read = 0
blocknum = 0
if "content-length" in headers:
size = int(headers["Content-Length"])
if reporthook:
reporthook(blocknum, bs, size)
while 1:
block = fp.read(bs)
if block == "":
break
read += len(block)
tfp.write(block)
blocknum += 1
if reporthook:
reporthook(blocknum, bs, size)
finally:
tfp.close()
finally:
fp.close()
# raise exception if actual size does not match content-length header
if size >= 0 and read < size:
raise ContentTooShortError("retrieval incomplete: got only %i out "
"of %i bytes" % (read, size), result)
return result | [
"def",
"retrieve",
"(",
"self",
",",
"url",
",",
"filename",
"=",
"None",
",",
"reporthook",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"url",
"=",
"unwrap",
"(",
"toBytes",
"(",
"url",
")",
")",
"if",
"self",
".",
"tempcache",
"and",
"url",
"in",
"self",
".",
"tempcache",
":",
"return",
"self",
".",
"tempcache",
"[",
"url",
"]",
"type",
",",
"url1",
"=",
"splittype",
"(",
"url",
")",
"if",
"filename",
"is",
"None",
"and",
"(",
"not",
"type",
"or",
"type",
"==",
"'file'",
")",
":",
"try",
":",
"fp",
"=",
"self",
".",
"open_local_file",
"(",
"url1",
")",
"hdrs",
"=",
"fp",
".",
"info",
"(",
")",
"fp",
".",
"close",
"(",
")",
"return",
"url2pathname",
"(",
"splithost",
"(",
"url1",
")",
"[",
"1",
"]",
")",
",",
"hdrs",
"except",
"IOError",
":",
"pass",
"fp",
"=",
"self",
".",
"open",
"(",
"url",
",",
"data",
")",
"try",
":",
"headers",
"=",
"fp",
".",
"info",
"(",
")",
"if",
"filename",
":",
"tfp",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"else",
":",
"import",
"tempfile",
"garbage",
",",
"path",
"=",
"splittype",
"(",
"url",
")",
"garbage",
",",
"path",
"=",
"splithost",
"(",
"path",
"or",
"\"\"",
")",
"path",
",",
"garbage",
"=",
"splitquery",
"(",
"path",
"or",
"\"\"",
")",
"path",
",",
"garbage",
"=",
"splitattr",
"(",
"path",
"or",
"\"\"",
")",
"suffix",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"(",
"fd",
",",
"filename",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
")",
"self",
".",
"__tempfiles",
".",
"append",
"(",
"filename",
")",
"tfp",
"=",
"os",
".",
"fdopen",
"(",
"fd",
",",
"'wb'",
")",
"try",
":",
"result",
"=",
"filename",
",",
"headers",
"if",
"self",
".",
"tempcache",
"is",
"not",
"None",
":",
"self",
".",
"tempcache",
"[",
"url",
"]",
"=",
"result",
"bs",
"=",
"1024",
"*",
"8",
"size",
"=",
"-",
"1",
"read",
"=",
"0",
"blocknum",
"=",
"0",
"if",
"\"content-length\"",
"in",
"headers",
":",
"size",
"=",
"int",
"(",
"headers",
"[",
"\"Content-Length\"",
"]",
")",
"if",
"reporthook",
":",
"reporthook",
"(",
"blocknum",
",",
"bs",
",",
"size",
")",
"while",
"1",
":",
"block",
"=",
"fp",
".",
"read",
"(",
"bs",
")",
"if",
"block",
"==",
"\"\"",
":",
"break",
"read",
"+=",
"len",
"(",
"block",
")",
"tfp",
".",
"write",
"(",
"block",
")",
"blocknum",
"+=",
"1",
"if",
"reporthook",
":",
"reporthook",
"(",
"blocknum",
",",
"bs",
",",
"size",
")",
"finally",
":",
"tfp",
".",
"close",
"(",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")",
"# raise exception if actual size does not match content-length header",
"if",
"size",
">=",
"0",
"and",
"read",
"<",
"size",
":",
"raise",
"ContentTooShortError",
"(",
"\"retrieval incomplete: got only %i out \"",
"\"of %i bytes\"",
"%",
"(",
"read",
",",
"size",
")",
",",
"result",
")",
"return",
"result"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py#L225-L286 | |
manutdzou/KITTI_SSD | 5b620c2f291d36a0fe14489214f22a992f173f44 | python/caffe/io.py | python | array_to_blobproto | (arr, diff=None) | return blob | Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check. | Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check. | [
"Converts",
"a",
"N",
"-",
"dimensional",
"array",
"to",
"blob",
"proto",
".",
"If",
"diff",
"is",
"given",
"also",
"convert",
"the",
"diff",
".",
"You",
"need",
"to",
"make",
"sure",
"that",
"arr",
"and",
"diff",
"have",
"the",
"same",
"shape",
"and",
"this",
"function",
"does",
"not",
"do",
"sanity",
"check",
"."
] | def array_to_blobproto(arr, diff=None):
"""Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check.
"""
blob = caffe_pb2.BlobProto()
blob.shape.dim.extend(arr.shape)
blob.data.extend(arr.astype(float).flat)
if diff is not None:
blob.diff.extend(diff.astype(float).flat)
return blob | [
"def",
"array_to_blobproto",
"(",
"arr",
",",
"diff",
"=",
"None",
")",
":",
"blob",
"=",
"caffe_pb2",
".",
"BlobProto",
"(",
")",
"blob",
".",
"shape",
".",
"dim",
".",
"extend",
"(",
"arr",
".",
"shape",
")",
"blob",
".",
"data",
".",
"extend",
"(",
"arr",
".",
"astype",
"(",
"float",
")",
".",
"flat",
")",
"if",
"diff",
"is",
"not",
"None",
":",
"blob",
".",
"diff",
".",
"extend",
"(",
"diff",
".",
"astype",
"(",
"float",
")",
".",
"flat",
")",
"return",
"blob"
] | https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/python/caffe/io.py#L36-L46 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/cpu/hswish_grad.py | python | _hswish_grad_cpu | () | return | HSwishGrad cpu register | HSwishGrad cpu register | [
"HSwishGrad",
"cpu",
"register"
] | def _hswish_grad_cpu():
"""HSwishGrad cpu register"""
return | [
"def",
"_hswish_grad_cpu",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/cpu/hswish_grad.py#L31-L33 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | Postprocessor.postrecursive | (self, container) | Postprocess the container contents recursively | Postprocess the container contents recursively | [
"Postprocess",
"the",
"container",
"contents",
"recursively"
] | def postrecursive(self, container):
"Postprocess the container contents recursively"
if not hasattr(container, 'contents'):
return
if len(container.contents) == 0:
return
if hasattr(container, 'postprocess'):
if not container.postprocess:
return
postprocessor = Postprocessor()
contents = []
for element in container.contents:
post = postprocessor.postprocess(element)
if post:
contents.append(post)
# two rounds to empty the pipeline
for i in range(2):
post = postprocessor.postprocess(None)
if post:
contents.append(post)
container.contents = contents | [
"def",
"postrecursive",
"(",
"self",
",",
"container",
")",
":",
"if",
"not",
"hasattr",
"(",
"container",
",",
"'contents'",
")",
":",
"return",
"if",
"len",
"(",
"container",
".",
"contents",
")",
"==",
"0",
":",
"return",
"if",
"hasattr",
"(",
"container",
",",
"'postprocess'",
")",
":",
"if",
"not",
"container",
".",
"postprocess",
":",
"return",
"postprocessor",
"=",
"Postprocessor",
"(",
")",
"contents",
"=",
"[",
"]",
"for",
"element",
"in",
"container",
".",
"contents",
":",
"post",
"=",
"postprocessor",
".",
"postprocess",
"(",
"element",
")",
"if",
"post",
":",
"contents",
".",
"append",
"(",
"post",
")",
"# two rounds to empty the pipeline",
"for",
"i",
"in",
"range",
"(",
"2",
")",
":",
"post",
"=",
"postprocessor",
".",
"postprocess",
"(",
"None",
")",
"if",
"post",
":",
"contents",
".",
"append",
"(",
"post",
")",
"container",
".",
"contents",
"=",
"contents"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L3879-L3899 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/akg/ascend/equal.py | python | _equal_akg | () | return | Equal Akg register | Equal Akg register | [
"Equal",
"Akg",
"register"
] | def _equal_akg():
"""Equal Akg register"""
return | [
"def",
"_equal_akg",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/akg/ascend/equal.py#L33-L35 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/xmlrpclib.py | python | gzip_encode | (data) | return encoded | data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952 | data -> gzip encoded data | [
"data",
"-",
">",
"gzip",
"encoded",
"data"
] | def gzip_encode(data):
"""data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO()
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
gzf.write(data)
gzf.close()
encoded = f.getvalue()
f.close()
return encoded | [
"def",
"gzip_encode",
"(",
"data",
")",
":",
"if",
"not",
"gzip",
":",
"raise",
"NotImplementedError",
"f",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"gzf",
"=",
"gzip",
".",
"GzipFile",
"(",
"mode",
"=",
"\"wb\"",
",",
"fileobj",
"=",
"f",
",",
"compresslevel",
"=",
"1",
")",
"gzf",
".",
"write",
"(",
"data",
")",
"gzf",
".",
"close",
"(",
")",
"encoded",
"=",
"f",
".",
"getvalue",
"(",
")",
"f",
".",
"close",
"(",
")",
"return",
"encoded"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/xmlrpclib.py#L1147-L1160 | |
Alexhuszagh/rust-lexical | 01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0 | lexical-parse-float/etc/powers_table.py | python | as_u64 | (value) | return result | Convert a big integer to an array of 64-bit values. | Convert a big integer to an array of 64-bit values. | [
"Convert",
"a",
"big",
"integer",
"to",
"an",
"array",
"of",
"64",
"-",
"bit",
"values",
"."
] | def as_u64(value):
'''Convert a big integer to an array of 64-bit values.'''
result = []
max_u64 = 2**64 - 1
while value:
result.append(value & max_u64)
value >>= 64
return result | [
"def",
"as_u64",
"(",
"value",
")",
":",
"result",
"=",
"[",
"]",
"max_u64",
"=",
"2",
"**",
"64",
"-",
"1",
"while",
"value",
":",
"result",
".",
"append",
"(",
"value",
"&",
"max_u64",
")",
"value",
">>=",
"64",
"return",
"result"
] | https://github.com/Alexhuszagh/rust-lexical/blob/01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0/lexical-parse-float/etc/powers_table.py#L55-L63 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/format.py | python | Datetime64TZFormatter._format_strings | (self) | return fmt_values | we by definition have a TZ | we by definition have a TZ | [
"we",
"by",
"definition",
"have",
"a",
"TZ"
] | def _format_strings(self) -> List[str]:
""" we by definition have a TZ """
values = self.values.astype(object)
is_dates_only = _is_dates_only(values)
formatter = self.formatter or _get_format_datetime64(
is_dates_only, date_format=self.date_format
)
fmt_values = [formatter(x) for x in values]
return fmt_values | [
"def",
"_format_strings",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"values",
"=",
"self",
".",
"values",
".",
"astype",
"(",
"object",
")",
"is_dates_only",
"=",
"_is_dates_only",
"(",
"values",
")",
"formatter",
"=",
"self",
".",
"formatter",
"or",
"_get_format_datetime64",
"(",
"is_dates_only",
",",
"date_format",
"=",
"self",
".",
"date_format",
")",
"fmt_values",
"=",
"[",
"formatter",
"(",
"x",
")",
"for",
"x",
"in",
"values",
"]",
"return",
"fmt_values"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/format.py#L1654-L1664 | |
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_handlers.py | python | IncomingMessageHandler.on_aborted | (self, event: Event) | Callback for when a message delivery is aborted by the remote peer.
:param event: The underlying event object. Use this to obtain further
information on the event. | Callback for when a message delivery is aborted by the remote peer. | [
"Callback",
"for",
"when",
"a",
"message",
"delivery",
"is",
"aborted",
"by",
"the",
"remote",
"peer",
"."
] | def on_aborted(self, event: Event):
"""
Callback for when a message delivery is aborted by the remote peer.
:param event: The underlying event object. Use this to obtain further
information on the event.
"""
if self.delegate is not None:
_dispatch(self.delegate, 'on_aborted', event) | [
"def",
"on_aborted",
"(",
"self",
",",
"event",
":",
"Event",
")",
":",
"if",
"self",
".",
"delegate",
"is",
"not",
"None",
":",
"_dispatch",
"(",
"self",
".",
"delegate",
",",
"'on_aborted'",
",",
"event",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_handlers.py#L291-L299 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/Draw/SimilarityMaps.py | python | GetSimilarityMapForFingerprint | (refMol, probeMol, fpFunction, metric=DataStructs.DiceSimilarity,
**kwargs) | return fig, maxWeight | Generates the similarity map for a given reference and probe molecule,
fingerprint function and similarity metric.
Parameters:
refMol -- the reference molecule
probeMol -- the probe molecule
fpFunction -- the fingerprint function
metric -- the similarity metric.
kwargs -- additional arguments for drawing | Generates the similarity map for a given reference and probe molecule,
fingerprint function and similarity metric. | [
"Generates",
"the",
"similarity",
"map",
"for",
"a",
"given",
"reference",
"and",
"probe",
"molecule",
"fingerprint",
"function",
"and",
"similarity",
"metric",
"."
] | def GetSimilarityMapForFingerprint(refMol, probeMol, fpFunction, metric=DataStructs.DiceSimilarity,
**kwargs):
"""
Generates the similarity map for a given reference and probe molecule,
fingerprint function and similarity metric.
Parameters:
refMol -- the reference molecule
probeMol -- the probe molecule
fpFunction -- the fingerprint function
metric -- the similarity metric.
kwargs -- additional arguments for drawing
"""
weights = GetAtomicWeightsForFingerprint(refMol, probeMol, fpFunction, metric)
weights, maxWeight = GetStandardizedWeights(weights)
fig = GetSimilarityMapFromWeights(probeMol, weights, **kwargs)
return fig, maxWeight | [
"def",
"GetSimilarityMapForFingerprint",
"(",
"refMol",
",",
"probeMol",
",",
"fpFunction",
",",
"metric",
"=",
"DataStructs",
".",
"DiceSimilarity",
",",
"*",
"*",
"kwargs",
")",
":",
"weights",
"=",
"GetAtomicWeightsForFingerprint",
"(",
"refMol",
",",
"probeMol",
",",
"fpFunction",
",",
"metric",
")",
"weights",
",",
"maxWeight",
"=",
"GetStandardizedWeights",
"(",
"weights",
")",
"fig",
"=",
"GetSimilarityMapFromWeights",
"(",
"probeMol",
",",
"weights",
",",
"*",
"*",
"kwargs",
")",
"return",
"fig",
",",
"maxWeight"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/Draw/SimilarityMaps.py#L235-L252 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/ensemble/gradient_boosting.py | python | LossFunction._update_terminal_region | (self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight) | Template method for updating terminal regions (=leaves). | Template method for updating terminal regions (=leaves). | [
"Template",
"method",
"for",
"updating",
"terminal",
"regions",
"(",
"=",
"leaves",
")",
"."
] | def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
"""Template method for updating terminal regions (=leaves). """ | [
"def",
"_update_terminal_region",
"(",
"self",
",",
"tree",
",",
"terminal_regions",
",",
"leaf",
",",
"X",
",",
"y",
",",
"residual",
",",
"pred",
",",
"sample_weight",
")",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/ensemble/gradient_boosting.py#L259-L261 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.SetTextCursor | (*args, **kwargs) | return _richtext.RichTextCtrl_SetTextCursor(*args, **kwargs) | SetTextCursor(self, Cursor cursor)
Set text cursor | SetTextCursor(self, Cursor cursor) | [
"SetTextCursor",
"(",
"self",
"Cursor",
"cursor",
")"
] | def SetTextCursor(*args, **kwargs):
"""
SetTextCursor(self, Cursor cursor)
Set text cursor
"""
return _richtext.RichTextCtrl_SetTextCursor(*args, **kwargs) | [
"def",
"SetTextCursor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_SetTextCursor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2989-L2995 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/framework/interfaces/face/face.py | python | RpcContext.protocol_context | (self) | Accesses a custom object specified by an implementation provider.
Returns:
A value specified by the provider of a Face interface implementation
affording custom state and behavior. | Accesses a custom object specified by an implementation provider. | [
"Accesses",
"a",
"custom",
"object",
"specified",
"by",
"an",
"implementation",
"provider",
"."
] | def protocol_context(self):
"""Accesses a custom object specified by an implementation provider.
Returns:
A value specified by the provider of a Face interface implementation
affording custom state and behavior.
"""
raise NotImplementedError() | [
"def",
"protocol_context",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/framework/interfaces/face/face.py#L183-L190 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/lib/auth_digest.py | python | get_ha1_dict_plain | (user_password_dict) | return get_ha1 | Returns a get_ha1 function which obtains a plaintext password from a
dictionary of the form: {username : password}.
If you want a simple dictionary-based authentication scheme, with plaintext
passwords, use get_ha1_dict_plain(my_userpass_dict) as the value for the
get_ha1 argument to digest_auth(). | Returns a get_ha1 function which obtains a plaintext password from a
dictionary of the form: {username : password}. | [
"Returns",
"a",
"get_ha1",
"function",
"which",
"obtains",
"a",
"plaintext",
"password",
"from",
"a",
"dictionary",
"of",
"the",
"form",
":",
"{",
"username",
":",
"password",
"}",
"."
] | def get_ha1_dict_plain(user_password_dict):
"""Returns a get_ha1 function which obtains a plaintext password from a
dictionary of the form: {username : password}.
If you want a simple dictionary-based authentication scheme, with plaintext
passwords, use get_ha1_dict_plain(my_userpass_dict) as the value for the
get_ha1 argument to digest_auth().
"""
def get_ha1(realm, username):
password = user_password_dict.get(username)
if password:
return md5_hex('%s:%s:%s' % (username, realm, password))
return None
return get_ha1 | [
"def",
"get_ha1_dict_plain",
"(",
"user_password_dict",
")",
":",
"def",
"get_ha1",
"(",
"realm",
",",
"username",
")",
":",
"password",
"=",
"user_password_dict",
".",
"get",
"(",
"username",
")",
"if",
"password",
":",
"return",
"md5_hex",
"(",
"'%s:%s:%s'",
"%",
"(",
"username",
",",
"realm",
",",
"password",
")",
")",
"return",
"None",
"return",
"get_ha1"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/auth_digest.py#L44-L58 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TUNGraph.IsNode | (self, *args) | return _snap.TUNGraph_IsNode(self, *args) | IsNode(TUNGraph self, int const & NId) -> bool
Parameters:
NId: int const & | IsNode(TUNGraph self, int const & NId) -> bool | [
"IsNode",
"(",
"TUNGraph",
"self",
"int",
"const",
"&",
"NId",
")",
"-",
">",
"bool"
] | def IsNode(self, *args):
"""
IsNode(TUNGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraph_IsNode(self, *args) | [
"def",
"IsNode",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TUNGraph_IsNode",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L3531-L3539 | |
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/site_packages/ordered_dict.py | python | OrderedDict.values | (self) | return [self[key] for key in self] | od.values() -> list of values in od | od.values() -> list of values in od | [
"od",
".",
"values",
"()",
"-",
">",
"list",
"of",
"values",
"in",
"od"
] | def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self] | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"[",
"self",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
"]"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/ordered_dict.py#L120-L122 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py | python | RawTurtle.write | (self, arg, move=False, align="left", font=("Arial", 8, "normal")) | Write text at the current turtle position.
Arguments:
arg -- info, which is to be written to the TurtleScreen
move (optional) -- True/False
align (optional) -- one of the strings "left", "center" or right"
font (optional) -- a triple (fontname, fontsize, fonttype)
Write text - the string representation of arg - at the current
turtle position according to align ("left", "center" or right")
and with the given font.
If move is True, the pen is moved to the bottom-right corner
of the text. By default, move is False.
Example (for a Turtle instance named turtle):
>>> turtle.write('Home = ', True, align="center")
>>> turtle.write((0,0), True) | Write text at the current turtle position. | [
"Write",
"text",
"at",
"the",
"current",
"turtle",
"position",
"."
] | def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")):
"""Write text at the current turtle position.
Arguments:
arg -- info, which is to be written to the TurtleScreen
move (optional) -- True/False
align (optional) -- one of the strings "left", "center" or right"
font (optional) -- a triple (fontname, fontsize, fonttype)
Write text - the string representation of arg - at the current
turtle position according to align ("left", "center" or right")
and with the given font.
If move is True, the pen is moved to the bottom-right corner
of the text. By default, move is False.
Example (for a Turtle instance named turtle):
>>> turtle.write('Home = ', True, align="center")
>>> turtle.write((0,0), True)
"""
if self.undobuffer:
self.undobuffer.push(["seq"])
self.undobuffer.cumulate = True
end = self._write(str(arg), align.lower(), font)
if move:
x, y = self.pos()
self.setpos(end, y)
if self.undobuffer:
self.undobuffer.cumulate = False | [
"def",
"write",
"(",
"self",
",",
"arg",
",",
"move",
"=",
"False",
",",
"align",
"=",
"\"left\"",
",",
"font",
"=",
"(",
"\"Arial\"",
",",
"8",
",",
"\"normal\"",
")",
")",
":",
"if",
"self",
".",
"undobuffer",
":",
"self",
".",
"undobuffer",
".",
"push",
"(",
"[",
"\"seq\"",
"]",
")",
"self",
".",
"undobuffer",
".",
"cumulate",
"=",
"True",
"end",
"=",
"self",
".",
"_write",
"(",
"str",
"(",
"arg",
")",
",",
"align",
".",
"lower",
"(",
")",
",",
"font",
")",
"if",
"move",
":",
"x",
",",
"y",
"=",
"self",
".",
"pos",
"(",
")",
"self",
".",
"setpos",
"(",
"end",
",",
"y",
")",
"if",
"self",
".",
"undobuffer",
":",
"self",
".",
"undobuffer",
".",
"cumulate",
"=",
"False"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py#L3276-L3303 | ||
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/layer.py | python | Pooling2d.__init__ | (self,
kernel_size,
stride=None,
padding=0,
is_max=True,
pad_mode="NOTSET") | Args:
kernel_size (int or tuple): kernel size for two direction of each
axis. For example, (2, 3), the first 2 means will add 2 at the
beginning and also 2 at the end for its axis.and if a int is
accepted, the kernel size will be initiated as (int, int)
stride (int or tuple): stride, the logic is the same as kernel size.
padding (int): tuple, list or None, padding, the logic is the same
as kernel size. However, if you set pad_mode as "SAME_UPPER" or
"SAME_LOWER" mode, you can set padding as None, and the padding
will be computed automatically.
is_max (bool): is max pooling or avg pooling
pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where
default value is NOTSET, which means explicit padding is used.
SAME_UPPER or SAME_LOWER mean pad the input so that the output
spatial size match the input. In case of odd number add the extra
padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. | Args:
kernel_size (int or tuple): kernel size for two direction of each
axis. For example, (2, 3), the first 2 means will add 2 at the
beginning and also 2 at the end for its axis.and if a int is
accepted, the kernel size will be initiated as (int, int)
stride (int or tuple): stride, the logic is the same as kernel size.
padding (int): tuple, list or None, padding, the logic is the same
as kernel size. However, if you set pad_mode as "SAME_UPPER" or
"SAME_LOWER" mode, you can set padding as None, and the padding
will be computed automatically.
is_max (bool): is max pooling or avg pooling
pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where
default value is NOTSET, which means explicit padding is used.
SAME_UPPER or SAME_LOWER mean pad the input so that the output
spatial size match the input. In case of odd number add the extra
padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. | [
"Args",
":",
"kernel_size",
"(",
"int",
"or",
"tuple",
")",
":",
"kernel",
"size",
"for",
"two",
"direction",
"of",
"each",
"axis",
".",
"For",
"example",
"(",
"2",
"3",
")",
"the",
"first",
"2",
"means",
"will",
"add",
"2",
"at",
"the",
"beginning",
"and",
"also",
"2",
"at",
"the",
"end",
"for",
"its",
"axis",
".",
"and",
"if",
"a",
"int",
"is",
"accepted",
"the",
"kernel",
"size",
"will",
"be",
"initiated",
"as",
"(",
"int",
"int",
")",
"stride",
"(",
"int",
"or",
"tuple",
")",
":",
"stride",
"the",
"logic",
"is",
"the",
"same",
"as",
"kernel",
"size",
".",
"padding",
"(",
"int",
")",
":",
"tuple",
"list",
"or",
"None",
"padding",
"the",
"logic",
"is",
"the",
"same",
"as",
"kernel",
"size",
".",
"However",
"if",
"you",
"set",
"pad_mode",
"as",
"SAME_UPPER",
"or",
"SAME_LOWER",
"mode",
"you",
"can",
"set",
"padding",
"as",
"None",
"and",
"the",
"padding",
"will",
"be",
"computed",
"automatically",
".",
"is_max",
"(",
"bool",
")",
":",
"is",
"max",
"pooling",
"or",
"avg",
"pooling",
"pad_mode",
"(",
"string",
")",
":",
"can",
"be",
"NOTSET",
"SAME_UPPER",
"or",
"SAME_LOWER",
"where",
"default",
"value",
"is",
"NOTSET",
"which",
"means",
"explicit",
"padding",
"is",
"used",
".",
"SAME_UPPER",
"or",
"SAME_LOWER",
"mean",
"pad",
"the",
"input",
"so",
"that",
"the",
"output",
"spatial",
"size",
"match",
"the",
"input",
".",
"In",
"case",
"of",
"odd",
"number",
"add",
"the",
"extra",
"padding",
"at",
"the",
"end",
"for",
"SAME_UPPER",
"and",
"at",
"the",
"beginning",
"for",
"SAME_LOWER",
"."
] | def __init__(self,
kernel_size,
stride=None,
padding=0,
is_max=True,
pad_mode="NOTSET"):
"""
Args:
kernel_size (int or tuple): kernel size for two direction of each
axis. For example, (2, 3), the first 2 means will add 2 at the
beginning and also 2 at the end for its axis.and if a int is
accepted, the kernel size will be initiated as (int, int)
stride (int or tuple): stride, the logic is the same as kernel size.
padding (int): tuple, list or None, padding, the logic is the same
as kernel size. However, if you set pad_mode as "SAME_UPPER" or
"SAME_LOWER" mode, you can set padding as None, and the padding
will be computed automatically.
is_max (bool): is max pooling or avg pooling
pad_mode (string): can be NOTSET, SAME_UPPER, or SAME_LOWER, where
default value is NOTSET, which means explicit padding is used.
SAME_UPPER or SAME_LOWER mean pad the input so that the output
spatial size match the input. In case of odd number add the extra
padding at the end for SAME_UPPER and at the beginning for SAME_LOWER.
"""
super(Pooling2d, self).__init__()
if isinstance(kernel_size, int):
self.kernel_size = (kernel_size, kernel_size)
elif isinstance(kernel_size, tuple):
self.kernel_size = kernel_size
else:
raise TypeError("Wrong kernel_size type.")
if stride is None:
self.stride = self.kernel_size
elif isinstance(stride, int):
self.stride = (stride, stride)
elif isinstance(stride, tuple):
self.stride = stride
assert stride[0] > 0 or (kernel_size[0] == 1 and padding[0] == 0), (
"stride[0]=0, but kernel_size[0]=%d, padding[0]=%d" %
(kernel_size[0], padding[0]))
else:
raise TypeError("Wrong stride type.")
self.odd_padding = (0, 0, 0, 0)
if isinstance(padding, int):
self.padding = (padding, padding)
elif isinstance(padding, tuple) or isinstance(padding, list):
if len(padding) == 2:
self.padding = padding
elif len(padding) == 4:
_h_mask = padding[0] - padding[1]
_w_mask = padding[2] - padding[3]
# the odd paddding is the value that cannot be handled by the tuple padding (w, h) mode
# so we need to firstly handle the input, then use the nomal padding method.
self.odd_padding = (max(_h_mask, 0), max(-_h_mask, 0),
max(_w_mask, 0), max(-_w_mask, 0))
self.padding = (
padding[0] - self.odd_padding[0],
padding[2] - self.odd_padding[2],
)
else:
raise TypeError("Wrong padding value.")
self.is_max = is_max
self.pad_mode = pad_mode | [
"def",
"__init__",
"(",
"self",
",",
"kernel_size",
",",
"stride",
"=",
"None",
",",
"padding",
"=",
"0",
",",
"is_max",
"=",
"True",
",",
"pad_mode",
"=",
"\"NOTSET\"",
")",
":",
"super",
"(",
"Pooling2d",
",",
"self",
")",
".",
"__init__",
"(",
")",
"if",
"isinstance",
"(",
"kernel_size",
",",
"int",
")",
":",
"self",
".",
"kernel_size",
"=",
"(",
"kernel_size",
",",
"kernel_size",
")",
"elif",
"isinstance",
"(",
"kernel_size",
",",
"tuple",
")",
":",
"self",
".",
"kernel_size",
"=",
"kernel_size",
"else",
":",
"raise",
"TypeError",
"(",
"\"Wrong kernel_size type.\"",
")",
"if",
"stride",
"is",
"None",
":",
"self",
".",
"stride",
"=",
"self",
".",
"kernel_size",
"elif",
"isinstance",
"(",
"stride",
",",
"int",
")",
":",
"self",
".",
"stride",
"=",
"(",
"stride",
",",
"stride",
")",
"elif",
"isinstance",
"(",
"stride",
",",
"tuple",
")",
":",
"self",
".",
"stride",
"=",
"stride",
"assert",
"stride",
"[",
"0",
"]",
">",
"0",
"or",
"(",
"kernel_size",
"[",
"0",
"]",
"==",
"1",
"and",
"padding",
"[",
"0",
"]",
"==",
"0",
")",
",",
"(",
"\"stride[0]=0, but kernel_size[0]=%d, padding[0]=%d\"",
"%",
"(",
"kernel_size",
"[",
"0",
"]",
",",
"padding",
"[",
"0",
"]",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Wrong stride type.\"",
")",
"self",
".",
"odd_padding",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"if",
"isinstance",
"(",
"padding",
",",
"int",
")",
":",
"self",
".",
"padding",
"=",
"(",
"padding",
",",
"padding",
")",
"elif",
"isinstance",
"(",
"padding",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"padding",
",",
"list",
")",
":",
"if",
"len",
"(",
"padding",
")",
"==",
"2",
":",
"self",
".",
"padding",
"=",
"padding",
"elif",
"len",
"(",
"padding",
")",
"==",
"4",
":",
"_h_mask",
"=",
"padding",
"[",
"0",
"]",
"-",
"padding",
"[",
"1",
"]",
"_w_mask",
"=",
"padding",
"[",
"2",
"]",
"-",
"padding",
"[",
"3",
"]",
"# the odd paddding is the value that cannot be handled by the tuple padding (w, h) mode",
"# so we need to firstly handle the input, then use the nomal padding method.",
"self",
".",
"odd_padding",
"=",
"(",
"max",
"(",
"_h_mask",
",",
"0",
")",
",",
"max",
"(",
"-",
"_h_mask",
",",
"0",
")",
",",
"max",
"(",
"_w_mask",
",",
"0",
")",
",",
"max",
"(",
"-",
"_w_mask",
",",
"0",
")",
")",
"self",
".",
"padding",
"=",
"(",
"padding",
"[",
"0",
"]",
"-",
"self",
".",
"odd_padding",
"[",
"0",
"]",
",",
"padding",
"[",
"2",
"]",
"-",
"self",
".",
"odd_padding",
"[",
"2",
"]",
",",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Wrong padding value.\"",
")",
"self",
".",
"is_max",
"=",
"is_max",
"self",
".",
"pad_mode",
"=",
"pad_mode"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/layer.py#L896-L962 | ||
stitchEm/stitchEm | 0f399501d41ab77933677f2907f41f80ceb704d7 | lib/bindings/samples/server/glfw.py | python | restore_window | (window) | Restores the specified window.
Wrapper for:
void glfwRestoreWindow(GLFWwindow* window); | Restores the specified window. | [
"Restores",
"the",
"specified",
"window",
"."
] | def restore_window(window):
"""
Restores the specified window.
Wrapper for:
void glfwRestoreWindow(GLFWwindow* window);
"""
_glfw.glfwRestoreWindow(window) | [
"def",
"restore_window",
"(",
"window",
")",
":",
"_glfw",
".",
"glfwRestoreWindow",
"(",
"window",
")"
] | https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/server/glfw.py#L1124-L1131 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Image.RemoveHandler | (*args, **kwargs) | return _core_.Image_RemoveHandler(*args, **kwargs) | RemoveHandler(String name) -> bool | RemoveHandler(String name) -> bool | [
"RemoveHandler",
"(",
"String",
"name",
")",
"-",
">",
"bool"
] | def RemoveHandler(*args, **kwargs):
"""RemoveHandler(String name) -> bool"""
return _core_.Image_RemoveHandler(*args, **kwargs) | [
"def",
"RemoveHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_RemoveHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3623-L3625 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/shutil.py | python | move | (src, dst) | Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over. | Recursively move a file or directory to another location. This is
similar to the Unix "mv" command. | [
"Recursively",
"move",
"a",
"file",
"or",
"directory",
"to",
"another",
"location",
".",
"This",
"is",
"similar",
"to",
"the",
"Unix",
"mv",
"command",
"."
] | def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.
"""
real_dst = dst
if os.path.isdir(dst):
if _samefile(src, dst):
# We might be on a case insensitive filesystem,
# perform the rename anyway.
os.rename(src, dst)
return
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error, "Destination path '%s' already exists" % real_dst
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src) | [
"def",
"move",
"(",
"src",
",",
"dst",
")",
":",
"real_dst",
"=",
"dst",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dst",
")",
":",
"if",
"_samefile",
"(",
"src",
",",
"dst",
")",
":",
"# We might be on a case insensitive filesystem,",
"# perform the rename anyway.",
"os",
".",
"rename",
"(",
"src",
",",
"dst",
")",
"return",
"real_dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"_basename",
"(",
"src",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"real_dst",
")",
":",
"raise",
"Error",
",",
"\"Destination path '%s' already exists\"",
"%",
"real_dst",
"try",
":",
"os",
".",
"rename",
"(",
"src",
",",
"real_dst",
")",
"except",
"OSError",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"src",
")",
":",
"if",
"_destinsrc",
"(",
"src",
",",
"dst",
")",
":",
"raise",
"Error",
",",
"\"Cannot move a directory '%s' into itself '%s'.\"",
"%",
"(",
"src",
",",
"dst",
")",
"copytree",
"(",
"src",
",",
"real_dst",
",",
"symlinks",
"=",
"True",
")",
"rmtree",
"(",
"src",
")",
"else",
":",
"copy2",
"(",
"src",
",",
"real_dst",
")",
"os",
".",
"unlink",
"(",
"src",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/shutil.py#L288-L326 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/onnxruntime_inference_collection.py | python | check_and_normalize_provider_args | (providers, provider_options, available_provider_names) | return list(provider_name_to_options.keys()), list(provider_name_to_options.values()) | Validates the 'providers' and 'provider_options' arguments and returns a
normalized version.
:param providers: Optional sequence of providers in order of decreasing
precedence. Values can either be provider names or tuples of
(provider name, options dict).
:param provider_options: Optional sequence of options dicts corresponding
to the providers listed in 'providers'.
:param available_provider_names: The available provider names.
:return: Tuple of (normalized 'providers' sequence, normalized
'provider_options' sequence).
'providers' can contain either names or names and options. When any options
are given in 'providers', 'provider_options' should not be used.
The normalized result is a tuple of:
1. Sequence of provider names in the same order as 'providers'.
2. Sequence of corresponding provider options dicts with string keys and
values. Unspecified provider options yield empty dicts. | Validates the 'providers' and 'provider_options' arguments and returns a
normalized version. | [
"Validates",
"the",
"providers",
"and",
"provider_options",
"arguments",
"and",
"returns",
"a",
"normalized",
"version",
"."
] | def check_and_normalize_provider_args(providers, provider_options, available_provider_names):
"""
Validates the 'providers' and 'provider_options' arguments and returns a
normalized version.
:param providers: Optional sequence of providers in order of decreasing
precedence. Values can either be provider names or tuples of
(provider name, options dict).
:param provider_options: Optional sequence of options dicts corresponding
to the providers listed in 'providers'.
:param available_provider_names: The available provider names.
:return: Tuple of (normalized 'providers' sequence, normalized
'provider_options' sequence).
'providers' can contain either names or names and options. When any options
are given in 'providers', 'provider_options' should not be used.
The normalized result is a tuple of:
1. Sequence of provider names in the same order as 'providers'.
2. Sequence of corresponding provider options dicts with string keys and
values. Unspecified provider options yield empty dicts.
"""
if providers is None:
return [], []
provider_name_to_options = collections.OrderedDict()
def set_provider_options(name, options):
if name not in available_provider_names:
warnings.warn("Specified provider '{}' is not in available provider names."
"Available providers: '{}'".format(name, ", ".join(available_provider_names)))
if name in provider_name_to_options:
warnings.warn("Duplicate provider '{}' encountered, ignoring.".format(name))
return
normalized_options = {str(key): str(value) for key, value in options.items()}
provider_name_to_options[name] = normalized_options
if not isinstance(providers, collections.abc.Sequence):
raise ValueError("'providers' should be a sequence.")
if provider_options is not None:
if not isinstance(provider_options, collections.abc.Sequence):
raise ValueError("'provider_options' should be a sequence.")
if len(providers) != len(provider_options):
raise ValueError("'providers' and 'provider_options' should be the same length if both are given.")
if not all([isinstance(provider, str) for provider in providers]):
raise ValueError("Only string values for 'providers' are supported if 'provider_options' is given.")
if not all([isinstance(options_for_provider, dict) for options_for_provider in provider_options]):
raise ValueError("'provider_options' values must be dicts.")
for name, options in zip(providers, provider_options):
set_provider_options(name, options)
else:
for provider in providers:
if isinstance(provider, str):
set_provider_options(provider, dict())
elif isinstance(provider, tuple) and len(provider) == 2 and \
isinstance(provider[0], str) and isinstance(provider[1], dict):
set_provider_options(provider[0], provider[1])
else:
raise ValueError("'providers' values must be either strings or (string, dict) tuples.")
return list(provider_name_to_options.keys()), list(provider_name_to_options.values()) | [
"def",
"check_and_normalize_provider_args",
"(",
"providers",
",",
"provider_options",
",",
"available_provider_names",
")",
":",
"if",
"providers",
"is",
"None",
":",
"return",
"[",
"]",
",",
"[",
"]",
"provider_name_to_options",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"def",
"set_provider_options",
"(",
"name",
",",
"options",
")",
":",
"if",
"name",
"not",
"in",
"available_provider_names",
":",
"warnings",
".",
"warn",
"(",
"\"Specified provider '{}' is not in available provider names.\"",
"\"Available providers: '{}'\"",
".",
"format",
"(",
"name",
",",
"\", \"",
".",
"join",
"(",
"available_provider_names",
")",
")",
")",
"if",
"name",
"in",
"provider_name_to_options",
":",
"warnings",
".",
"warn",
"(",
"\"Duplicate provider '{}' encountered, ignoring.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"normalized_options",
"=",
"{",
"str",
"(",
"key",
")",
":",
"str",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"options",
".",
"items",
"(",
")",
"}",
"provider_name_to_options",
"[",
"name",
"]",
"=",
"normalized_options",
"if",
"not",
"isinstance",
"(",
"providers",
",",
"collections",
".",
"abc",
".",
"Sequence",
")",
":",
"raise",
"ValueError",
"(",
"\"'providers' should be a sequence.\"",
")",
"if",
"provider_options",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"provider_options",
",",
"collections",
".",
"abc",
".",
"Sequence",
")",
":",
"raise",
"ValueError",
"(",
"\"'provider_options' should be a sequence.\"",
")",
"if",
"len",
"(",
"providers",
")",
"!=",
"len",
"(",
"provider_options",
")",
":",
"raise",
"ValueError",
"(",
"\"'providers' and 'provider_options' should be the same length if both are given.\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"provider",
",",
"str",
")",
"for",
"provider",
"in",
"providers",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Only string values for 'providers' are supported if 'provider_options' is given.\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"options_for_provider",
",",
"dict",
")",
"for",
"options_for_provider",
"in",
"provider_options",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"'provider_options' values must be dicts.\"",
")",
"for",
"name",
",",
"options",
"in",
"zip",
"(",
"providers",
",",
"provider_options",
")",
":",
"set_provider_options",
"(",
"name",
",",
"options",
")",
"else",
":",
"for",
"provider",
"in",
"providers",
":",
"if",
"isinstance",
"(",
"provider",
",",
"str",
")",
":",
"set_provider_options",
"(",
"provider",
",",
"dict",
"(",
")",
")",
"elif",
"isinstance",
"(",
"provider",
",",
"tuple",
")",
"and",
"len",
"(",
"provider",
")",
"==",
"2",
"and",
"isinstance",
"(",
"provider",
"[",
"0",
"]",
",",
"str",
")",
"and",
"isinstance",
"(",
"provider",
"[",
"1",
"]",
",",
"dict",
")",
":",
"set_provider_options",
"(",
"provider",
"[",
"0",
"]",
",",
"provider",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"'providers' values must be either strings or (string, dict) tuples.\"",
")",
"return",
"list",
"(",
"provider_name_to_options",
".",
"keys",
"(",
")",
")",
",",
"list",
"(",
"provider_name_to_options",
".",
"values",
"(",
")",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/onnxruntime_inference_collection.py#L25-L94 | |
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/patch_updater.py | python | extract_paths | (file) | return paths | Extract the list of modified paths from the patch file. | Extract the list of modified paths from the patch file. | [
"Extract",
"the",
"list",
"of",
"modified",
"paths",
"from",
"the",
"patch",
"file",
"."
] | def extract_paths(file):
""" Extract the list of modified paths from the patch file. """
paths = []
with open(file, 'r', encoding='utf-8') as fp:
for line in fp:
if line[:4] != '+++ ':
continue
match = re.match('^([^\t]+)', line[4:])
if not match:
continue
paths.append(match.group(1).strip())
return paths | [
"def",
"extract_paths",
"(",
"file",
")",
":",
"paths",
"=",
"[",
"]",
"with",
"open",
"(",
"file",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
":",
"if",
"line",
"[",
":",
"4",
"]",
"!=",
"'+++ '",
":",
"continue",
"match",
"=",
"re",
".",
"match",
"(",
"'^([^\\t]+)'",
",",
"line",
"[",
"4",
":",
"]",
")",
"if",
"not",
"match",
":",
"continue",
"paths",
".",
"append",
"(",
"match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
"return",
"paths"
] | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/patch_updater.py#L36-L47 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/tkMessageBox.py | python | askokcancel | (title=None, message=None, **options) | return s == OK | Ask if operation should proceed; return true if the answer is ok | Ask if operation should proceed; return true if the answer is ok | [
"Ask",
"if",
"operation",
"should",
"proceed",
";",
"return",
"true",
"if",
"the",
"answer",
"is",
"ok"
] | def askokcancel(title=None, message=None, **options):
"Ask if operation should proceed; return true if the answer is ok"
s = _show(title, message, QUESTION, OKCANCEL, **options)
return s == OK | [
"def",
"askokcancel",
"(",
"title",
"=",
"None",
",",
"message",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"s",
"=",
"_show",
"(",
"title",
",",
"message",
",",
"QUESTION",
",",
"OKCANCEL",
",",
"*",
"*",
"options",
")",
"return",
"s",
"==",
"OK"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/tkMessageBox.py#L97-L100 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetCurrentPos | (*args, **kwargs) | return _stc.StyledTextCtrl_GetCurrentPos(*args, **kwargs) | GetCurrentPos(self) -> int
Returns the position of the caret. | GetCurrentPos(self) -> int | [
"GetCurrentPos",
"(",
"self",
")",
"-",
">",
"int"
] | def GetCurrentPos(*args, **kwargs):
"""
GetCurrentPos(self) -> int
Returns the position of the caret.
"""
return _stc.StyledTextCtrl_GetCurrentPos(*args, **kwargs) | [
"def",
"GetCurrentPos",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetCurrentPos",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2095-L2101 | |
vgough/encfs | c444f9b9176beea1ad41a7b2e29ca26e709b57f7 | vendor/github.com/muflihun/easyloggingpp/tools/cpplint.py | python | _BlockInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Run checks that applies to text after the closing brace. | [
"Run",
"checks",
"that",
"applies",
"to",
"text",
"after",
"the",
"closing",
"brace",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"pass"
] | https://github.com/vgough/encfs/blob/c444f9b9176beea1ad41a7b2e29ca26e709b57f7/vendor/github.com/muflihun/easyloggingpp/tools/cpplint.py#L1655-L1666 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/sumolib/net/lane.py | python | Lane.setShape | (self, shape) | Set the shape of the lane
shape must be a list containing x,y,z coords as numbers
to represent the shape of the lane | Set the shape of the lane | [
"Set",
"the",
"shape",
"of",
"the",
"lane"
] | def setShape(self, shape):
"""Set the shape of the lane
shape must be a list containing x,y,z coords as numbers
to represent the shape of the lane
"""
for pp in shape:
if len(pp) != 3:
raise ValueError('shape point must consist of x,y,z')
self._shape3D = shape
self._shape = [(x, y) for x, y, z in shape] | [
"def",
"setShape",
"(",
"self",
",",
"shape",
")",
":",
"for",
"pp",
"in",
"shape",
":",
"if",
"len",
"(",
"pp",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'shape point must consist of x,y,z'",
")",
"self",
".",
"_shape3D",
"=",
"shape",
"self",
".",
"_shape",
"=",
"[",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
",",
"z",
"in",
"shape",
"]"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/sumolib/net/lane.py#L116-L127 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py | python | Type.get_result | (self) | return conf.lib.clang_getResultType(self) | Retrieve the result type associated with a function type. | Retrieve the result type associated with a function type. | [
"Retrieve",
"the",
"result",
"type",
"associated",
"with",
"a",
"function",
"type",
"."
] | def get_result(self):
"""
Retrieve the result type associated with a function type.
"""
return conf.lib.clang_getResultType(self) | [
"def",
"get_result",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getResultType",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L2084-L2088 | |
dmlc/decord | 96b750c7221322391969929e855b942d2fdcd06b | python/decord/_ffi/ndarray.py | python | NDArrayBase.asnumpy | (self) | return np_arr | Convert this array to numpy array
Returns
-------
np_arr : numpy.ndarray
The corresponding numpy array. | Convert this array to numpy array | [
"Convert",
"this",
"array",
"to",
"numpy",
"array"
] | def asnumpy(self):
"""Convert this array to numpy array
Returns
-------
np_arr : numpy.ndarray
The corresponding numpy array.
"""
t = DECORDType(self.dtype)
shape, dtype = self.shape, self.dtype
if t.lanes > 1:
shape = shape + (t.lanes,)
t.lanes = 1
dtype = str(t)
np_arr = np.empty(shape, dtype=dtype)
assert np_arr.flags['C_CONTIGUOUS']
data = np_arr.ctypes.data_as(ctypes.c_void_p)
nbytes = ctypes.c_size_t(np_arr.size * np_arr.dtype.itemsize)
check_call(_LIB.DECORDArrayCopyToBytes(self.handle, data, nbytes))
return np_arr | [
"def",
"asnumpy",
"(",
"self",
")",
":",
"t",
"=",
"DECORDType",
"(",
"self",
".",
"dtype",
")",
"shape",
",",
"dtype",
"=",
"self",
".",
"shape",
",",
"self",
".",
"dtype",
"if",
"t",
".",
"lanes",
">",
"1",
":",
"shape",
"=",
"shape",
"+",
"(",
"t",
".",
"lanes",
",",
")",
"t",
".",
"lanes",
"=",
"1",
"dtype",
"=",
"str",
"(",
"t",
")",
"np_arr",
"=",
"np",
".",
"empty",
"(",
"shape",
",",
"dtype",
"=",
"dtype",
")",
"assert",
"np_arr",
".",
"flags",
"[",
"'C_CONTIGUOUS'",
"]",
"data",
"=",
"np_arr",
".",
"ctypes",
".",
"data_as",
"(",
"ctypes",
".",
"c_void_p",
")",
"nbytes",
"=",
"ctypes",
".",
"c_size_t",
"(",
"np_arr",
".",
"size",
"*",
"np_arr",
".",
"dtype",
".",
"itemsize",
")",
"check_call",
"(",
"_LIB",
".",
"DECORDArrayCopyToBytes",
"(",
"self",
".",
"handle",
",",
"data",
",",
"nbytes",
")",
")",
"return",
"np_arr"
] | https://github.com/dmlc/decord/blob/96b750c7221322391969929e855b942d2fdcd06b/python/decord/_ffi/ndarray.py#L245-L264 | |
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/python/caffe/coord_map.py | python | coord_map | (fn) | Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords. | Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords. | [
"Define",
"the",
"coordinate",
"mapping",
"by",
"its",
"-",
"axis",
"-",
"scale",
":",
"output",
"coord",
"[",
"i",
"*",
"scale",
"]",
"<",
"-",
"input_coord",
"[",
"i",
"]",
"-",
"shift",
":",
"output",
"coord",
"[",
"i",
"]",
"<",
"-",
"output_coord",
"[",
"i",
"+",
"shift",
"]",
"s",
".",
"t",
".",
"the",
"identity",
"mapping",
"as",
"for",
"pointwise",
"layers",
"like",
"ReLu",
"is",
"defined",
"by",
"(",
"None",
"1",
"0",
")",
"since",
"it",
"is",
"independent",
"of",
"axis",
"and",
"does",
"not",
"transform",
"coords",
"."
] | def coord_map(fn):
"""
Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords.
"""
if fn.type_name in ['Convolution', 'Pooling', 'Im2col']:
axis, stride, ks, pad = conv_params(fn)
return axis, 1 / stride, (pad - (ks - 1) / 2) / stride
elif fn.type_name == 'Deconvolution':
axis, stride, ks, pad = conv_params(fn)
return axis, stride, (ks - 1) / 2 - pad
elif fn.type_name in PASS_THROUGH_LAYERS:
return None, 1, 0
elif fn.type_name == 'Crop':
axis, offset = crop_params(fn)
axis -= 1 # -1 for last non-coordinate dim.
return axis, 1, - offset
else:
raise UndefinedMapException | [
"def",
"coord_map",
"(",
"fn",
")",
":",
"if",
"fn",
".",
"type_name",
"in",
"[",
"'Convolution'",
",",
"'Pooling'",
",",
"'Im2col'",
"]",
":",
"axis",
",",
"stride",
",",
"ks",
",",
"pad",
"=",
"conv_params",
"(",
"fn",
")",
"return",
"axis",
",",
"1",
"/",
"stride",
",",
"(",
"pad",
"-",
"(",
"ks",
"-",
"1",
")",
"/",
"2",
")",
"/",
"stride",
"elif",
"fn",
".",
"type_name",
"==",
"'Deconvolution'",
":",
"axis",
",",
"stride",
",",
"ks",
",",
"pad",
"=",
"conv_params",
"(",
"fn",
")",
"return",
"axis",
",",
"stride",
",",
"(",
"ks",
"-",
"1",
")",
"/",
"2",
"-",
"pad",
"elif",
"fn",
".",
"type_name",
"in",
"PASS_THROUGH_LAYERS",
":",
"return",
"None",
",",
"1",
",",
"0",
"elif",
"fn",
".",
"type_name",
"==",
"'Crop'",
":",
"axis",
",",
"offset",
"=",
"crop_params",
"(",
"fn",
")",
"axis",
"-=",
"1",
"# -1 for last non-coordinate dim.",
"return",
"axis",
",",
"1",
",",
"-",
"offset",
"else",
":",
"raise",
"UndefinedMapException"
] | https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/python/caffe/coord_map.py#L57-L79 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/gtk/gizmos.py | python | TreeListColumnInfo.SetAlignment | (*args, **kwargs) | return _gizmos.TreeListColumnInfo_SetAlignment(*args, **kwargs) | SetAlignment(self, int alignment) | SetAlignment(self, int alignment) | [
"SetAlignment",
"(",
"self",
"int",
"alignment",
")"
] | def SetAlignment(*args, **kwargs):
"""SetAlignment(self, int alignment)"""
return _gizmos.TreeListColumnInfo_SetAlignment(*args, **kwargs) | [
"def",
"SetAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListColumnInfo_SetAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L432-L434 | |
wangkuiyi/mapreduce-lite | 1bb92fe094dc47480ef9163c34070a3199feead6 | src/mapreduce_lite/scheduler/util.py | python | SocketWrapper.recv | (self) | return urllib.unquote(message) | Receive message | Receive message | [
"Receive",
"message"
] | def recv(self):
""" Receive message
"""
while not '\n' in self.buf:
self.buf += self.sockobj.recv(1024)
message, remain = self.buf.split('\n', 1)
self.buf = remain
return urllib.unquote(message) | [
"def",
"recv",
"(",
"self",
")",
":",
"while",
"not",
"'\\n'",
"in",
"self",
".",
"buf",
":",
"self",
".",
"buf",
"+=",
"self",
".",
"sockobj",
".",
"recv",
"(",
"1024",
")",
"message",
",",
"remain",
"=",
"self",
".",
"buf",
".",
"split",
"(",
"'\\n'",
",",
"1",
")",
"self",
".",
"buf",
"=",
"remain",
"return",
"urllib",
".",
"unquote",
"(",
"message",
")"
] | https://github.com/wangkuiyi/mapreduce-lite/blob/1bb92fe094dc47480ef9163c34070a3199feead6/src/mapreduce_lite/scheduler/util.py#L57-L64 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/aui.py | python | AuiToolBarItem.SetAlignment | (*args, **kwargs) | return _aui.AuiToolBarItem_SetAlignment(*args, **kwargs) | SetAlignment(self, int l) | SetAlignment(self, int l) | [
"SetAlignment",
"(",
"self",
"int",
"l",
")"
] | def SetAlignment(*args, **kwargs):
"""SetAlignment(self, int l)"""
return _aui.AuiToolBarItem_SetAlignment(*args, **kwargs) | [
"def",
"SetAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBarItem_SetAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L1873-L1875 | |
google/angle | d5df233189cad620b8e0de653fe5e6cb778e209d | tools/android/modularization/convenience/lookup_dep.py | python | ClassLookupIndex.match | (self, search_string: str) | return matches | Get class/target entries where the class matches search_string | Get class/target entries where the class matches search_string | [
"Get",
"class",
"/",
"target",
"entries",
"where",
"the",
"class",
"matches",
"search_string"
] | def match(self, search_string: str) -> List[ClassEntry]:
"""Get class/target entries where the class matches search_string"""
# Priority 1: Exact full matches
if search_string in self._class_index:
return self._entries_for(search_string)
# Priority 2: Match full class name (any case), if it's a class name
matches = []
lower_search_string = search_string.lower()
if '.' not in lower_search_string:
for full_class_name in self._class_index:
package_and_class = full_class_name.rsplit('.', 1)
if len(package_and_class) < 2:
continue
class_name = package_and_class[1]
class_lower = class_name.lower()
if class_lower == lower_search_string:
matches.extend(self._entries_for(full_class_name))
if matches:
return matches
# Priority 3: Match anything
for full_class_name in self._class_index:
if lower_search_string in full_class_name.lower():
matches.extend(self._entries_for(full_class_name))
return matches | [
"def",
"match",
"(",
"self",
",",
"search_string",
":",
"str",
")",
"->",
"List",
"[",
"ClassEntry",
"]",
":",
"# Priority 1: Exact full matches",
"if",
"search_string",
"in",
"self",
".",
"_class_index",
":",
"return",
"self",
".",
"_entries_for",
"(",
"search_string",
")",
"# Priority 2: Match full class name (any case), if it's a class name",
"matches",
"=",
"[",
"]",
"lower_search_string",
"=",
"search_string",
".",
"lower",
"(",
")",
"if",
"'.'",
"not",
"in",
"lower_search_string",
":",
"for",
"full_class_name",
"in",
"self",
".",
"_class_index",
":",
"package_and_class",
"=",
"full_class_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"if",
"len",
"(",
"package_and_class",
")",
"<",
"2",
":",
"continue",
"class_name",
"=",
"package_and_class",
"[",
"1",
"]",
"class_lower",
"=",
"class_name",
".",
"lower",
"(",
")",
"if",
"class_lower",
"==",
"lower_search_string",
":",
"matches",
".",
"extend",
"(",
"self",
".",
"_entries_for",
"(",
"full_class_name",
")",
")",
"if",
"matches",
":",
"return",
"matches",
"# Priority 3: Match anything",
"for",
"full_class_name",
"in",
"self",
".",
"_class_index",
":",
"if",
"lower_search_string",
"in",
"full_class_name",
".",
"lower",
"(",
")",
":",
"matches",
".",
"extend",
"(",
"self",
".",
"_entries_for",
"(",
"full_class_name",
")",
")",
"return",
"matches"
] | https://github.com/google/angle/blob/d5df233189cad620b8e0de653fe5e6cb778e209d/tools/android/modularization/convenience/lookup_dep.py#L111-L137 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/skia/make.py | python | MakeClean | () | Cross-platform "make clean" operation. | Cross-platform "make clean" operation. | [
"Cross",
"-",
"platform",
"make",
"clean",
"operation",
"."
] | def MakeClean():
"""Cross-platform "make clean" operation."""
cd(SCRIPT_DIR)
rmtree(OUT_SUBDIR) | [
"def",
"MakeClean",
"(",
")",
":",
"cd",
"(",
"SCRIPT_DIR",
")",
"rmtree",
"(",
"OUT_SUBDIR",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/make.py#L50-L53 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/webencodings/__init__.py | python | _detect_bom | (input) | return None, input | Return (bom_encoding, input), with any BOM removed from the input. | Return (bom_encoding, input), with any BOM removed from the input. | [
"Return",
"(",
"bom_encoding",
"input",
")",
"with",
"any",
"BOM",
"removed",
"from",
"the",
"input",
"."
] | def _detect_bom(input):
"""Return (bom_encoding, input), with any BOM removed from the input."""
if input.startswith(b'\xFF\xFE'):
return _UTF16LE, input[2:]
if input.startswith(b'\xFE\xFF'):
return _UTF16BE, input[2:]
if input.startswith(b'\xEF\xBB\xBF'):
return UTF8, input[3:]
return None, input | [
"def",
"_detect_bom",
"(",
"input",
")",
":",
"if",
"input",
".",
"startswith",
"(",
"b'\\xFF\\xFE'",
")",
":",
"return",
"_UTF16LE",
",",
"input",
"[",
"2",
":",
"]",
"if",
"input",
".",
"startswith",
"(",
"b'\\xFE\\xFF'",
")",
":",
"return",
"_UTF16BE",
",",
"input",
"[",
"2",
":",
"]",
"if",
"input",
".",
"startswith",
"(",
"b'\\xEF\\xBB\\xBF'",
")",
":",
"return",
"UTF8",
",",
"input",
"[",
"3",
":",
"]",
"return",
"None",
",",
"input"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/webencodings/__init__.py#L321-L337 | |
weichengkuo/DeepBox | c4f8c065b6a51cf296540cc453a44f0519aaacc9 | caffe-fast-rcnn/scripts/cpp_lint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/caffe-fast-rcnn/scripts/cpp_lint.py#L767-L769 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/compat/dictconfig.py | python | BaseConfigurator.convert | (self, value) | return value | Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do. | Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do. | [
"Convert",
"values",
"to",
"an",
"appropriate",
"type",
".",
"dicts",
"lists",
"and",
"tuples",
"are",
"replaced",
"by",
"their",
"converting",
"alternatives",
".",
"Strings",
"are",
"checked",
"to",
"see",
"if",
"they",
"have",
"a",
"conversion",
"format",
"and",
"are",
"converted",
"if",
"they",
"do",
"."
] | def convert(self, value):
"""
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.
"""
if not isinstance(value, ConvertingDict) and isinstance(value, dict):
value = ConvertingDict(value)
value.configurator = self
elif not isinstance(value, ConvertingList) and isinstance(value, list):
value = ConvertingList(value)
value.configurator = self
elif not isinstance(value, ConvertingTuple) and\
isinstance(value, tuple):
value = ConvertingTuple(value)
value.configurator = self
elif isinstance(value, six.string_types): # str for py3k
m = self.CONVERT_PATTERN.match(value)
if m:
d = m.groupdict()
prefix = d['prefix']
converter = self.value_converters.get(prefix, None)
if converter:
suffix = d['suffix']
converter = getattr(self, converter)
value = converter(suffix)
return value | [
"def",
"convert",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"ConvertingDict",
")",
"and",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value",
"=",
"ConvertingDict",
"(",
"value",
")",
"value",
".",
"configurator",
"=",
"self",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"ConvertingList",
")",
"and",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"ConvertingList",
"(",
"value",
")",
"value",
".",
"configurator",
"=",
"self",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"ConvertingTuple",
")",
"and",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"value",
"=",
"ConvertingTuple",
"(",
"value",
")",
"value",
".",
"configurator",
"=",
"self",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"# str for py3k",
"m",
"=",
"self",
".",
"CONVERT_PATTERN",
".",
"match",
"(",
"value",
")",
"if",
"m",
":",
"d",
"=",
"m",
".",
"groupdict",
"(",
")",
"prefix",
"=",
"d",
"[",
"'prefix'",
"]",
"converter",
"=",
"self",
".",
"value_converters",
".",
"get",
"(",
"prefix",
",",
"None",
")",
"if",
"converter",
":",
"suffix",
"=",
"d",
"[",
"'suffix'",
"]",
"converter",
"=",
"getattr",
"(",
"self",
",",
"converter",
")",
"value",
"=",
"converter",
"(",
"suffix",
")",
"return",
"value"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/compat/dictconfig.py#L228-L254 | |
mickem/nscp | 79f89fdbb6da63f91bc9dedb7aea202fe938f237 | scripts/python/lib/google/protobuf/descriptor.py | python | FieldDescriptor.__init__ | (self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
has_default_value=True) | The arguments are as described in the description of FieldDescriptor
attributes above.
Note that containing_type may be None, and may be set later if necessary
(to deal with circular references between message types, for example).
Likewise for extension_scope. | The arguments are as described in the description of FieldDescriptor
attributes above. | [
"The",
"arguments",
"are",
"as",
"described",
"in",
"the",
"description",
"of",
"FieldDescriptor",
"attributes",
"above",
"."
] | def __init__(self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
has_default_value=True):
"""The arguments are as described in the description of FieldDescriptor
attributes above.
Note that containing_type may be None, and may be set later if necessary
(to deal with circular references between message types, for example).
Likewise for extension_scope.
"""
super(FieldDescriptor, self).__init__(options, 'FieldOptions')
self.name = name
self.full_name = full_name
self.index = index
self.number = number
self.type = type
self.cpp_type = cpp_type
self.label = label
self.has_default_value = has_default_value
self.default_value = default_value
self.containing_type = containing_type
self.message_type = message_type
self.enum_type = enum_type
self.is_extension = is_extension
self.extension_scope = extension_scope
if api_implementation.Type() == 'cpp':
if is_extension:
self._cdescriptor = cpp_message.GetExtensionDescriptor(full_name)
else:
self._cdescriptor = cpp_message.GetFieldDescriptor(full_name)
else:
self._cdescriptor = None | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"index",
",",
"number",
",",
"type",
",",
"cpp_type",
",",
"label",
",",
"default_value",
",",
"message_type",
",",
"enum_type",
",",
"containing_type",
",",
"is_extension",
",",
"extension_scope",
",",
"options",
"=",
"None",
",",
"has_default_value",
"=",
"True",
")",
":",
"super",
"(",
"FieldDescriptor",
",",
"self",
")",
".",
"__init__",
"(",
"options",
",",
"'FieldOptions'",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"full_name",
"=",
"full_name",
"self",
".",
"index",
"=",
"index",
"self",
".",
"number",
"=",
"number",
"self",
".",
"type",
"=",
"type",
"self",
".",
"cpp_type",
"=",
"cpp_type",
"self",
".",
"label",
"=",
"label",
"self",
".",
"has_default_value",
"=",
"has_default_value",
"self",
".",
"default_value",
"=",
"default_value",
"self",
".",
"containing_type",
"=",
"containing_type",
"self",
".",
"message_type",
"=",
"message_type",
"self",
".",
"enum_type",
"=",
"enum_type",
"self",
".",
"is_extension",
"=",
"is_extension",
"self",
".",
"extension_scope",
"=",
"extension_scope",
"if",
"api_implementation",
".",
"Type",
"(",
")",
"==",
"'cpp'",
":",
"if",
"is_extension",
":",
"self",
".",
"_cdescriptor",
"=",
"cpp_message",
".",
"GetExtensionDescriptor",
"(",
"full_name",
")",
"else",
":",
"self",
".",
"_cdescriptor",
"=",
"cpp_message",
".",
"GetFieldDescriptor",
"(",
"full_name",
")",
"else",
":",
"self",
".",
"_cdescriptor",
"=",
"None"
] | https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/descriptor.py#L370-L402 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | Maildir.get_folder | (self, folder) | return Maildir(os.path.join(self._path, '.' + folder),
factory=self._factory,
create=False) | Return a Maildir instance for the named folder. | Return a Maildir instance for the named folder. | [
"Return",
"a",
"Maildir",
"instance",
"for",
"the",
"named",
"folder",
"."
] | def get_folder(self, folder):
"""Return a Maildir instance for the named folder."""
return Maildir(os.path.join(self._path, '.' + folder),
factory=self._factory,
create=False) | [
"def",
"get_folder",
"(",
"self",
",",
"folder",
")",
":",
"return",
"Maildir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"'.'",
"+",
"folder",
")",
",",
"factory",
"=",
"self",
".",
"_factory",
",",
"create",
"=",
"False",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L445-L449 | |
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/segmentation/scripts/BirdsEyeView.py | python | BirdsEyeView.world2image_uvMat | (self, uv_mat) | return resultB[0] / resultB[1] | :param uv_mat:
:return: | [] | def world2image_uvMat(self, uv_mat):
"""
:param uv_mat:
:return:
"""
if uv_mat.shape[0] == 2:
if len(uv_mat.shape) == 1:
uv_mat = uv_mat.reshape(uv_mat.shape + (1,))
uv_mat = np.vstack((uv_mat, np.ones((1, uv_mat.shape[1]), uv_mat.dtype)))
result = np.dot(self.Tr33, uv_mat)
# w0 = -(uv_mat[0]* self.Tr_inv_33[1,0]+ uv_mat[1]* self.Tr_inv[1,1])/self.Tr_inv[1,2]
resultB = np.broadcast_arrays(result, result[-1, :])
return resultB[0] / resultB[1] | [
"def",
"world2image_uvMat",
"(",
"self",
",",
"uv_mat",
")",
":",
"if",
"uv_mat",
".",
"shape",
"[",
"0",
"]",
"==",
"2",
":",
"if",
"len",
"(",
"uv_mat",
".",
"shape",
")",
"==",
"1",
":",
"uv_mat",
"=",
"uv_mat",
".",
"reshape",
"(",
"uv_mat",
".",
"shape",
"+",
"(",
"1",
",",
")",
")",
"uv_mat",
"=",
"np",
".",
"vstack",
"(",
"(",
"uv_mat",
",",
"np",
".",
"ones",
"(",
"(",
"1",
",",
"uv_mat",
".",
"shape",
"[",
"1",
"]",
")",
",",
"uv_mat",
".",
"dtype",
")",
")",
")",
"result",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"Tr33",
",",
"uv_mat",
")",
"# w0 = -(uv_mat[0]* self.Tr_inv_33[1,0]+ uv_mat[1]* self.Tr_inv[1,1])/self.Tr_inv[1,2]",
"resultB",
"=",
"np",
".",
"broadcast_arrays",
"(",
"result",
",",
"result",
"[",
"-",
"1",
",",
":",
"]",
")",
"return",
"resultB",
"[",
"0",
"]",
"/",
"resultB",
"[",
"1",
"]"
] | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/segmentation/scripts/BirdsEyeView.py#L250-L263 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | demo/agw/AUI.py | python | ProgressGauge.__init__ | (self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=(-1,30)) | Default class constructor. | Default class constructor. | [
"Default",
"class",
"constructor",
"."
] | def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=(-1,30)):
""" Default class constructor. """
wx.PyWindow.__init__(self, parent, id, pos, size, style=wx.BORDER_NONE)
self._value = 0
self._steps = 16
self._pos = 0
self._current = 0
self._gaugeproportion = 0.4
self._startTime = time.time()
self._bottomStartColour = wx.GREEN
rgba = self._bottomStartColour.Red(), self._bottomStartColour.Green(), \
self._bottomStartColour.Blue(), self._bottomStartColour.Alpha()
self._bottomEndColour = self.LightColour(self._bottomStartColour, 30)
self._topStartColour = self.LightColour(self._bottomStartColour, 80)
self._topEndColour = self.LightColour(self._bottomStartColour, 40)
self._background = wx.Brush(wx.WHITE, wx.SOLID)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"id",
"=",
"wx",
".",
"ID_ANY",
",",
"pos",
"=",
"wx",
".",
"DefaultPosition",
",",
"size",
"=",
"(",
"-",
"1",
",",
"30",
")",
")",
":",
"wx",
".",
"PyWindow",
".",
"__init__",
"(",
"self",
",",
"parent",
",",
"id",
",",
"pos",
",",
"size",
",",
"style",
"=",
"wx",
".",
"BORDER_NONE",
")",
"self",
".",
"_value",
"=",
"0",
"self",
".",
"_steps",
"=",
"16",
"self",
".",
"_pos",
"=",
"0",
"self",
".",
"_current",
"=",
"0",
"self",
".",
"_gaugeproportion",
"=",
"0.4",
"self",
".",
"_startTime",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_bottomStartColour",
"=",
"wx",
".",
"GREEN",
"rgba",
"=",
"self",
".",
"_bottomStartColour",
".",
"Red",
"(",
")",
",",
"self",
".",
"_bottomStartColour",
".",
"Green",
"(",
")",
",",
"self",
".",
"_bottomStartColour",
".",
"Blue",
"(",
")",
",",
"self",
".",
"_bottomStartColour",
".",
"Alpha",
"(",
")",
"self",
".",
"_bottomEndColour",
"=",
"self",
".",
"LightColour",
"(",
"self",
".",
"_bottomStartColour",
",",
"30",
")",
"self",
".",
"_topStartColour",
"=",
"self",
".",
"LightColour",
"(",
"self",
".",
"_bottomStartColour",
",",
"80",
")",
"self",
".",
"_topEndColour",
"=",
"self",
".",
"LightColour",
"(",
"self",
".",
"_bottomStartColour",
",",
"40",
")",
"self",
".",
"_background",
"=",
"wx",
".",
"Brush",
"(",
"wx",
".",
"WHITE",
",",
"wx",
".",
"SOLID",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_PAINT",
",",
"self",
".",
"OnPaint",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_ERASE_BACKGROUND",
",",
"self",
".",
"OnEraseBackground",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/demo/agw/AUI.py#L732-L754 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.