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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apache/incubator-mxnet
|
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
|
python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py
|
python
|
convert_broadcast_logical_or
|
(node, **kwargs)
|
return nodes
|
Map MXNet's broadcast logical or operator attributes to onnx's Or operator
and return the created node.
|
Map MXNet's broadcast logical or operator attributes to onnx's Or operator
and return the created node.
|
[
"Map",
"MXNet",
"s",
"broadcast",
"logical",
"or",
"operator",
"attributes",
"to",
"onnx",
"s",
"Or",
"operator",
"and",
"return",
"the",
"created",
"node",
"."
] |
def convert_broadcast_logical_or(node, **kwargs):
"""Map MXNet's broadcast logical or operator attributes to onnx's Or operator
and return the created node.
"""
from onnx.helper import make_node
from onnx import TensorProto
name, input_nodes, _ = get_inputs(node, kwargs)
input_dtypes = get_input_dtypes(node, kwargs)
dtype = input_dtypes[0]
dtype_t = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[dtype]
nodes = [
make_node("Cast", [input_nodes[0]], [name+"_cast0"], to=int(TensorProto.BOOL)),
make_node("Cast", [input_nodes[1]], [name+"_cast1"], to=int(TensorProto.BOOL)),
make_node("Or", [name+"_cast0", name+"_cast1"], [name+"_or"]),
make_node("Cast", [name+"_or"], [name], name=name, to=int(dtype_t))
]
return nodes
|
[
"def",
"convert_broadcast_logical_or",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"onnx",
".",
"helper",
"import",
"make_node",
"from",
"onnx",
"import",
"TensorProto",
"name",
",",
"input_nodes",
",",
"_",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"input_dtypes",
"=",
"get_input_dtypes",
"(",
"node",
",",
"kwargs",
")",
"dtype",
"=",
"input_dtypes",
"[",
"0",
"]",
"dtype_t",
"=",
"onnx",
".",
"mapping",
".",
"NP_TYPE_TO_TENSOR_TYPE",
"[",
"dtype",
"]",
"nodes",
"=",
"[",
"make_node",
"(",
"\"Cast\"",
",",
"[",
"input_nodes",
"[",
"0",
"]",
"]",
",",
"[",
"name",
"+",
"\"_cast0\"",
"]",
",",
"to",
"=",
"int",
"(",
"TensorProto",
".",
"BOOL",
")",
")",
",",
"make_node",
"(",
"\"Cast\"",
",",
"[",
"input_nodes",
"[",
"1",
"]",
"]",
",",
"[",
"name",
"+",
"\"_cast1\"",
"]",
",",
"to",
"=",
"int",
"(",
"TensorProto",
".",
"BOOL",
")",
")",
",",
"make_node",
"(",
"\"Or\"",
",",
"[",
"name",
"+",
"\"_cast0\"",
",",
"name",
"+",
"\"_cast1\"",
"]",
",",
"[",
"name",
"+",
"\"_or\"",
"]",
")",
",",
"make_node",
"(",
"\"Cast\"",
",",
"[",
"name",
"+",
"\"_or\"",
"]",
",",
"[",
"name",
"]",
",",
"name",
"=",
"name",
",",
"to",
"=",
"int",
"(",
"dtype_t",
")",
")",
"]",
"return",
"nodes"
] |
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py#L2428-L2444
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/_misc.py
|
python
|
GetNumberFromUser
|
(*args, **kwargs)
|
return _misc_.GetNumberFromUser(*args, **kwargs)
|
GetNumberFromUser(String message, String prompt, String caption, long value,
long min=0, long max=100, Window parent=None,
Point pos=DefaultPosition) -> long
|
GetNumberFromUser(String message, String prompt, String caption, long value,
long min=0, long max=100, Window parent=None,
Point pos=DefaultPosition) -> long
|
[
"GetNumberFromUser",
"(",
"String",
"message",
"String",
"prompt",
"String",
"caption",
"long",
"value",
"long",
"min",
"=",
"0",
"long",
"max",
"=",
"100",
"Window",
"parent",
"=",
"None",
"Point",
"pos",
"=",
"DefaultPosition",
")",
"-",
">",
"long"
] |
def GetNumberFromUser(*args, **kwargs):
"""
GetNumberFromUser(String message, String prompt, String caption, long value,
long min=0, long max=100, Window parent=None,
Point pos=DefaultPosition) -> long
"""
return _misc_.GetNumberFromUser(*args, **kwargs)
|
[
"def",
"GetNumberFromUser",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"GetNumberFromUser",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L493-L499
|
|
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py
|
python
|
DocComment.SuppressionOnly
|
(self)
|
return True
|
Returns whether this comment contains only suppression flags.
|
Returns whether this comment contains only suppression flags.
|
[
"Returns",
"whether",
"this",
"comment",
"contains",
"only",
"suppression",
"flags",
"."
] |
def SuppressionOnly(self):
"""Returns whether this comment contains only suppression flags."""
if not self.__flags:
return False
for flag in self.__flags:
if flag.flag_type != 'suppress':
return False
return True
|
[
"def",
"SuppressionOnly",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__flags",
":",
"return",
"False",
"for",
"flag",
"in",
"self",
".",
"__flags",
":",
"if",
"flag",
".",
"flag_type",
"!=",
"'suppress'",
":",
"return",
"False",
"return",
"True"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py#L361-L370
|
|
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
qt/python/mantidqt/mantidqt/widgets/sliceviewer/presenter.py
|
python
|
SliceViewer.slicepoint_changed
|
(self)
|
Indicates the slicepoint has been updated
|
Indicates the slicepoint has been updated
|
[
"Indicates",
"the",
"slicepoint",
"has",
"been",
"updated"
] |
def slicepoint_changed(self):
"""Indicates the slicepoint has been updated"""
self._call_peaks_presenter_if_created("notify",
PeaksViewerPresenter.Event.SlicePointChanged)
self.update_plot_data()
|
[
"def",
"slicepoint_changed",
"(",
"self",
")",
":",
"self",
".",
"_call_peaks_presenter_if_created",
"(",
"\"notify\"",
",",
"PeaksViewerPresenter",
".",
"Event",
".",
"SlicePointChanged",
")",
"self",
".",
"update_plot_data",
"(",
")"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/presenter.py#L216-L220
|
||
taskflow/taskflow
|
f423a100a70b275f6e7331bc96537a3fe172e8d7
|
3rd-party/tbb/python/tbb/__init__.py
|
python
|
TBBProcessPool27._repopulate_pool
|
(self)
|
Bring the number of pool processes up to the specified number,
for use after reaping workers which have exited.
|
Bring the number of pool processes up to the specified number,
for use after reaping workers which have exited.
|
[
"Bring",
"the",
"number",
"of",
"pool",
"processes",
"up",
"to",
"the",
"specified",
"number",
"for",
"use",
"after",
"reaping",
"workers",
"which",
"have",
"exited",
"."
] |
def _repopulate_pool(self):
"""Bring the number of pool processes up to the specified number,
for use after reaping workers which have exited.
"""
from multiprocessing.util import debug
for i in range(self._processes - len(self._pool)):
w = self.Process(target=tbb_process_pool_worker27,
args=(self._inqueue, self._outqueue,
self._initializer,
self._initargs, self._maxtasksperchild)
)
self._pool.append(w)
w.name = w.name.replace('Process', 'PoolWorker')
w.daemon = True
w.start()
debug('added worker')
|
[
"def",
"_repopulate_pool",
"(",
"self",
")",
":",
"from",
"multiprocessing",
".",
"util",
"import",
"debug",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_processes",
"-",
"len",
"(",
"self",
".",
"_pool",
")",
")",
":",
"w",
"=",
"self",
".",
"Process",
"(",
"target",
"=",
"tbb_process_pool_worker27",
",",
"args",
"=",
"(",
"self",
".",
"_inqueue",
",",
"self",
".",
"_outqueue",
",",
"self",
".",
"_initializer",
",",
"self",
".",
"_initargs",
",",
"self",
".",
"_maxtasksperchild",
")",
")",
"self",
".",
"_pool",
".",
"append",
"(",
"w",
")",
"w",
".",
"name",
"=",
"w",
".",
"name",
".",
"replace",
"(",
"'Process'",
",",
"'PoolWorker'",
")",
"w",
".",
"daemon",
"=",
"True",
"w",
".",
"start",
"(",
")",
"debug",
"(",
"'added worker'",
")"
] |
https://github.com/taskflow/taskflow/blob/f423a100a70b275f6e7331bc96537a3fe172e8d7/3rd-party/tbb/python/tbb/__init__.py#L75-L91
|
||
randombit/botan
|
e068d80953469fc8a3ec1715d0f64756d972daba
|
configure.py
|
python
|
have_program
|
(program)
|
return False
|
Test for the existence of a program
|
Test for the existence of a program
|
[
"Test",
"for",
"the",
"existence",
"of",
"a",
"program"
] |
def have_program(program):
"""
Test for the existence of a program
"""
def exe_test(path, program):
exe_file = os.path.join(path, program)
if os.path.exists(exe_file) and os.access(exe_file, os.X_OK):
logging.debug('Found program %s in %s', program, path)
return True
else:
return False
exe_suffixes = ['', '.exe']
for path in os.environ['PATH'].split(os.pathsep):
for suffix in exe_suffixes:
if exe_test(path, program + suffix):
return True
logging.debug('Program %s not found', program)
return False
|
[
"def",
"have_program",
"(",
"program",
")",
":",
"def",
"exe_test",
"(",
"path",
",",
"program",
")",
":",
"exe_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"program",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"exe_file",
")",
"and",
"os",
".",
"access",
"(",
"exe_file",
",",
"os",
".",
"X_OK",
")",
":",
"logging",
".",
"debug",
"(",
"'Found program %s in %s'",
",",
"program",
",",
"path",
")",
"return",
"True",
"else",
":",
"return",
"False",
"exe_suffixes",
"=",
"[",
"''",
",",
"'.exe'",
"]",
"for",
"path",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"for",
"suffix",
"in",
"exe_suffixes",
":",
"if",
"exe_test",
"(",
"path",
",",
"program",
"+",
"suffix",
")",
":",
"return",
"True",
"logging",
".",
"debug",
"(",
"'Program %s not found'",
",",
"program",
")",
"return",
"False"
] |
https://github.com/randombit/botan/blob/e068d80953469fc8a3ec1715d0f64756d972daba/configure.py#L2777-L2799
|
|
verilog-to-routing/vtr-verilog-to-routing
|
d9719cf7374821156c3cee31d66991cb85578562
|
vtr_flow/scripts/benchtracker/util.py
|
python
|
walk_runs
|
(params, operation, select=sort_runs)
|
walk the selected run# directories and apply operation on each
|
walk the selected run# directories and apply operation on each
|
[
"walk",
"the",
"selected",
"run#",
"directories",
"and",
"apply",
"operation",
"on",
"each"
] |
def walk_runs(params, operation, select=sort_runs):
"""walk the selected run# directories and apply operation on each"""
runs = [
run for run in immediate_subdir(params.task_dir) if is_rundir_name(params.run_prefix, run)
]
# select how to and which runs to use for a certain range
select(runs)
if not runs:
print("no {}s in {}".format(params.run_prefix, params.task_dir))
sys.exit(1)
for run in runs:
operation(params, run)
|
[
"def",
"walk_runs",
"(",
"params",
",",
"operation",
",",
"select",
"=",
"sort_runs",
")",
":",
"runs",
"=",
"[",
"run",
"for",
"run",
"in",
"immediate_subdir",
"(",
"params",
".",
"task_dir",
")",
"if",
"is_rundir_name",
"(",
"params",
".",
"run_prefix",
",",
"run",
")",
"]",
"# select how to and which runs to use for a certain range",
"select",
"(",
"runs",
")",
"if",
"not",
"runs",
":",
"print",
"(",
"\"no {}s in {}\"",
".",
"format",
"(",
"params",
".",
"run_prefix",
",",
"params",
".",
"task_dir",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"for",
"run",
"in",
"runs",
":",
"operation",
"(",
"params",
",",
"run",
")"
] |
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/benchtracker/util.py#L22-L33
|
||
PaddlePaddle/Paddle-Lite
|
75fa072dca1c54d8b4ce4fb9e5491edc787e6300
|
tools/codestyle/docstring_checker.py
|
python
|
DocstringChecker.with_raises
|
(self, node, doc)
|
return True
|
with_raises checks if one line doc end-with '.' .
Args:
node (astroid.node): the node is visiting.
doc (Docstring): Docstring object.
Returns:
True if successful otherwise False.
|
with_raises checks if one line doc end-with '.' .
Args:
node (astroid.node): the node is visiting.
doc (Docstring): Docstring object.
Returns:
True if successful otherwise False.
|
[
"with_raises",
"checks",
"if",
"one",
"line",
"doc",
"end",
"-",
"with",
".",
".",
"Args",
":",
"node",
"(",
"astroid",
".",
"node",
")",
":",
"the",
"node",
"is",
"visiting",
".",
"doc",
"(",
"Docstring",
")",
":",
"Docstring",
"object",
".",
"Returns",
":",
"True",
"if",
"successful",
"otherwise",
"False",
"."
] |
def with_raises(self, node, doc):
"""with_raises checks if one line doc end-with '.' .
Args:
node (astroid.node): the node is visiting.
doc (Docstring): Docstring object.
Returns:
True if successful otherwise False.
"""
find = False
for t in node.body:
if not isinstance(t, astroid.Raise):
continue
find = True
break
if not find:
return True
if len(doc.get_raises()) == 0:
self.add_message('W9008', node=node, line=node.fromlineno)
return False
return True
|
[
"def",
"with_raises",
"(",
"self",
",",
"node",
",",
"doc",
")",
":",
"find",
"=",
"False",
"for",
"t",
"in",
"node",
".",
"body",
":",
"if",
"not",
"isinstance",
"(",
"t",
",",
"astroid",
".",
"Raise",
")",
":",
"continue",
"find",
"=",
"True",
"break",
"if",
"not",
"find",
":",
"return",
"True",
"if",
"len",
"(",
"doc",
".",
"get_raises",
"(",
")",
")",
"==",
"0",
":",
"self",
".",
"add_message",
"(",
"'W9008'",
",",
"node",
"=",
"node",
",",
"line",
"=",
"node",
".",
"fromlineno",
")",
"return",
"False",
"return",
"True"
] |
https://github.com/PaddlePaddle/Paddle-Lite/blob/75fa072dca1c54d8b4ce4fb9e5491edc787e6300/tools/codestyle/docstring_checker.py#L259-L283
|
|
cms-sw/cmssw
|
fd9de012d503d3405420bcbeec0ec879baa57cf2
|
RecoVertex/BeamSpotProducer/scripts/getBeamSpotDB.py
|
python
|
pack
|
(high,low)
|
return (h|low)
|
pack high,low 32bit unsigned int to one unsigned 64bit long long
Note:the print value of result number may appear signed, if the sign bit is used.
|
pack high,low 32bit unsigned int to one unsigned 64bit long long
Note:the print value of result number may appear signed, if the sign bit is used.
|
[
"pack",
"high",
"low",
"32bit",
"unsigned",
"int",
"to",
"one",
"unsigned",
"64bit",
"long",
"long",
"Note",
":",
"the",
"print",
"value",
"of",
"result",
"number",
"may",
"appear",
"signed",
"if",
"the",
"sign",
"bit",
"is",
"used",
"."
] |
def pack(high,low):
"""pack high,low 32bit unsigned int to one unsigned 64bit long long
Note:the print value of result number may appear signed, if the sign bit is used.
"""
h=high<<32
return (h|low)
|
[
"def",
"pack",
"(",
"high",
",",
"low",
")",
":",
"h",
"=",
"high",
"<<",
"32",
"return",
"(",
"h",
"|",
"low",
")"
] |
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/RecoVertex/BeamSpotProducer/scripts/getBeamSpotDB.py#L82-L87
|
|
gimli-org/gimli
|
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
|
pygimli/solver/solver.py
|
python
|
showSparseMatrix
|
(mat, full=False)
|
Show the content of a sparse matrix.
Parameters
----------
mat: :gimliapi:`GIMLI::SparseMatrix` | :gimliapi:`GIMLI::SparseMapMatrix`
Matrix to be shown.
full: bool [False]
Show as dense matrix.
|
Show the content of a sparse matrix.
|
[
"Show",
"the",
"content",
"of",
"a",
"sparse",
"matrix",
"."
] |
def showSparseMatrix(mat, full=False):
"""Show the content of a sparse matrix.
Parameters
----------
mat: :gimliapi:`GIMLI::SparseMatrix` | :gimliapi:`GIMLI::SparseMapMatrix`
Matrix to be shown.
full: bool [False]
Show as dense matrix.
"""
if isinstance(mat, pg.matrix.SparseMapMatrix):
m_ = pg.matrix.SparseMatrix(mat)
return showSparseMatrix(m_, full)
else:
rows = mat.vecRowIdx()
cols = mat.vecColPtr()
vals = mat.vecVals()
matD = None
if full:
matD = pg.Matrix(mat.rows(), mat.cols())
for i in range(mat.rows()):
for j in range(cols[i], cols[i + 1]):
if full:
matD[i, rows[j]] = vals[j]
else:
if vals[j] != 0:
print(i, rows[j], vals[j])
if full:
print(np.array(matD))
|
[
"def",
"showSparseMatrix",
"(",
"mat",
",",
"full",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"mat",
",",
"pg",
".",
"matrix",
".",
"SparseMapMatrix",
")",
":",
"m_",
"=",
"pg",
".",
"matrix",
".",
"SparseMatrix",
"(",
"mat",
")",
"return",
"showSparseMatrix",
"(",
"m_",
",",
"full",
")",
"else",
":",
"rows",
"=",
"mat",
".",
"vecRowIdx",
"(",
")",
"cols",
"=",
"mat",
".",
"vecColPtr",
"(",
")",
"vals",
"=",
"mat",
".",
"vecVals",
"(",
")",
"matD",
"=",
"None",
"if",
"full",
":",
"matD",
"=",
"pg",
".",
"Matrix",
"(",
"mat",
".",
"rows",
"(",
")",
",",
"mat",
".",
"cols",
"(",
")",
")",
"for",
"i",
"in",
"range",
"(",
"mat",
".",
"rows",
"(",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"cols",
"[",
"i",
"]",
",",
"cols",
"[",
"i",
"+",
"1",
"]",
")",
":",
"if",
"full",
":",
"matD",
"[",
"i",
",",
"rows",
"[",
"j",
"]",
"]",
"=",
"vals",
"[",
"j",
"]",
"else",
":",
"if",
"vals",
"[",
"j",
"]",
"!=",
"0",
":",
"print",
"(",
"i",
",",
"rows",
"[",
"j",
"]",
",",
"vals",
"[",
"j",
"]",
")",
"if",
"full",
":",
"print",
"(",
"np",
".",
"array",
"(",
"matD",
")",
")"
] |
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/solver/solver.py#L1013-L1044
|
||
baidu-research/tensorflow-allreduce
|
66d5b855e90b0949e9fa5cca5599fd729a70e874
|
tensorflow/python/ops/distributions/bijector_impl.py
|
python
|
_Mapping.y_key
|
(self)
|
return (self.y,) + self._deep_tuple(tuple(sorted(self.kwargs.items())))
|
Returns key used for caching X=g^{-1}(Y).
|
Returns key used for caching X=g^{-1}(Y).
|
[
"Returns",
"key",
"used",
"for",
"caching",
"X",
"=",
"g^",
"{",
"-",
"1",
"}",
"(",
"Y",
")",
"."
] |
def y_key(self):
"""Returns key used for caching X=g^{-1}(Y)."""
return (self.y,) + self._deep_tuple(tuple(sorted(self.kwargs.items())))
|
[
"def",
"y_key",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"y",
",",
")",
"+",
"self",
".",
"_deep_tuple",
"(",
"tuple",
"(",
"sorted",
"(",
"self",
".",
"kwargs",
".",
"items",
"(",
")",
")",
")",
")"
] |
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/distributions/bijector_impl.py#L67-L69
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/_controls.py
|
python
|
InfoBar.SetEffectDuration
|
(*args, **kwargs)
|
return _controls_.InfoBar_SetEffectDuration(*args, **kwargs)
|
SetEffectDuration(self, int duration)
|
SetEffectDuration(self, int duration)
|
[
"SetEffectDuration",
"(",
"self",
"int",
"duration",
")"
] |
def SetEffectDuration(*args, **kwargs):
"""SetEffectDuration(self, int duration)"""
return _controls_.InfoBar_SetEffectDuration(*args, **kwargs)
|
[
"def",
"SetEffectDuration",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"InfoBar_SetEffectDuration",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L7745-L7747
|
|
eventql/eventql
|
7ca0dbb2e683b525620ea30dc40540a22d5eb227
|
deps/3rdparty/spidermonkey/mozjs/python/blessings/blessings/__init__.py
|
python
|
Terminal._resolve_capability
|
(self, atom)
|
return u''
|
Return a terminal code for a capname or a sugary name, or an empty Unicode.
The return value is always Unicode, because otherwise it is clumsy
(especially in Python 3) to concatenate with real (Unicode) strings.
|
Return a terminal code for a capname or a sugary name, or an empty Unicode.
|
[
"Return",
"a",
"terminal",
"code",
"for",
"a",
"capname",
"or",
"a",
"sugary",
"name",
"or",
"an",
"empty",
"Unicode",
"."
] |
def _resolve_capability(self, atom):
"""Return a terminal code for a capname or a sugary name, or an empty Unicode.
The return value is always Unicode, because otherwise it is clumsy
(especially in Python 3) to concatenate with real (Unicode) strings.
"""
code = tigetstr(self._sugar.get(atom, atom))
if code:
# We can encode escape sequences as UTF-8 because they never
# contain chars > 127, and UTF-8 never changes anything within that
# range..
return code.decode('utf-8')
return u''
|
[
"def",
"_resolve_capability",
"(",
"self",
",",
"atom",
")",
":",
"code",
"=",
"tigetstr",
"(",
"self",
".",
"_sugar",
".",
"get",
"(",
"atom",
",",
"atom",
")",
")",
"if",
"code",
":",
"# We can encode escape sequences as UTF-8 because they never",
"# contain chars > 127, and UTF-8 never changes anything within that",
"# range..",
"return",
"code",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"u''"
] |
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/blessings/blessings/__init__.py#L279-L292
|
|
facebookincubator/fizz
|
bd0ba1b80f72023cb7ede671a4caa85f6664d3f6
|
build/fbcode_builder/getdeps/fetcher.py
|
python
|
copy_if_different
|
(src_name, dest_name)
|
return True
|
Copy src_name -> dest_name, but only touch dest_name
if src_name is different from dest_name, making this a
more build system friendly way to copy.
|
Copy src_name -> dest_name, but only touch dest_name
if src_name is different from dest_name, making this a
more build system friendly way to copy.
|
[
"Copy",
"src_name",
"-",
">",
"dest_name",
"but",
"only",
"touch",
"dest_name",
"if",
"src_name",
"is",
"different",
"from",
"dest_name",
"making",
"this",
"a",
"more",
"build",
"system",
"friendly",
"way",
"to",
"copy",
"."
] |
def copy_if_different(src_name, dest_name):
"""Copy src_name -> dest_name, but only touch dest_name
if src_name is different from dest_name, making this a
more build system friendly way to copy."""
src_st = os.lstat(src_name)
if not does_file_need_update(src_name, src_st, dest_name):
return False
dest_parent = os.path.dirname(dest_name)
if not os.path.exists(dest_parent):
os.makedirs(dest_parent)
if stat.S_ISLNK(src_st.st_mode):
try:
os.unlink(dest_name)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
target = os.readlink(src_name)
print("Symlinking %s -> %s" % (dest_name, target))
os.symlink(target, dest_name)
else:
print("Copying %s -> %s" % (src_name, dest_name))
shutil.copy2(src_name, dest_name)
return True
|
[
"def",
"copy_if_different",
"(",
"src_name",
",",
"dest_name",
")",
":",
"src_st",
"=",
"os",
".",
"lstat",
"(",
"src_name",
")",
"if",
"not",
"does_file_need_update",
"(",
"src_name",
",",
"src_st",
",",
"dest_name",
")",
":",
"return",
"False",
"dest_parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dest_name",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest_parent",
")",
":",
"os",
".",
"makedirs",
"(",
"dest_parent",
")",
"if",
"stat",
".",
"S_ISLNK",
"(",
"src_st",
".",
"st_mode",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"dest_name",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"target",
"=",
"os",
".",
"readlink",
"(",
"src_name",
")",
"print",
"(",
"\"Symlinking %s -> %s\"",
"%",
"(",
"dest_name",
",",
"target",
")",
")",
"os",
".",
"symlink",
"(",
"target",
",",
"dest_name",
")",
"else",
":",
"print",
"(",
"\"Copying %s -> %s\"",
"%",
"(",
"src_name",
",",
"dest_name",
")",
")",
"shutil",
".",
"copy2",
"(",
"src_name",
",",
"dest_name",
")",
"return",
"True"
] |
https://github.com/facebookincubator/fizz/blob/bd0ba1b80f72023cb7ede671a4caa85f6664d3f6/build/fbcode_builder/getdeps/fetcher.py#L359-L383
|
|
funnyzhou/Adaptive_Feeding
|
9c78182331d8c0ea28de47226e805776c638d46f
|
tools/extra/resize_and_crop_images.py
|
python
|
OpenCVResizeCrop.resize_and_crop_image
|
(self, input_file, output_file, output_side_length = 256)
|
Takes an image name, resize it and crop the center square
|
Takes an image name, resize it and crop the center square
|
[
"Takes",
"an",
"image",
"name",
"resize",
"it",
"and",
"crop",
"the",
"center",
"square"
] |
def resize_and_crop_image(self, input_file, output_file, output_side_length = 256):
'''Takes an image name, resize it and crop the center square
'''
img = cv2.imread(input_file)
height, width, depth = img.shape
new_height = output_side_length
new_width = output_side_length
if height > width:
new_height = output_side_length * height / width
else:
new_width = output_side_length * width / height
resized_img = cv2.resize(img, (new_width, new_height))
height_offset = (new_height - output_side_length) / 2
width_offset = (new_width - output_side_length) / 2
cropped_img = resized_img[height_offset:height_offset + output_side_length,
width_offset:width_offset + output_side_length]
cv2.imwrite(output_file, cropped_img)
|
[
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"input_file",
")",
"height",
",",
"width",
",",
"depth",
"=",
"img",
".",
"shape",
"new_height",
"=",
"output_side_length",
"new_width",
"=",
"output_side_length",
"if",
"height",
">",
"width",
":",
"new_height",
"=",
"output_side_length",
"*",
"height",
"/",
"width",
"else",
":",
"new_width",
"=",
"output_side_length",
"*",
"width",
"/",
"height",
"resized_img",
"=",
"cv2",
".",
"resize",
"(",
"img",
",",
"(",
"new_width",
",",
"new_height",
")",
")",
"height_offset",
"=",
"(",
"new_height",
"-",
"output_side_length",
")",
"/",
"2",
"width_offset",
"=",
"(",
"new_width",
"-",
"output_side_length",
")",
"/",
"2",
"cropped_img",
"=",
"resized_img",
"[",
"height_offset",
":",
"height_offset",
"+",
"output_side_length",
",",
"width_offset",
":",
"width_offset",
"+",
"output_side_length",
"]",
"cv2",
".",
"imwrite",
"(",
"output_file",
",",
"cropped_img",
")"
] |
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/tools/extra/resize_and_crop_images.py#L20-L36
|
||
microsoft/CNTK
|
e9396480025b9ca457d26b6f33dd07c474c6aa04
|
bindings/python/cntk/contrib/deeprl/agent/policy_gradient.py
|
python
|
ActorCritic.__init__
|
(self, config_filename, o_space, a_space)
|
Constructor for policy gradient.
Args:
config_filename: configure file specifying training details.
o_space: observation space, gym.spaces.tuple_space.Tuple is not
supported.
a_space: action space, limits to gym.spaces.discrete.Discrete.
|
Constructor for policy gradient.
|
[
"Constructor",
"for",
"policy",
"gradient",
"."
] |
def __init__(self, config_filename, o_space, a_space):
"""
Constructor for policy gradient.
Args:
config_filename: configure file specifying training details.
o_space: observation space, gym.spaces.tuple_space.Tuple is not
supported.
a_space: action space, limits to gym.spaces.discrete.Discrete.
"""
super(ActorCritic, self).__init__(o_space, a_space)
self._parameters = PolicyGradientParameters(config_filename)
# Create preprocessor.
if self._parameters.preprocessing:
preproc = self._import_method(self._parameters.preprocessing)
self._preprocessor = preproc(
self._shape_of_inputs,
*ast.literal_eval(self._parameters.preprocessing_args))
self._set_up_policy_network_and_value_network()
self._trajectory_states = []
self._trajectory_actions = []
self._trajectory_rewards = []
# Training data for the policy and value networks. Note they share the
# same input.
self._input_buffer = []
self._value_network_output_buffer = []
self._policy_network_output_buffer = []
self._policy_network_weight_buffer = []
self.episode_count = 0
self.step_count = 0
|
[
"def",
"__init__",
"(",
"self",
",",
"config_filename",
",",
"o_space",
",",
"a_space",
")",
":",
"super",
"(",
"ActorCritic",
",",
"self",
")",
".",
"__init__",
"(",
"o_space",
",",
"a_space",
")",
"self",
".",
"_parameters",
"=",
"PolicyGradientParameters",
"(",
"config_filename",
")",
"# Create preprocessor.",
"if",
"self",
".",
"_parameters",
".",
"preprocessing",
":",
"preproc",
"=",
"self",
".",
"_import_method",
"(",
"self",
".",
"_parameters",
".",
"preprocessing",
")",
"self",
".",
"_preprocessor",
"=",
"preproc",
"(",
"self",
".",
"_shape_of_inputs",
",",
"*",
"ast",
".",
"literal_eval",
"(",
"self",
".",
"_parameters",
".",
"preprocessing_args",
")",
")",
"self",
".",
"_set_up_policy_network_and_value_network",
"(",
")",
"self",
".",
"_trajectory_states",
"=",
"[",
"]",
"self",
".",
"_trajectory_actions",
"=",
"[",
"]",
"self",
".",
"_trajectory_rewards",
"=",
"[",
"]",
"# Training data for the policy and value networks. Note they share the",
"# same input.",
"self",
".",
"_input_buffer",
"=",
"[",
"]",
"self",
".",
"_value_network_output_buffer",
"=",
"[",
"]",
"self",
".",
"_policy_network_output_buffer",
"=",
"[",
"]",
"self",
".",
"_policy_network_weight_buffer",
"=",
"[",
"]",
"self",
".",
"episode_count",
"=",
"0",
"self",
".",
"step_count",
"=",
"0"
] |
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/contrib/deeprl/agent/policy_gradient.py#L26-L61
|
||
hydrogen-music/hydrogen
|
8a4eff74f9706922bd3a649a17cb18f4f5849cc1
|
windows/ci/copy_thirdparty_dlls.py
|
python
|
LibraryResolver.get_info
|
(self, file_name, kind: int = LibraryKind.THIRDPARTY)
|
Fetch information about given library.
|
Fetch information about given library.
|
[
"Fetch",
"information",
"about",
"given",
"library",
"."
] |
def get_info(self, file_name, kind: int = LibraryKind.THIRDPARTY) -> Library:
"""
Fetch information about given library.
"""
logging.debug("Processing %s", file_name)
system_lib = self.find_lib(file_name, self.kind_paths)
if system_lib:
logging.debug(" Found system library: %s", system_lib)
return Library(file_name, system_lib, LibraryKind.SYSTEM, [])
path = self.find_lib(file_name, self.libdirs)
if path:
logging.debug(" Found: %s", path)
deps = self.scan_dependencies(path)
logging.debug(" Dependencies: %s", " ".join(deps))
return Library(file_name, path, kind, deps)
raise LibraryNotFoundError("Cannot find DLL {0}".format(file_name))
|
[
"def",
"get_info",
"(",
"self",
",",
"file_name",
",",
"kind",
":",
"int",
"=",
"LibraryKind",
".",
"THIRDPARTY",
")",
"->",
"Library",
":",
"logging",
".",
"debug",
"(",
"\"Processing %s\"",
",",
"file_name",
")",
"system_lib",
"=",
"self",
".",
"find_lib",
"(",
"file_name",
",",
"self",
".",
"kind_paths",
")",
"if",
"system_lib",
":",
"logging",
".",
"debug",
"(",
"\" Found system library: %s\"",
",",
"system_lib",
")",
"return",
"Library",
"(",
"file_name",
",",
"system_lib",
",",
"LibraryKind",
".",
"SYSTEM",
",",
"[",
"]",
")",
"path",
"=",
"self",
".",
"find_lib",
"(",
"file_name",
",",
"self",
".",
"libdirs",
")",
"if",
"path",
":",
"logging",
".",
"debug",
"(",
"\" Found: %s\"",
",",
"path",
")",
"deps",
"=",
"self",
".",
"scan_dependencies",
"(",
"path",
")",
"logging",
".",
"debug",
"(",
"\" Dependencies: %s\"",
",",
"\" \"",
".",
"join",
"(",
"deps",
")",
")",
"return",
"Library",
"(",
"file_name",
",",
"path",
",",
"kind",
",",
"deps",
")",
"raise",
"LibraryNotFoundError",
"(",
"\"Cannot find DLL {0}\"",
".",
"format",
"(",
"file_name",
")",
")"
] |
https://github.com/hydrogen-music/hydrogen/blob/8a4eff74f9706922bd3a649a17cb18f4f5849cc1/windows/ci/copy_thirdparty_dlls.py#L115-L133
|
||
windystrife/UnrealEngine_NVIDIAGameWorks
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py
|
python
|
LoggerAdapter.log
|
(self, level, msg, *args, **kwargs)
|
Delegate a log call to the underlying logger, after adding
contextual information from this adapter instance.
|
Delegate a log call to the underlying logger, after adding
contextual information from this adapter instance.
|
[
"Delegate",
"a",
"log",
"call",
"to",
"the",
"underlying",
"logger",
"after",
"adding",
"contextual",
"information",
"from",
"this",
"adapter",
"instance",
"."
] |
def log(self, level, msg, *args, **kwargs):
"""
Delegate a log call to the underlying logger, after adding
contextual information from this adapter instance.
"""
msg, kwargs = self.process(msg, kwargs)
self.logger.log(level, msg, *args, **kwargs)
|
[
"def",
"log",
"(",
"self",
",",
"level",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
",",
"kwargs",
"=",
"self",
".",
"process",
"(",
"msg",
",",
"kwargs",
")",
"self",
".",
"logger",
".",
"log",
"(",
"level",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py#L1465-L1471
|
||
Xilinx/Vitis-AI
|
fc74d404563d9951b57245443c73bef389f3657f
|
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/source_remote.py
|
python
|
send_eager_tracebacks
|
(destinations,
origin_stack,
send_source=True)
|
Send the tracebacks of an eager execution call to debug server(s).
Args:
destinations: gRPC destination addresses, a `str` or a `list` of `str`s,
e.g., "localhost:4242". If a `list`, gRPC requests containing the same
origin_stack: The traceback of the eager operation invocation.
send_source: Whether the source files involved in the op tracebacks but
outside the TensorFlow library are to be sent.
|
Send the tracebacks of an eager execution call to debug server(s).
|
[
"Send",
"the",
"tracebacks",
"of",
"an",
"eager",
"execution",
"call",
"to",
"debug",
"server",
"(",
"s",
")",
"."
] |
def send_eager_tracebacks(destinations,
origin_stack,
send_source=True):
"""Send the tracebacks of an eager execution call to debug server(s).
Args:
destinations: gRPC destination addresses, a `str` or a `list` of `str`s,
e.g., "localhost:4242". If a `list`, gRPC requests containing the same
origin_stack: The traceback of the eager operation invocation.
send_source: Whether the source files involved in the op tracebacks but
outside the TensorFlow library are to be sent.
"""
_send_call_tracebacks(
destinations, origin_stack, is_eager_execution=True,
send_source=send_source)
|
[
"def",
"send_eager_tracebacks",
"(",
"destinations",
",",
"origin_stack",
",",
"send_source",
"=",
"True",
")",
":",
"_send_call_tracebacks",
"(",
"destinations",
",",
"origin_stack",
",",
"is_eager_execution",
"=",
"True",
",",
"send_source",
"=",
"send_source",
")"
] |
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/source_remote.py#L200-L214
|
||
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py
|
python
|
IdleConf.GetThemeDict
|
(self,type,themeName)
|
return theme
|
type - string, 'default' or 'user' theme type
themeName - string, theme name
Returns a dictionary which holds {option:value} for each element
in the specified theme. Values are loaded over a set of ultimate last
fallback defaults to guarantee that all theme elements are present in
a newly created theme.
|
type - string, 'default' or 'user' theme type
themeName - string, theme name
Returns a dictionary which holds {option:value} for each element
in the specified theme. Values are loaded over a set of ultimate last
fallback defaults to guarantee that all theme elements are present in
a newly created theme.
|
[
"type",
"-",
"string",
"default",
"or",
"user",
"theme",
"type",
"themeName",
"-",
"string",
"theme",
"name",
"Returns",
"a",
"dictionary",
"which",
"holds",
"{",
"option",
":",
"value",
"}",
"for",
"each",
"element",
"in",
"the",
"specified",
"theme",
".",
"Values",
"are",
"loaded",
"over",
"a",
"set",
"of",
"ultimate",
"last",
"fallback",
"defaults",
"to",
"guarantee",
"that",
"all",
"theme",
"elements",
"are",
"present",
"in",
"a",
"newly",
"created",
"theme",
"."
] |
def GetThemeDict(self,type,themeName):
"""
type - string, 'default' or 'user' theme type
themeName - string, theme name
Returns a dictionary which holds {option:value} for each element
in the specified theme. Values are loaded over a set of ultimate last
fallback defaults to guarantee that all theme elements are present in
a newly created theme.
"""
if type == 'user':
cfgParser=self.userCfg['highlight']
elif type == 'default':
cfgParser=self.defaultCfg['highlight']
else:
raise InvalidTheme, 'Invalid theme type specified'
#foreground and background values are provded for each theme element
#(apart from cursor) even though all these values are not yet used
#by idle, to allow for their use in the future. Default values are
#generally black and white.
theme={ 'normal-foreground':'#000000',
'normal-background':'#ffffff',
'keyword-foreground':'#000000',
'keyword-background':'#ffffff',
'builtin-foreground':'#000000',
'builtin-background':'#ffffff',
'comment-foreground':'#000000',
'comment-background':'#ffffff',
'string-foreground':'#000000',
'string-background':'#ffffff',
'definition-foreground':'#000000',
'definition-background':'#ffffff',
'hilite-foreground':'#000000',
'hilite-background':'gray',
'break-foreground':'#ffffff',
'break-background':'#000000',
'hit-foreground':'#ffffff',
'hit-background':'#000000',
'error-foreground':'#ffffff',
'error-background':'#000000',
#cursor (only foreground can be set)
'cursor-foreground':'#000000',
#shell window
'stdout-foreground':'#000000',
'stdout-background':'#ffffff',
'stderr-foreground':'#000000',
'stderr-background':'#ffffff',
'console-foreground':'#000000',
'console-background':'#ffffff' }
for element in theme.keys():
if not cfgParser.has_option(themeName,element):
#we are going to return a default, print warning
warning=('\n Warning: configHandler.py - IdleConf.GetThemeDict'
' -\n problem retrieving theme element %r'
'\n from theme %r.\n'
' returning default value: %r\n' %
(element, themeName, theme[element]))
try:
sys.stderr.write(warning)
except IOError:
pass
colour=cfgParser.Get(themeName,element,default=theme[element])
theme[element]=colour
return theme
|
[
"def",
"GetThemeDict",
"(",
"self",
",",
"type",
",",
"themeName",
")",
":",
"if",
"type",
"==",
"'user'",
":",
"cfgParser",
"=",
"self",
".",
"userCfg",
"[",
"'highlight'",
"]",
"elif",
"type",
"==",
"'default'",
":",
"cfgParser",
"=",
"self",
".",
"defaultCfg",
"[",
"'highlight'",
"]",
"else",
":",
"raise",
"InvalidTheme",
",",
"'Invalid theme type specified'",
"#foreground and background values are provded for each theme element",
"#(apart from cursor) even though all these values are not yet used",
"#by idle, to allow for their use in the future. Default values are",
"#generally black and white.",
"theme",
"=",
"{",
"'normal-foreground'",
":",
"'#000000'",
",",
"'normal-background'",
":",
"'#ffffff'",
",",
"'keyword-foreground'",
":",
"'#000000'",
",",
"'keyword-background'",
":",
"'#ffffff'",
",",
"'builtin-foreground'",
":",
"'#000000'",
",",
"'builtin-background'",
":",
"'#ffffff'",
",",
"'comment-foreground'",
":",
"'#000000'",
",",
"'comment-background'",
":",
"'#ffffff'",
",",
"'string-foreground'",
":",
"'#000000'",
",",
"'string-background'",
":",
"'#ffffff'",
",",
"'definition-foreground'",
":",
"'#000000'",
",",
"'definition-background'",
":",
"'#ffffff'",
",",
"'hilite-foreground'",
":",
"'#000000'",
",",
"'hilite-background'",
":",
"'gray'",
",",
"'break-foreground'",
":",
"'#ffffff'",
",",
"'break-background'",
":",
"'#000000'",
",",
"'hit-foreground'",
":",
"'#ffffff'",
",",
"'hit-background'",
":",
"'#000000'",
",",
"'error-foreground'",
":",
"'#ffffff'",
",",
"'error-background'",
":",
"'#000000'",
",",
"#cursor (only foreground can be set)",
"'cursor-foreground'",
":",
"'#000000'",
",",
"#shell window",
"'stdout-foreground'",
":",
"'#000000'",
",",
"'stdout-background'",
":",
"'#ffffff'",
",",
"'stderr-foreground'",
":",
"'#000000'",
",",
"'stderr-background'",
":",
"'#ffffff'",
",",
"'console-foreground'",
":",
"'#000000'",
",",
"'console-background'",
":",
"'#ffffff'",
"}",
"for",
"element",
"in",
"theme",
".",
"keys",
"(",
")",
":",
"if",
"not",
"cfgParser",
".",
"has_option",
"(",
"themeName",
",",
"element",
")",
":",
"#we are going to return a default, print warning",
"warning",
"=",
"(",
"'\\n Warning: configHandler.py - IdleConf.GetThemeDict'",
"' -\\n problem retrieving theme element %r'",
"'\\n from theme %r.\\n'",
"' returning default value: %r\\n'",
"%",
"(",
"element",
",",
"themeName",
",",
"theme",
"[",
"element",
"]",
")",
")",
"try",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"warning",
")",
"except",
"IOError",
":",
"pass",
"colour",
"=",
"cfgParser",
".",
"Get",
"(",
"themeName",
",",
"element",
",",
"default",
"=",
"theme",
"[",
"element",
"]",
")",
"theme",
"[",
"element",
"]",
"=",
"colour",
"return",
"theme"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py#L324-L386
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/utils.py
|
python
|
CountCallbackInvoker.increment
|
(self)
|
Increment the count by one
|
Increment the count by one
|
[
"Increment",
"the",
"count",
"by",
"one"
] |
def increment(self):
"""Increment the count by one"""
with self._lock:
if self._is_finalized:
raise RuntimeError(
'Counter has been finalized it can no longer be '
'incremented.'
)
self._count += 1
|
[
"def",
"increment",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_is_finalized",
":",
"raise",
"RuntimeError",
"(",
"'Counter has been finalized it can no longer be '",
"'incremented.'",
")",
"self",
".",
"_count",
"+=",
"1"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/utils.py#L209-L217
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/_misc.py
|
python
|
DataObjectSimple.SetData
|
(*args, **kwargs)
|
return _misc_.DataObjectSimple_SetData(*args, **kwargs)
|
SetData(self, String data) -> bool
Copy the data value to the data object. Must be implemented in the
derived class if the object supports setting its data.
|
SetData(self, String data) -> bool
|
[
"SetData",
"(",
"self",
"String",
"data",
")",
"-",
">",
"bool"
] |
def SetData(*args, **kwargs):
"""
SetData(self, String data) -> bool
Copy the data value to the data object. Must be implemented in the
derived class if the object supports setting its data.
"""
return _misc_.DataObjectSimple_SetData(*args, **kwargs)
|
[
"def",
"SetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DataObjectSimple_SetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L5054-L5062
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/windows/Lib/xml/sax/xmlreader.py
|
python
|
XMLReader.getContentHandler
|
(self)
|
return self._cont_handler
|
Returns the current ContentHandler.
|
Returns the current ContentHandler.
|
[
"Returns",
"the",
"current",
"ContentHandler",
"."
] |
def getContentHandler(self):
"Returns the current ContentHandler."
return self._cont_handler
|
[
"def",
"getContentHandler",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cont_handler"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/xml/sax/xmlreader.py#L34-L36
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/propgrid.py
|
python
|
PropertyGrid.DoHidePropertyError
|
(*args, **kwargs)
|
return _propgrid.PropertyGrid_DoHidePropertyError(*args, **kwargs)
|
DoHidePropertyError(self, PGProperty property)
|
DoHidePropertyError(self, PGProperty property)
|
[
"DoHidePropertyError",
"(",
"self",
"PGProperty",
"property",
")"
] |
def DoHidePropertyError(*args, **kwargs):
"""DoHidePropertyError(self, PGProperty property)"""
return _propgrid.PropertyGrid_DoHidePropertyError(*args, **kwargs)
|
[
"def",
"DoHidePropertyError",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_DoHidePropertyError",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2435-L2437
|
|
PixarAnimationStudios/OpenSubdiv
|
ff76e0f2dc9c9202b7d2f965f264bfd6f41866d5
|
regression/far_regression/example_createMesh.py
|
python
|
createMesh
|
(vertices, polygons, parent=None)
|
return dagpath.partialPathName()
|
Create a mesh with the specified vertices and polygons
|
Create a mesh with the specified vertices and polygons
|
[
"Create",
"a",
"mesh",
"with",
"the",
"specified",
"vertices",
"and",
"polygons"
] |
def createMesh(vertices, polygons, parent=None):
'''Create a mesh with the specified vertices and polygons
'''
# The parameters used in MFnMesh.create() can all be derived from the
# input vertices and polygon lists
numVertices = len(vertices)
numPolygons = len(polygons)
verticesM = convertToMPointArray(vertices)
polygonCounts = [len(i) for i in polygons]
polygonCountsM = convertToMIntArray(polygonCounts)
# Flatten the list of lists
# Reference: http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
polygonConnects = list(chain.from_iterable(polygons))
polygonConnectsM = convertToMIntArray(polygonConnects)
# Determine parent
if parent == None:
parentM = om.MObject()
else:
parentM = getDagPath(parent).node()
# Create Mesh
newMesh = om.MFnMesh()
newTransformOrShape = newMesh.create(
numVertices,
numPolygons,
verticesM,
polygonCountsM,
polygonConnectsM,
parentM)
dagpath = om.MDagPath()
om.MDagPath.getAPathTo( newTransformOrShape, dagpath )
# Assign the default shader to the mesh.
cmds.sets(
dagpath.fullPathName(),
edit=True,
forceElement='initialShadingGroup')
return dagpath.partialPathName()
|
[
"def",
"createMesh",
"(",
"vertices",
",",
"polygons",
",",
"parent",
"=",
"None",
")",
":",
"# The parameters used in MFnMesh.create() can all be derived from the",
"# input vertices and polygon lists",
"numVertices",
"=",
"len",
"(",
"vertices",
")",
"numPolygons",
"=",
"len",
"(",
"polygons",
")",
"verticesM",
"=",
"convertToMPointArray",
"(",
"vertices",
")",
"polygonCounts",
"=",
"[",
"len",
"(",
"i",
")",
"for",
"i",
"in",
"polygons",
"]",
"polygonCountsM",
"=",
"convertToMIntArray",
"(",
"polygonCounts",
")",
"# Flatten the list of lists",
"# Reference: http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python",
"polygonConnects",
"=",
"list",
"(",
"chain",
".",
"from_iterable",
"(",
"polygons",
")",
")",
"polygonConnectsM",
"=",
"convertToMIntArray",
"(",
"polygonConnects",
")",
"# Determine parent",
"if",
"parent",
"==",
"None",
":",
"parentM",
"=",
"om",
".",
"MObject",
"(",
")",
"else",
":",
"parentM",
"=",
"getDagPath",
"(",
"parent",
")",
".",
"node",
"(",
")",
"# Create Mesh",
"newMesh",
"=",
"om",
".",
"MFnMesh",
"(",
")",
"newTransformOrShape",
"=",
"newMesh",
".",
"create",
"(",
"numVertices",
",",
"numPolygons",
",",
"verticesM",
",",
"polygonCountsM",
",",
"polygonConnectsM",
",",
"parentM",
")",
"dagpath",
"=",
"om",
".",
"MDagPath",
"(",
")",
"om",
".",
"MDagPath",
".",
"getAPathTo",
"(",
"newTransformOrShape",
",",
"dagpath",
")",
"# Assign the default shader to the mesh.",
"cmds",
".",
"sets",
"(",
"dagpath",
".",
"fullPathName",
"(",
")",
",",
"edit",
"=",
"True",
",",
"forceElement",
"=",
"'initialShadingGroup'",
")",
"return",
"dagpath",
".",
"partialPathName",
"(",
")"
] |
https://github.com/PixarAnimationStudios/OpenSubdiv/blob/ff76e0f2dc9c9202b7d2f965f264bfd6f41866d5/regression/far_regression/example_createMesh.py#L70-L114
|
|
apple/swift-lldb
|
d74be846ef3e62de946df343e8c234bde93a8912
|
scripts/Python/static-binding/lldb.py
|
python
|
SBThread.Suspend
|
(self, *args)
|
return _lldb.SBThread_Suspend(self, *args)
|
Suspend(SBThread self) -> bool
Suspend(SBThread self, SBError error) -> bool
LLDB currently supports process centric debugging which means when any
thread in a process stops, all other threads are stopped. The Suspend()
call here tells our process to suspend a thread and not let it run when
the other threads in a process are allowed to run. So when
SBProcess::Continue() is called, any threads that aren't suspended will
be allowed to run. If any of the SBThread functions for stepping are
called (StepOver, StepInto, StepOut, StepInstruction, RunToAddres), the
thread will now be allowed to run and these functions will simply return.
Eventually we plan to add support for thread centric debugging where
each thread is controlled individually and each thread would broadcast
its state, but we haven't implemented this yet.
Likewise the SBThread::Resume() call will again allow the thread to run
when the process is continued.
Suspend() and Resume() functions are not currently reference counted, if
anyone has the need for them to be reference counted, please let us
know.
|
Suspend(SBThread self) -> bool
Suspend(SBThread self, SBError error) -> bool
|
[
"Suspend",
"(",
"SBThread",
"self",
")",
"-",
">",
"bool",
"Suspend",
"(",
"SBThread",
"self",
"SBError",
"error",
")",
"-",
">",
"bool"
] |
def Suspend(self, *args):
"""
Suspend(SBThread self) -> bool
Suspend(SBThread self, SBError error) -> bool
LLDB currently supports process centric debugging which means when any
thread in a process stops, all other threads are stopped. The Suspend()
call here tells our process to suspend a thread and not let it run when
the other threads in a process are allowed to run. So when
SBProcess::Continue() is called, any threads that aren't suspended will
be allowed to run. If any of the SBThread functions for stepping are
called (StepOver, StepInto, StepOut, StepInstruction, RunToAddres), the
thread will now be allowed to run and these functions will simply return.
Eventually we plan to add support for thread centric debugging where
each thread is controlled individually and each thread would broadcast
its state, but we haven't implemented this yet.
Likewise the SBThread::Resume() call will again allow the thread to run
when the process is continued.
Suspend() and Resume() functions are not currently reference counted, if
anyone has the need for them to be reference counted, please let us
know.
"""
return _lldb.SBThread_Suspend(self, *args)
|
[
"def",
"Suspend",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBThread_Suspend",
"(",
"self",
",",
"*",
"args",
")"
] |
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L11783-L11809
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_gdi.py
|
python
|
PseudoDC.DrawRotatedTextPoint
|
(*args, **kwargs)
|
return _gdi_.PseudoDC_DrawRotatedTextPoint(*args, **kwargs)
|
DrawRotatedTextPoint(self, String text, Point pt, double angle)
Draws the text rotated by *angle* degrees, if supported by the platform.
**NOTE**: Under Win9x only TrueType fonts can be drawn by this
function. In particular, a font different from ``wx.NORMAL_FONT``
should be used as the it is not normally a TrueType
font. ``wx.SWISS_FONT`` is an example of a font which is.
|
DrawRotatedTextPoint(self, String text, Point pt, double angle)
|
[
"DrawRotatedTextPoint",
"(",
"self",
"String",
"text",
"Point",
"pt",
"double",
"angle",
")"
] |
def DrawRotatedTextPoint(*args, **kwargs):
"""
DrawRotatedTextPoint(self, String text, Point pt, double angle)
Draws the text rotated by *angle* degrees, if supported by the platform.
**NOTE**: Under Win9x only TrueType fonts can be drawn by this
function. In particular, a font different from ``wx.NORMAL_FONT``
should be used as the it is not normally a TrueType
font. ``wx.SWISS_FONT`` is an example of a font which is.
"""
return _gdi_.PseudoDC_DrawRotatedTextPoint(*args, **kwargs)
|
[
"def",
"DrawRotatedTextPoint",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"PseudoDC_DrawRotatedTextPoint",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L8136-L8147
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/joblib/joblib/parallel.py
|
python
|
effective_n_jobs
|
(n_jobs=-1)
|
return backend.effective_n_jobs(n_jobs=n_jobs)
|
Determine the number of jobs that can actually run in parallel
n_jobs is the number of workers requested by the callers. Passing n_jobs=-1
means requesting all available workers for instance matching the number of
CPU cores on the worker host(s).
This method should return a guesstimate of the number of workers that can
actually perform work concurrently with the currently enabled default
backend. The primary use case is to make it possible for the caller to know
in how many chunks to slice the work.
In general working on larger data chunks is more efficient (less scheduling
overhead and better use of CPU cache prefetching heuristics) as long as all
the workers have enough work to do.
Warning: this function is experimental and subject to change in a future
version of joblib.
.. versionadded:: 0.10
|
Determine the number of jobs that can actually run in parallel
|
[
"Determine",
"the",
"number",
"of",
"jobs",
"that",
"can",
"actually",
"run",
"in",
"parallel"
] |
def effective_n_jobs(n_jobs=-1):
"""Determine the number of jobs that can actually run in parallel
n_jobs is the number of workers requested by the callers. Passing n_jobs=-1
means requesting all available workers for instance matching the number of
CPU cores on the worker host(s).
This method should return a guesstimate of the number of workers that can
actually perform work concurrently with the currently enabled default
backend. The primary use case is to make it possible for the caller to know
in how many chunks to slice the work.
In general working on larger data chunks is more efficient (less scheduling
overhead and better use of CPU cache prefetching heuristics) as long as all
the workers have enough work to do.
Warning: this function is experimental and subject to change in a future
version of joblib.
.. versionadded:: 0.10
"""
backend, backend_n_jobs = get_active_backend()
if n_jobs is None:
n_jobs = backend_n_jobs
return backend.effective_n_jobs(n_jobs=n_jobs)
|
[
"def",
"effective_n_jobs",
"(",
"n_jobs",
"=",
"-",
"1",
")",
":",
"backend",
",",
"backend_n_jobs",
"=",
"get_active_backend",
"(",
")",
"if",
"n_jobs",
"is",
"None",
":",
"n_jobs",
"=",
"backend_n_jobs",
"return",
"backend",
".",
"effective_n_jobs",
"(",
"n_jobs",
"=",
"n_jobs",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/parallel.py#L385-L410
|
|
apache/incubator-mxnet
|
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
|
python/mxnet/numpy/multiarray.py
|
python
|
prod
|
(a, axis=None, dtype=None, out=None, keepdims=False, initial=None)
|
return _mx_nd_np.prod(a, axis=axis, dtype=dtype, keepdims=keepdims, initial=initial, out=out)
|
Return the product of array elements over a given axis.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
Axis or axes along which a product is performed. The default,
axis=None, will calculate the product of all the elements in the
input array. If axis is negative it counts from the last to the
first axis.
.. versionadded:: 1.7.0
If axis is a tuple of ints, a product is performed on all of the
axes specified in the tuple instead of a single axis or all the
axes as before.
dtype : dtype, optional
The type of the returned array, as well as of the accumulator in
which the elements are multiplied. The dtype of `a` is used by
default unless `a` has an integer dtype of less precision than the
default platform integer. In that case, if `a` is signed then the
platform integer is used while if `a` is unsigned then an unsigned
integer of the same precision as the platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output, but the type of the output
values will be cast if necessary.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in the
result as dimensions with size one. With this option, the result
will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `prod` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
initial : scalar, optional
The starting value for this product. See `~numpy.ufunc.reduce` for details.
where : not supported
Returns
-------
product_along_axis : ndarray, see `dtype` parameter above.
An array shaped as `a` but with the specified axis removed.
Returns a reference to `out` if specified.
Examples
--------
By default, calculate the product of all elements:
>>> np.prod([1.,2.])
2.0
Even when the input array is two-dimensional:
>>> np.prod([[1.,2.],[3.,4.]])
24.0
But we can also specify the axis over which to multiply:
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
Or select specific elements to include:
>>> np.prod([1., np.nan, 3.], where=[True, False, True])
3.0
If the type of `x` is unsigned, then the output type is
the unsigned platform integer:
>>> x = np.array([1, 2, 3], dtype=np.uint8)
>>> np.prod(x).dtype == np.uint
True
If `x` is of a signed integer type, then the output type
is the default platform integer:
>>> x = np.array([1, 2, 3], dtype=np.int8)
>>> np.prod(x).dtype == int
True
You can also start the product with a value other than one:
>>> np.prod([1, 2], initial=5)
10
|
Return the product of array elements over a given axis.
|
[
"Return",
"the",
"product",
"of",
"array",
"elements",
"over",
"a",
"given",
"axis",
"."
] |
def prod(a, axis=None, dtype=None, out=None, keepdims=False, initial=None): # pylint: disable=too-many-arguments
"""
Return the product of array elements over a given axis.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
Axis or axes along which a product is performed. The default,
axis=None, will calculate the product of all the elements in the
input array. If axis is negative it counts from the last to the
first axis.
.. versionadded:: 1.7.0
If axis is a tuple of ints, a product is performed on all of the
axes specified in the tuple instead of a single axis or all the
axes as before.
dtype : dtype, optional
The type of the returned array, as well as of the accumulator in
which the elements are multiplied. The dtype of `a` is used by
default unless `a` has an integer dtype of less precision than the
default platform integer. In that case, if `a` is signed then the
platform integer is used while if `a` is unsigned then an unsigned
integer of the same precision as the platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output, but the type of the output
values will be cast if necessary.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in the
result as dimensions with size one. With this option, the result
will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `prod` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
initial : scalar, optional
The starting value for this product. See `~numpy.ufunc.reduce` for details.
where : not supported
Returns
-------
product_along_axis : ndarray, see `dtype` parameter above.
An array shaped as `a` but with the specified axis removed.
Returns a reference to `out` if specified.
Examples
--------
By default, calculate the product of all elements:
>>> np.prod([1.,2.])
2.0
Even when the input array is two-dimensional:
>>> np.prod([[1.,2.],[3.,4.]])
24.0
But we can also specify the axis over which to multiply:
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
Or select specific elements to include:
>>> np.prod([1., np.nan, 3.], where=[True, False, True])
3.0
If the type of `x` is unsigned, then the output type is
the unsigned platform integer:
>>> x = np.array([1, 2, 3], dtype=np.uint8)
>>> np.prod(x).dtype == np.uint
True
If `x` is of a signed integer type, then the output type
is the default platform integer:
>>> x = np.array([1, 2, 3], dtype=np.int8)
>>> np.prod(x).dtype == int
True
You can also start the product with a value other than one:
>>> np.prod([1, 2], initial=5)
10
"""
return _mx_nd_np.prod(a, axis=axis, dtype=dtype, keepdims=keepdims, initial=initial, out=out)
|
[
"def",
"prod",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"keepdims",
"=",
"False",
",",
"initial",
"=",
"None",
")",
":",
"# pylint: disable=too-many-arguments",
"return",
"_mx_nd_np",
".",
"prod",
"(",
"a",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"dtype",
",",
"keepdims",
"=",
"keepdims",
",",
"initial",
"=",
"initial",
",",
"out",
"=",
"out",
")"
] |
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L12634-L12709
|
|
TGAC/KAT
|
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
|
deps/boost/tools/build/src/build/virtual_target.py
|
python
|
VirtualTargetRegistry.recent_targets
|
(self)
|
return self.recent_targets_
|
Each target returned by 'register' is added to a list of
'recent-target', returned by this function. So, this allows
us to find all targets created when building a given main
target, even if the target.
|
Each target returned by 'register' is added to a list of
'recent-target', returned by this function. So, this allows
us to find all targets created when building a given main
target, even if the target.
|
[
"Each",
"target",
"returned",
"by",
"register",
"is",
"added",
"to",
"a",
"list",
"of",
"recent",
"-",
"target",
"returned",
"by",
"this",
"function",
".",
"So",
"this",
"allows",
"us",
"to",
"find",
"all",
"targets",
"created",
"when",
"building",
"a",
"given",
"main",
"target",
"even",
"if",
"the",
"target",
"."
] |
def recent_targets(self):
"""Each target returned by 'register' is added to a list of
'recent-target', returned by this function. So, this allows
us to find all targets created when building a given main
target, even if the target."""
return self.recent_targets_
|
[
"def",
"recent_targets",
"(",
"self",
")",
":",
"return",
"self",
".",
"recent_targets_"
] |
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/virtual_target.py#L180-L186
|
|
ApolloAuto/apollo-platform
|
86d9dc6743b496ead18d597748ebabd34a513289
|
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/shape_base.py
|
python
|
get_array_prepare
|
(*args)
|
return None
|
Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
|
Find the wrapper for the array with the highest priority.
|
[
"Find",
"the",
"wrapper",
"for",
"the",
"array",
"with",
"the",
"highest",
"priority",
"."
] |
def get_array_prepare(*args):
"""Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
"""
wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
x.__array_prepare__) for i, x in enumerate(args)
if hasattr(x, '__array_prepare__'))
if wrappers:
return wrappers[-1][-1]
return None
|
[
"def",
"get_array_prepare",
"(",
"*",
"args",
")",
":",
"wrappers",
"=",
"sorted",
"(",
"(",
"getattr",
"(",
"x",
",",
"'__array_priority__'",
",",
"0",
")",
",",
"-",
"i",
",",
"x",
".",
"__array_prepare__",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"args",
")",
"if",
"hasattr",
"(",
"x",
",",
"'__array_prepare__'",
")",
")",
"if",
"wrappers",
":",
"return",
"wrappers",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"return",
"None"
] |
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/shape_base.py#L638-L648
|
|
miyosuda/TensorFlowAndroidDemo
|
35903e0221aa5f109ea2dbef27f20b52e317f42d
|
jni-build/jni/include/tensorflow/python/client/timeline.py
|
python
|
_TensorTracker.object_id
|
(self)
|
return self._object_id
|
Returns the object identifier of this tensor (integer).
|
Returns the object identifier of this tensor (integer).
|
[
"Returns",
"the",
"object",
"identifier",
"of",
"this",
"tensor",
"(",
"integer",
")",
"."
] |
def object_id(self):
"""Returns the object identifier of this tensor (integer)."""
return self._object_id
|
[
"def",
"object_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_object_id"
] |
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/client/timeline.py#L311-L313
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py
|
python
|
_split_optional_netmask
|
(address)
|
return addr
|
Helper to split the netmask and raise AddressValueError if needed
|
Helper to split the netmask and raise AddressValueError if needed
|
[
"Helper",
"to",
"split",
"the",
"netmask",
"and",
"raise",
"AddressValueError",
"if",
"needed"
] |
def _split_optional_netmask(address):
"""Helper to split the netmask and raise AddressValueError if needed"""
addr = str(address).split('/')
if len(addr) > 2:
raise AddressValueError("Only one '/' permitted in %r" % address)
return addr
|
[
"def",
"_split_optional_netmask",
"(",
"address",
")",
":",
"addr",
"=",
"str",
"(",
"address",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"addr",
")",
">",
"2",
":",
"raise",
"AddressValueError",
"(",
"\"Only one '/' permitted in %r\"",
"%",
"address",
")",
"return",
"addr"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py#L158-L163
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ntpath.py
|
python
|
split
|
(p)
|
return d + head, tail
|
Split a pathname.
Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty.
|
Split a pathname.
|
[
"Split",
"a",
"pathname",
"."
] |
def split(p):
"""Split a pathname.
Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty."""
p = os.fspath(p)
seps = _get_bothseps(p)
d, p = splitdrive(p)
# set i to index beyond p's last slash
i = len(p)
while i and p[i-1] not in seps:
i -= 1
head, tail = p[:i], p[i:] # now tail has no slashes
# remove trailing slashes from head, unless it's all slashes
head = head.rstrip(seps) or head
return d + head, tail
|
[
"def",
"split",
"(",
"p",
")",
":",
"p",
"=",
"os",
".",
"fspath",
"(",
"p",
")",
"seps",
"=",
"_get_bothseps",
"(",
"p",
")",
"d",
",",
"p",
"=",
"splitdrive",
"(",
"p",
")",
"# set i to index beyond p's last slash",
"i",
"=",
"len",
"(",
"p",
")",
"while",
"i",
"and",
"p",
"[",
"i",
"-",
"1",
"]",
"not",
"in",
"seps",
":",
"i",
"-=",
"1",
"head",
",",
"tail",
"=",
"p",
"[",
":",
"i",
"]",
",",
"p",
"[",
"i",
":",
"]",
"# now tail has no slashes",
"# remove trailing slashes from head, unless it's all slashes",
"head",
"=",
"head",
".",
"rstrip",
"(",
"seps",
")",
"or",
"head",
"return",
"d",
"+",
"head",
",",
"tail"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ntpath.py#L178-L193
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_misc.py
|
python
|
DateSpan.__add__
|
(*args, **kwargs)
|
return _misc_.DateSpan___add__(*args, **kwargs)
|
__add__(self, DateSpan other) -> DateSpan
|
__add__(self, DateSpan other) -> DateSpan
|
[
"__add__",
"(",
"self",
"DateSpan",
"other",
")",
"-",
">",
"DateSpan"
] |
def __add__(*args, **kwargs):
"""__add__(self, DateSpan other) -> DateSpan"""
return _misc_.DateSpan___add__(*args, **kwargs)
|
[
"def",
"__add__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan___add__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4721-L4723
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/easy_install.py
|
python
|
get_win_launcher
|
(type)
|
return resource_string('setuptools', launcher_fn)
|
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
Returns the executable as a byte string.
|
Load the Windows launcher (executable) suitable for launching a script.
|
[
"Load",
"the",
"Windows",
"launcher",
"(",
"executable",
")",
"suitable",
"for",
"launching",
"a",
"script",
"."
] |
def get_win_launcher(type):
"""
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
Returns the executable as a byte string.
"""
launcher_fn = '%s.exe' % type
if is_64bit():
launcher_fn = launcher_fn.replace(".", "-64.")
else:
launcher_fn = launcher_fn.replace(".", "-32.")
return resource_string('setuptools', launcher_fn)
|
[
"def",
"get_win_launcher",
"(",
"type",
")",
":",
"launcher_fn",
"=",
"'%s.exe'",
"%",
"type",
"if",
"is_64bit",
"(",
")",
":",
"launcher_fn",
"=",
"launcher_fn",
".",
"replace",
"(",
"\".\"",
",",
"\"-64.\"",
")",
"else",
":",
"launcher_fn",
"=",
"launcher_fn",
".",
"replace",
"(",
"\".\"",
",",
"\"-32.\"",
")",
"return",
"resource_string",
"(",
"'setuptools'",
",",
"launcher_fn",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/easy_install.py#L2263-L2276
|
|
hakuna-m/wubiuefi
|
caec1af0a09c78fd5a345180ada1fe45e0c63493
|
src/pypack/altgraph/Graph.py
|
python
|
Graph.back_topo_sort
|
(self)
|
return self._topo_sort(forward=False)
|
Reverse topological sort.
Returns a list of nodes where the successors (based on incoming edges)
of any given node appear in the sequence after that node.
|
Reverse topological sort.
Returns a list of nodes where the successors (based on incoming edges)
of any given node appear in the sequence after that node.
|
[
"Reverse",
"topological",
"sort",
".",
"Returns",
"a",
"list",
"of",
"nodes",
"where",
"the",
"successors",
"(",
"based",
"on",
"incoming",
"edges",
")",
"of",
"any",
"given",
"node",
"appear",
"in",
"the",
"sequence",
"after",
"that",
"node",
"."
] |
def back_topo_sort(self):
"""
Reverse topological sort.
Returns a list of nodes where the successors (based on incoming edges)
of any given node appear in the sequence after that node.
"""
return self._topo_sort(forward=False)
|
[
"def",
"back_topo_sort",
"(",
"self",
")",
":",
"return",
"self",
".",
"_topo_sort",
"(",
"forward",
"=",
"False",
")"
] |
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/altgraph/Graph.py#L410-L416
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/grid.py
|
python
|
Grid.DisableDragColMove
|
(*args, **kwargs)
|
return _grid.Grid_DisableDragColMove(*args, **kwargs)
|
DisableDragColMove(self)
|
DisableDragColMove(self)
|
[
"DisableDragColMove",
"(",
"self",
")"
] |
def DisableDragColMove(*args, **kwargs):
"""DisableDragColMove(self)"""
return _grid.Grid_DisableDragColMove(*args, **kwargs)
|
[
"def",
"DisableDragColMove",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_DisableDragColMove",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1634-L1636
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/setuptools/py2/setuptools/command/egg_info.py
|
python
|
manifest_maker.write_manifest
|
(self)
|
Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.
|
Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.
|
[
"Write",
"the",
"file",
"list",
"in",
"self",
".",
"filelist",
"to",
"the",
"manifest",
"file",
"named",
"by",
"self",
".",
"manifest",
"."
] |
def write_manifest(self):
"""
Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.
"""
self.filelist._repair()
# Now _repairs should encodability, but not unicode
files = [self._manifest_normalize(f) for f in self.filelist.files]
msg = "writing manifest file '%s'" % self.manifest
self.execute(write_file, (self.manifest, files), msg)
|
[
"def",
"write_manifest",
"(",
"self",
")",
":",
"self",
".",
"filelist",
".",
"_repair",
"(",
")",
"# Now _repairs should encodability, but not unicode",
"files",
"=",
"[",
"self",
".",
"_manifest_normalize",
"(",
"f",
")",
"for",
"f",
"in",
"self",
".",
"filelist",
".",
"files",
"]",
"msg",
"=",
"\"writing manifest file '%s'\"",
"%",
"self",
".",
"manifest",
"self",
".",
"execute",
"(",
"write_file",
",",
"(",
"self",
".",
"manifest",
",",
"files",
")",
",",
"msg",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/command/egg_info.py#L546-L556
|
||
Tencent/CMONGO
|
c40380caa14e05509f46993aa8b8da966b09b0b5
|
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/PathList.py
|
python
|
PathListCache.PathList
|
(self, pathlist)
|
return result
|
Returns the cached _PathList object for the specified pathlist,
creating and caching a new object as necessary.
|
Returns the cached _PathList object for the specified pathlist,
creating and caching a new object as necessary.
|
[
"Returns",
"the",
"cached",
"_PathList",
"object",
"for",
"the",
"specified",
"pathlist",
"creating",
"and",
"caching",
"a",
"new",
"object",
"as",
"necessary",
"."
] |
def PathList(self, pathlist):
"""
Returns the cached _PathList object for the specified pathlist,
creating and caching a new object as necessary.
"""
pathlist = self._PathList_key(pathlist)
try:
memo_dict = self._memo['PathList']
except KeyError:
memo_dict = {}
self._memo['PathList'] = memo_dict
else:
try:
return memo_dict[pathlist]
except KeyError:
pass
result = _PathList(pathlist)
memo_dict[pathlist] = result
return result
|
[
"def",
"PathList",
"(",
"self",
",",
"pathlist",
")",
":",
"pathlist",
"=",
"self",
".",
"_PathList_key",
"(",
"pathlist",
")",
"try",
":",
"memo_dict",
"=",
"self",
".",
"_memo",
"[",
"'PathList'",
"]",
"except",
"KeyError",
":",
"memo_dict",
"=",
"{",
"}",
"self",
".",
"_memo",
"[",
"'PathList'",
"]",
"=",
"memo_dict",
"else",
":",
"try",
":",
"return",
"memo_dict",
"[",
"pathlist",
"]",
"except",
"KeyError",
":",
"pass",
"result",
"=",
"_PathList",
"(",
"pathlist",
")",
"memo_dict",
"[",
"pathlist",
"]",
"=",
"result",
"return",
"result"
] |
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/PathList.py#L195-L216
|
|
miyosuda/TensorFlowAndroidDemo
|
35903e0221aa5f109ea2dbef27f20b52e317f42d
|
jni-build/jni/include/tensorflow/python/ops/linalg_grad.py
|
python
|
_BatchMatrixTriangularSolveGrad
|
(op, grad)
|
return (grad_a, grad_b)
|
Gradient for BatchMatrixTriangularSolve.
|
Gradient for BatchMatrixTriangularSolve.
|
[
"Gradient",
"for",
"BatchMatrixTriangularSolve",
"."
] |
def _BatchMatrixTriangularSolveGrad(op, grad):
"""Gradient for BatchMatrixTriangularSolve."""
a = op.inputs[0]
adjoint_a = op.get_attr("adjoint")
lower_a = op.get_attr("lower")
c = op.outputs[0]
grad_b = linalg_ops.batch_matrix_triangular_solve(a,
grad,
lower=lower_a,
adjoint=not adjoint_a)
if adjoint_a:
grad_a = -math_ops.batch_matmul(c, grad_b, adj_y=True)
else:
grad_a = -math_ops.batch_matmul(grad_b, c, adj_y=True)
if lower_a:
grad_a = array_ops.batch_matrix_band_part(grad_a, -1, 0)
else:
grad_a = array_ops.batch_matrix_band_part(grad_a, 0, -1)
return (grad_a, grad_b)
|
[
"def",
"_BatchMatrixTriangularSolveGrad",
"(",
"op",
",",
"grad",
")",
":",
"a",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"adjoint_a",
"=",
"op",
".",
"get_attr",
"(",
"\"adjoint\"",
")",
"lower_a",
"=",
"op",
".",
"get_attr",
"(",
"\"lower\"",
")",
"c",
"=",
"op",
".",
"outputs",
"[",
"0",
"]",
"grad_b",
"=",
"linalg_ops",
".",
"batch_matrix_triangular_solve",
"(",
"a",
",",
"grad",
",",
"lower",
"=",
"lower_a",
",",
"adjoint",
"=",
"not",
"adjoint_a",
")",
"if",
"adjoint_a",
":",
"grad_a",
"=",
"-",
"math_ops",
".",
"batch_matmul",
"(",
"c",
",",
"grad_b",
",",
"adj_y",
"=",
"True",
")",
"else",
":",
"grad_a",
"=",
"-",
"math_ops",
".",
"batch_matmul",
"(",
"grad_b",
",",
"c",
",",
"adj_y",
"=",
"True",
")",
"if",
"lower_a",
":",
"grad_a",
"=",
"array_ops",
".",
"batch_matrix_band_part",
"(",
"grad_a",
",",
"-",
"1",
",",
"0",
")",
"else",
":",
"grad_a",
"=",
"array_ops",
".",
"batch_matrix_band_part",
"(",
"grad_a",
",",
"0",
",",
"-",
"1",
")",
"return",
"(",
"grad_a",
",",
"grad_b",
")"
] |
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/linalg_grad.py#L148-L166
|
|
Polidea/SiriusObfuscator
|
b0e590d8130e97856afe578869b83a209e2b19be
|
SymbolExtractorAndRenamer/llvm/bindings/python/llvm/disassembler.py
|
python
|
Disassembler.get_instruction
|
(self, source, pc=0)
|
return (result, out_str.value)
|
Obtain the next instruction from an input source.
The input source should be a str or bytearray or something that
represents a sequence of bytes.
This function will start reading bytes from the beginning of the
source.
The pc argument specifies the address that the first byte is at.
This returns a 2-tuple of:
long number of bytes read. 0 if no instruction was read.
str representation of instruction. This will be the assembly that
represents the instruction.
|
Obtain the next instruction from an input source.
|
[
"Obtain",
"the",
"next",
"instruction",
"from",
"an",
"input",
"source",
"."
] |
def get_instruction(self, source, pc=0):
"""Obtain the next instruction from an input source.
The input source should be a str or bytearray or something that
represents a sequence of bytes.
This function will start reading bytes from the beginning of the
source.
The pc argument specifies the address that the first byte is at.
This returns a 2-tuple of:
long number of bytes read. 0 if no instruction was read.
str representation of instruction. This will be the assembly that
represents the instruction.
"""
buf = cast(c_char_p(source), POINTER(c_ubyte))
out_str = cast((c_byte * 255)(), c_char_p)
result = lib.LLVMDisasmInstruction(self, buf, c_uint64(len(source)),
c_uint64(pc), out_str, 255)
return (result, out_str.value)
|
[
"def",
"get_instruction",
"(",
"self",
",",
"source",
",",
"pc",
"=",
"0",
")",
":",
"buf",
"=",
"cast",
"(",
"c_char_p",
"(",
"source",
")",
",",
"POINTER",
"(",
"c_ubyte",
")",
")",
"out_str",
"=",
"cast",
"(",
"(",
"c_byte",
"*",
"255",
")",
"(",
")",
",",
"c_char_p",
")",
"result",
"=",
"lib",
".",
"LLVMDisasmInstruction",
"(",
"self",
",",
"buf",
",",
"c_uint64",
"(",
"len",
"(",
"source",
")",
")",
",",
"c_uint64",
"(",
"pc",
")",
",",
"out_str",
",",
"255",
")",
"return",
"(",
"result",
",",
"out_str",
".",
"value",
")"
] |
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/llvm/bindings/python/llvm/disassembler.py#L84-L107
|
|
idaholab/moose
|
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
|
python/pyhit/pyhit.py
|
python
|
Node.format
|
(self, **kwargs)
|
return self.render()
|
Return a string of the node that is rendered with C hit library with formatting.
An optional keyword argument *canonical_section_markers* can be supplied with `True` or
`False` to enable/disable the use of "./" and "../" section markings. By default these
markings this are removed.
|
Return a string of the node that is rendered with C hit library with formatting.
|
[
"Return",
"a",
"string",
"of",
"the",
"node",
"that",
"is",
"rendered",
"with",
"C",
"hit",
"library",
"with",
"formatting",
"."
] |
def format(self, **kwargs):
"""
Return a string of the node that is rendered with C hit library with formatting.
An optional keyword argument *canonical_section_markers* can be supplied with `True` or
`False` to enable/disable the use of "./" and "../" section markings. By default these
markings this are removed.
"""
formatter = hit.Formatter()
formatter.config(**kwargs)
formatter.formatTree(self.__hitnode)
return self.render()
|
[
"def",
"format",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"formatter",
"=",
"hit",
".",
"Formatter",
"(",
")",
"formatter",
".",
"config",
"(",
"*",
"*",
"kwargs",
")",
"formatter",
".",
"formatTree",
"(",
"self",
".",
"__hitnode",
")",
"return",
"self",
".",
"render",
"(",
")"
] |
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/pyhit/pyhit.py#L155-L166
|
|
zyq8709/DexHunter
|
9d829a9f6f608ebad26923f29a294ae9c68d0441
|
art/tools/cpplint.py
|
python
|
_NestingState.CheckClassFinished
|
(self, filename, error)
|
Checks that all classes have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
|
Checks that all classes have been completely parsed.
|
[
"Checks",
"that",
"all",
"classes",
"have",
"been",
"completely",
"parsed",
"."
] |
def CheckClassFinished(self, filename, error):
"""Checks that all classes have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
"""
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
|
[
"def",
"CheckClassFinished",
"(",
"self",
",",
"filename",
",",
"error",
")",
":",
"# Note: This test can result in false positives if #ifdef constructs",
"# get in the way of brace matching. See the testBuildClass test in",
"# cpplint_unittest.py for an example of this.",
"for",
"obj",
"in",
"self",
".",
"stack",
":",
"if",
"isinstance",
"(",
"obj",
",",
"_ClassInfo",
")",
":",
"error",
"(",
"filename",
",",
"obj",
".",
"starting_linenum",
",",
"'build/class'",
",",
"5",
",",
"'Failed to find complete declaration of class %s'",
"%",
"obj",
".",
"name",
")"
] |
https://github.com/zyq8709/DexHunter/blob/9d829a9f6f608ebad26923f29a294ae9c68d0441/art/tools/cpplint.py#L1739-L1754
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/stc.py
|
python
|
StyledTextCtrl.StyleGetWeight
|
(*args, **kwargs)
|
return _stc.StyledTextCtrl_StyleGetWeight(*args, **kwargs)
|
StyleGetWeight(self, int style) -> int
|
StyleGetWeight(self, int style) -> int
|
[
"StyleGetWeight",
"(",
"self",
"int",
"style",
")",
"-",
">",
"int"
] |
def StyleGetWeight(*args, **kwargs):
"""StyleGetWeight(self, int style) -> int"""
return _stc.StyledTextCtrl_StyleGetWeight(*args, **kwargs)
|
[
"def",
"StyleGetWeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_StyleGetWeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2711-L2713
|
|
ricardoquesada/Spidermonkey
|
4a75ea2543408bd1b2c515aa95901523eeef7858
|
ipc/ipdl/ipdl/lower.py
|
python
|
_UnionMember.constptrToSelfExpr
|
(self)
|
return ExprCast(ExprAddrOf(v), self.constPtrToType(), reinterpret=1)
|
|*constptrToSelfExpr()| has type |self.constType()|
|
|*constptrToSelfExpr()| has type |self.constType()|
|
[
"|",
"*",
"constptrToSelfExpr",
"()",
"|",
"has",
"type",
"|self",
".",
"constType",
"()",
"|"
] |
def constptrToSelfExpr(self):
"""|*constptrToSelfExpr()| has type |self.constType()|"""
v = self.unionValue()
if self.recursive:
return v
return ExprCast(ExprAddrOf(v), self.constPtrToType(), reinterpret=1)
|
[
"def",
"constptrToSelfExpr",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"unionValue",
"(",
")",
"if",
"self",
".",
"recursive",
":",
"return",
"v",
"return",
"ExprCast",
"(",
"ExprAddrOf",
"(",
"v",
")",
",",
"self",
".",
"constPtrToType",
"(",
")",
",",
"reinterpret",
"=",
"1",
")"
] |
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/ipc/ipdl/ipdl/lower.py#L839-L844
|
|
vusec/vuzzer64
|
2b1b0ed757a3dca114db0192fa4ab1add92348bc
|
fuzzer-code/gautils.py
|
python
|
fitnesCal2
|
(bbdict, cinput,ilen)
|
calculates fitness of each input based on its execution trace. The difference from "fitnesCal()" is that it again multiplies fitnes score by the number of BB executed.
|
calculates fitness of each input based on its execution trace. The difference from "fitnesCal()" is that it again multiplies fitnes score by the number of BB executed.
|
[
"calculates",
"fitness",
"of",
"each",
"input",
"based",
"on",
"its",
"execution",
"trace",
".",
"The",
"difference",
"from",
"fitnesCal",
"()",
"is",
"that",
"it",
"again",
"multiplies",
"fitnes",
"score",
"by",
"the",
"number",
"of",
"BB",
"executed",
"."
] |
def fitnesCal2(bbdict, cinput,ilen):
'''
calculates fitness of each input based on its execution trace. The difference from "fitnesCal()" is that it again multiplies fitnes score by the number of BB executed.
'''
config.GOTSPECIAL=False
score=0.0
bbNum=0
tempset=config.ERRORBBALL.union(config.TEMPERRORBB)
# calculate negative weight for error BBs
numEBB=len(set(bbdict)&tempset)
if numEBB>0:
ew=-len(bbdict)*config.ERRORBBPERCENTAGE/numEBB
tset=set(bbdict)-tempset # we make sure that newly discovered BBs are not related to error BB.
config.cPERGENBB.update(tset)
if not tset <=config.SEENBB:# and not tset <=tempset:
diffb=tset-config.SEENBB
#let input pruning, lets set the flag is this input has found a new BB
config.GOTSPECIAL=True
config.SEENBB.update(diffb)
for bbadr in bbdict:
#config.cPERGENBB.add(bbadr)#added for code-coverage
#if bbadr in tempset:#config.ERRORBBALL:
# continue
#bbNum +=1
bbfr=bbdict[bbadr]
if bbfr > config.BBMAXFREQ:
bbfr = config.BBMAXFREQ
lgfr=int(math.log(bbfr+1,2)) #1 is added to avoid having log(1)=0 case
#if bbadr not in config.SEENBB:
# config.SEENBB.add(bbadr)
# config.SPECIALENTRY.append(cinput)
if bbadr in tempset:
#print"[0x%x] Error BB hit (%f ) !"%(bbadr,ew)
score=score+(lgfr*ew)
elif bbadr in config.ALLBB:
#print"[0x%x] BB hit (%d - %f) !"%(bbadr,bbfr,config.ALLBB[bbadr])
score=score+(lgfr*config.ALLBB[bbadr])
bbNum +=1
else:
#print"[0x%x] BB missed (%d) !"%(bbadr,bbfr)
score = score+lgfr
bbNum +=1
del tempset
#print "BBNum", bbNum
#return round((score*bbNum)/(ilen*1.0),2)
#return (score*bbNum)/totalFreq
if ilen > config.MAXINPUTLEN:
return (score*bbNum)/int(math.log(ilen+1,2))
else:
return score*bbNum
|
[
"def",
"fitnesCal2",
"(",
"bbdict",
",",
"cinput",
",",
"ilen",
")",
":",
"config",
".",
"GOTSPECIAL",
"=",
"False",
"score",
"=",
"0.0",
"bbNum",
"=",
"0",
"tempset",
"=",
"config",
".",
"ERRORBBALL",
".",
"union",
"(",
"config",
".",
"TEMPERRORBB",
")",
"# calculate negative weight for error BBs",
"numEBB",
"=",
"len",
"(",
"set",
"(",
"bbdict",
")",
"&",
"tempset",
")",
"if",
"numEBB",
">",
"0",
":",
"ew",
"=",
"-",
"len",
"(",
"bbdict",
")",
"*",
"config",
".",
"ERRORBBPERCENTAGE",
"/",
"numEBB",
"tset",
"=",
"set",
"(",
"bbdict",
")",
"-",
"tempset",
"# we make sure that newly discovered BBs are not related to error BB.",
"config",
".",
"cPERGENBB",
".",
"update",
"(",
"tset",
")",
"if",
"not",
"tset",
"<=",
"config",
".",
"SEENBB",
":",
"# and not tset <=tempset:",
"diffb",
"=",
"tset",
"-",
"config",
".",
"SEENBB",
"#let input pruning, lets set the flag is this input has found a new BB",
"config",
".",
"GOTSPECIAL",
"=",
"True",
"config",
".",
"SEENBB",
".",
"update",
"(",
"diffb",
")",
"for",
"bbadr",
"in",
"bbdict",
":",
"#config.cPERGENBB.add(bbadr)#added for code-coverage",
"#if bbadr in tempset:#config.ERRORBBALL:",
"# continue",
"#bbNum +=1",
"bbfr",
"=",
"bbdict",
"[",
"bbadr",
"]",
"if",
"bbfr",
">",
"config",
".",
"BBMAXFREQ",
":",
"bbfr",
"=",
"config",
".",
"BBMAXFREQ",
"lgfr",
"=",
"int",
"(",
"math",
".",
"log",
"(",
"bbfr",
"+",
"1",
",",
"2",
")",
")",
"#1 is added to avoid having log(1)=0 case",
"#if bbadr not in config.SEENBB:",
"# config.SEENBB.add(bbadr)",
"# config.SPECIALENTRY.append(cinput)",
"if",
"bbadr",
"in",
"tempset",
":",
"#print\"[0x%x] Error BB hit (%f ) !\"%(bbadr,ew)",
"score",
"=",
"score",
"+",
"(",
"lgfr",
"*",
"ew",
")",
"elif",
"bbadr",
"in",
"config",
".",
"ALLBB",
":",
"#print\"[0x%x] BB hit (%d - %f) !\"%(bbadr,bbfr,config.ALLBB[bbadr])",
"score",
"=",
"score",
"+",
"(",
"lgfr",
"*",
"config",
".",
"ALLBB",
"[",
"bbadr",
"]",
")",
"bbNum",
"+=",
"1",
"else",
":",
"#print\"[0x%x] BB missed (%d) !\"%(bbadr,bbfr)",
"score",
"=",
"score",
"+",
"lgfr",
"bbNum",
"+=",
"1",
"del",
"tempset",
"#print \"BBNum\", bbNum",
"#return round((score*bbNum)/(ilen*1.0),2)",
"#return (score*bbNum)/totalFreq",
"if",
"ilen",
">",
"config",
".",
"MAXINPUTLEN",
":",
"return",
"(",
"score",
"*",
"bbNum",
")",
"/",
"int",
"(",
"math",
".",
"log",
"(",
"ilen",
"+",
"1",
",",
"2",
")",
")",
"else",
":",
"return",
"score",
"*",
"bbNum"
] |
https://github.com/vusec/vuzzer64/blob/2b1b0ed757a3dca114db0192fa4ab1add92348bc/fuzzer-code/gautils.py#L426-L478
|
||
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
tools/site_compare/operators/__init__.py
|
python
|
GetOperator
|
(operator)
|
return module
|
Given an operator by name, returns its module.
Args:
operator: string describing the comparison
Returns:
module
|
Given an operator by name, returns its module.
|
[
"Given",
"an",
"operator",
"by",
"name",
"returns",
"its",
"module",
"."
] |
def GetOperator(operator):
"""Given an operator by name, returns its module.
Args:
operator: string describing the comparison
Returns:
module
"""
# TODO(jhaas): come up with a happy way of integrating multiple operators
# with different, possibly divergent and possibly convergent, operators.
module = __import__(operator, globals(), locals(), [''])
return module
|
[
"def",
"GetOperator",
"(",
"operator",
")",
":",
"# TODO(jhaas): come up with a happy way of integrating multiple operators",
"# with different, possibly divergent and possibly convergent, operators.",
"module",
"=",
"__import__",
"(",
"operator",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
",",
"[",
"''",
"]",
")",
"return",
"module"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/site_compare/operators/__init__.py#L8-L23
|
|
mongodb/mongo
|
d8ff665343ad29cf286ee2cf4a1960d29371937b
|
buildscripts/resmokelib/powercycle/lib/services.py
|
python
|
PosixService.status
|
(self)
|
return "running"
|
Return status of service. If "pids" is empty due to a `stop` call, return that the process is stopped. Otherwise only return `stopped` when the lock file is removed.
|
Return status of service. If "pids" is empty due to a `stop` call, return that the process is stopped. Otherwise only return `stopped` when the lock file is removed.
|
[
"Return",
"status",
"of",
"service",
".",
"If",
"pids",
"is",
"empty",
"due",
"to",
"a",
"stop",
"call",
"return",
"that",
"the",
"process",
"is",
"stopped",
".",
"Otherwise",
"only",
"return",
"stopped",
"when",
"the",
"lock",
"file",
"is",
"removed",
"."
] |
def status(self):
"""Return status of service. If "pids" is empty due to a `stop` call, return that the process is stopped. Otherwise only return `stopped` when the lock file is removed."""
if not self.get_pids():
return "stopped"
# Wait for the lock file to be deleted which concludes a clean shutdown.
lock_file = os.path.join(self.db_path, "mongod.lock")
if not os.path.exists(lock_file):
self.pids = []
return "stopped"
try:
if os.stat(lock_file).st_size == 0:
self.pids = []
return "stopped"
except OSError:
# The lock file was probably removed. Instead of being omnipotent with exception
# interpretation, have a follow-up call observe the file does not exist.
return "running"
return "running"
|
[
"def",
"status",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"get_pids",
"(",
")",
":",
"return",
"\"stopped\"",
"# Wait for the lock file to be deleted which concludes a clean shutdown.",
"lock_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"db_path",
",",
"\"mongod.lock\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"lock_file",
")",
":",
"self",
".",
"pids",
"=",
"[",
"]",
"return",
"\"stopped\"",
"try",
":",
"if",
"os",
".",
"stat",
"(",
"lock_file",
")",
".",
"st_size",
"==",
"0",
":",
"self",
".",
"pids",
"=",
"[",
"]",
"return",
"\"stopped\"",
"except",
"OSError",
":",
"# The lock file was probably removed. Instead of being omnipotent with exception",
"# interpretation, have a follow-up call observe the file does not exist.",
"return",
"\"running\"",
"return",
"\"running\""
] |
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/powercycle/lib/services.py#L222-L242
|
|
wisdompeak/LeetCode
|
ef729c1249ead3ead47f1a94b5eeb5958a69e152
|
Dynamic_Programming/494.Target-Sum/494.Target-Sum-DFS.py
|
python
|
Solution.findTargetSumWays
|
(self, nums, S)
|
return DFS(0,S)
|
:type nums: List[int]
:type S: int
:rtype: int
|
:type nums: List[int]
:type S: int
:rtype: int
|
[
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"type",
"S",
":",
"int",
":",
"rtype",
":",
"int"
] |
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
def DFS(i,target):
if i==len(nums): return target==0
if (i,target) in mem: return mem[(i,target)]
mem[(i,target)] = DFS(i+1,target-nums[i]) + DFS(i+1,target+nums[i])
return mem[(i,target)]
mem={}
return DFS(0,S)
|
[
"def",
"findTargetSumWays",
"(",
"self",
",",
"nums",
",",
"S",
")",
":",
"def",
"DFS",
"(",
"i",
",",
"target",
")",
":",
"if",
"i",
"==",
"len",
"(",
"nums",
")",
":",
"return",
"target",
"==",
"0",
"if",
"(",
"i",
",",
"target",
")",
"in",
"mem",
":",
"return",
"mem",
"[",
"(",
"i",
",",
"target",
")",
"]",
"mem",
"[",
"(",
"i",
",",
"target",
")",
"]",
"=",
"DFS",
"(",
"i",
"+",
"1",
",",
"target",
"-",
"nums",
"[",
"i",
"]",
")",
"+",
"DFS",
"(",
"i",
"+",
"1",
",",
"target",
"+",
"nums",
"[",
"i",
"]",
")",
"return",
"mem",
"[",
"(",
"i",
",",
"target",
")",
"]",
"mem",
"=",
"{",
"}",
"return",
"DFS",
"(",
"0",
",",
"S",
")"
] |
https://github.com/wisdompeak/LeetCode/blob/ef729c1249ead3ead47f1a94b5eeb5958a69e152/Dynamic_Programming/494.Target-Sum/494.Target-Sum-DFS.py#L2-L15
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/calendar.py
|
python
|
TextCalendar.prweek
|
(self, theweek, width)
|
Print a single week (no newline).
|
Print a single week (no newline).
|
[
"Print",
"a",
"single",
"week",
"(",
"no",
"newline",
")",
"."
] |
def prweek(self, theweek, width):
"""
Print a single week (no newline).
"""
print(self.formatweek(theweek, width), end='')
|
[
"def",
"prweek",
"(",
"self",
",",
"theweek",
",",
"width",
")",
":",
"print",
"(",
"self",
".",
"formatweek",
"(",
"theweek",
",",
"width",
")",
",",
"end",
"=",
"''",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/calendar.py#L299-L303
|
||
H-uru/Plasma
|
c2140ea046e82e9c199e257a7f2e7edb42602871
|
Scripts/Python/nb01RPSGame.py
|
python
|
nb01RPSGame._GetPlayerNameFromPlayerInfoID
|
(self, infoID)
|
Use this if the player is an age owner, but may not be in the age atm
|
Use this if the player is an age owner, but may not be in the age atm
|
[
"Use",
"this",
"if",
"the",
"player",
"is",
"an",
"age",
"owner",
"but",
"may",
"not",
"be",
"in",
"the",
"age",
"atm"
] |
def _GetPlayerNameFromPlayerInfoID(self, infoID):
"""Use this if the player is an age owner, but may not be in the age atm"""
vault = ptAgeVault()
if vault is None:
PtDebugPrint("nb01RPSGame._GetPlayerNameFromPlayerInfoID():\tAin't got no age vault!")
return None
owners = vault.getAgeInfo().getAgeOwnersFolder()
# REMEMBER: game scores use the player info ID. Therefore, we have to manually search through
# all of the child nodes
for i in owners.getChildNodeRefList():
info = i.getChild().upcastToPlayerInfoNode()
if info is None:
continue
if infoID == info.getID():
return info.playerGetName()
else:
PtDebugPrint("nb01RPSGame._GetPlayerNameFromPlayerInfoID():\tFailed to find PlayerInfo {}".format(infoID))
return ""
|
[
"def",
"_GetPlayerNameFromPlayerInfoID",
"(",
"self",
",",
"infoID",
")",
":",
"vault",
"=",
"ptAgeVault",
"(",
")",
"if",
"vault",
"is",
"None",
":",
"PtDebugPrint",
"(",
"\"nb01RPSGame._GetPlayerNameFromPlayerInfoID():\\tAin't got no age vault!\"",
")",
"return",
"None",
"owners",
"=",
"vault",
".",
"getAgeInfo",
"(",
")",
".",
"getAgeOwnersFolder",
"(",
")",
"# REMEMBER: game scores use the player info ID. Therefore, we have to manually search through",
"# all of the child nodes",
"for",
"i",
"in",
"owners",
".",
"getChildNodeRefList",
"(",
")",
":",
"info",
"=",
"i",
".",
"getChild",
"(",
")",
".",
"upcastToPlayerInfoNode",
"(",
")",
"if",
"info",
"is",
"None",
":",
"continue",
"if",
"infoID",
"==",
"info",
".",
"getID",
"(",
")",
":",
"return",
"info",
".",
"playerGetName",
"(",
")",
"else",
":",
"PtDebugPrint",
"(",
"\"nb01RPSGame._GetPlayerNameFromPlayerInfoID():\\tFailed to find PlayerInfo {}\"",
".",
"format",
"(",
"infoID",
")",
")",
"return",
"\"\""
] |
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/nb01RPSGame.py#L803-L821
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python3/src/Lib/turtle.py
|
python
|
ScrolledCanvas.onResize
|
(self, event)
|
self-explanatory
|
self-explanatory
|
[
"self",
"-",
"explanatory"
] |
def onResize(self, event):
"""self-explanatory"""
self.adjustScrolls()
|
[
"def",
"onResize",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"adjustScrolls",
"(",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L395-L397
|
||
microsoft/onnxruntime
|
f92e47e95b13a240e37caf7b36577983544f98fc
|
onnxruntime/python/tools/quantization/quantize.py
|
python
|
quantize
|
(model,
per_channel=False,
nbits=8,
quantization_mode=QuantizationMode.IntegerOps,
static=False,
force_fusions=False,
symmetric_activation=False,
symmetric_weight=False,
quantization_params=None,
nodes_to_quantize=None,
nodes_to_exclude=None,
op_types_to_quantize=[])
|
Given an onnx model, create a quantized onnx model and save it into a file
:param model: ModelProto to quantize
:param per_channel: quantize weights per channel
:param nbits: number of bits to represent quantized data. Currently only supporting 8-bit types
:param quantization_mode: Can be one of the QuantizationMode types.
IntegerOps:
the function will use integer ops. Only ConvInteger and MatMulInteger ops are supported now.
QLinearOps:
the function will use QLinear ops. Only QLinearConv and QLinearMatMul ops are supported now.
:param static:
True: The inputs/activations are quantized using static scale and zero point values
specified through quantization_params.
False: The inputs/activations are quantized using dynamic scale and zero point values
computed while running the model.
:param symmetric_activation:
True: activations are quantized into signed integers.
False: activations are quantized into unsigned integers.
:param symmetric_weight:
True: weights are quantized into signed integers.
False: weights are quantized into unsigned integers.
:param quantization_params:
Dictionary to specify the zero point and scale values for inputs to conv and matmul nodes.
Should be specified when static is set to True.
The quantization_params should be specified in the following format:
{
"input_name": [zero_point, scale]
}.
zero_point should be of type np.uint8 and scale should be of type np.float32.
example:
{
'resnet_model/Relu_1:0': [np.uint8(0), np.float32(0.019539741799235344)],
'resnet_model/Relu_2:0': [np.uint8(0), np.float32(0.011359662748873234)]
}
:param nodes_to_quantize:
List of nodes names to quantize. When this list is not None only the nodes in this list
are quantized.
example:
[
'Conv__224',
'Conv__252'
]
:param nodes_to_exclude:
List of nodes names to exclude. The nodes in this list will be excluded from quantization
when it is not None.
:param op_types_to_quantize: specify the types of operators to quantize, like ['Conv'] to quantize Conv only. It quantizes all supported operators by default.
:return: ModelProto with quantization
|
Given an onnx model, create a quantized onnx model and save it into a file
:param model: ModelProto to quantize
:param per_channel: quantize weights per channel
:param nbits: number of bits to represent quantized data. Currently only supporting 8-bit types
:param quantization_mode: Can be one of the QuantizationMode types.
IntegerOps:
the function will use integer ops. Only ConvInteger and MatMulInteger ops are supported now.
QLinearOps:
the function will use QLinear ops. Only QLinearConv and QLinearMatMul ops are supported now.
:param static:
True: The inputs/activations are quantized using static scale and zero point values
specified through quantization_params.
False: The inputs/activations are quantized using dynamic scale and zero point values
computed while running the model.
:param symmetric_activation:
True: activations are quantized into signed integers.
False: activations are quantized into unsigned integers.
:param symmetric_weight:
True: weights are quantized into signed integers.
False: weights are quantized into unsigned integers.
:param quantization_params:
Dictionary to specify the zero point and scale values for inputs to conv and matmul nodes.
Should be specified when static is set to True.
The quantization_params should be specified in the following format:
{
"input_name": [zero_point, scale]
}.
zero_point should be of type np.uint8 and scale should be of type np.float32.
example:
{
'resnet_model/Relu_1:0': [np.uint8(0), np.float32(0.019539741799235344)],
'resnet_model/Relu_2:0': [np.uint8(0), np.float32(0.011359662748873234)]
}
:param nodes_to_quantize:
List of nodes names to quantize. When this list is not None only the nodes in this list
are quantized.
example:
[
'Conv__224',
'Conv__252'
]
:param nodes_to_exclude:
List of nodes names to exclude. The nodes in this list will be excluded from quantization
when it is not None.
:param op_types_to_quantize: specify the types of operators to quantize, like ['Conv'] to quantize Conv only. It quantizes all supported operators by default.
:return: ModelProto with quantization
|
[
"Given",
"an",
"onnx",
"model",
"create",
"a",
"quantized",
"onnx",
"model",
"and",
"save",
"it",
"into",
"a",
"file",
":",
"param",
"model",
":",
"ModelProto",
"to",
"quantize",
":",
"param",
"per_channel",
":",
"quantize",
"weights",
"per",
"channel",
":",
"param",
"nbits",
":",
"number",
"of",
"bits",
"to",
"represent",
"quantized",
"data",
".",
"Currently",
"only",
"supporting",
"8",
"-",
"bit",
"types",
":",
"param",
"quantization_mode",
":",
"Can",
"be",
"one",
"of",
"the",
"QuantizationMode",
"types",
".",
"IntegerOps",
":",
"the",
"function",
"will",
"use",
"integer",
"ops",
".",
"Only",
"ConvInteger",
"and",
"MatMulInteger",
"ops",
"are",
"supported",
"now",
".",
"QLinearOps",
":",
"the",
"function",
"will",
"use",
"QLinear",
"ops",
".",
"Only",
"QLinearConv",
"and",
"QLinearMatMul",
"ops",
"are",
"supported",
"now",
".",
":",
"param",
"static",
":",
"True",
":",
"The",
"inputs",
"/",
"activations",
"are",
"quantized",
"using",
"static",
"scale",
"and",
"zero",
"point",
"values",
"specified",
"through",
"quantization_params",
".",
"False",
":",
"The",
"inputs",
"/",
"activations",
"are",
"quantized",
"using",
"dynamic",
"scale",
"and",
"zero",
"point",
"values",
"computed",
"while",
"running",
"the",
"model",
".",
":",
"param",
"symmetric_activation",
":",
"True",
":",
"activations",
"are",
"quantized",
"into",
"signed",
"integers",
".",
"False",
":",
"activations",
"are",
"quantized",
"into",
"unsigned",
"integers",
".",
":",
"param",
"symmetric_weight",
":",
"True",
":",
"weights",
"are",
"quantized",
"into",
"signed",
"integers",
".",
"False",
":",
"weights",
"are",
"quantized",
"into",
"unsigned",
"integers",
".",
":",
"param",
"quantization_params",
":",
"Dictionary",
"to",
"specify",
"the",
"zero",
"point",
"and",
"scale",
"values",
"for",
"inputs",
"to",
"conv",
"and",
"matmul",
"nodes",
".",
"Should",
"be",
"specified",
"when",
"static",
"is",
"set",
"to",
"True",
".",
"The",
"quantization_params",
"should",
"be",
"specified",
"in",
"the",
"following",
"format",
":",
"{",
"input_name",
":",
"[",
"zero_point",
"scale",
"]",
"}",
".",
"zero_point",
"should",
"be",
"of",
"type",
"np",
".",
"uint8",
"and",
"scale",
"should",
"be",
"of",
"type",
"np",
".",
"float32",
".",
"example",
":",
"{",
"resnet_model",
"/",
"Relu_1",
":",
"0",
":",
"[",
"np",
".",
"uint8",
"(",
"0",
")",
"np",
".",
"float32",
"(",
"0",
".",
"019539741799235344",
")",
"]",
"resnet_model",
"/",
"Relu_2",
":",
"0",
":",
"[",
"np",
".",
"uint8",
"(",
"0",
")",
"np",
".",
"float32",
"(",
"0",
".",
"011359662748873234",
")",
"]",
"}",
":",
"param",
"nodes_to_quantize",
":",
"List",
"of",
"nodes",
"names",
"to",
"quantize",
".",
"When",
"this",
"list",
"is",
"not",
"None",
"only",
"the",
"nodes",
"in",
"this",
"list",
"are",
"quantized",
".",
"example",
":",
"[",
"Conv__224",
"Conv__252",
"]",
":",
"param",
"nodes_to_exclude",
":",
"List",
"of",
"nodes",
"names",
"to",
"exclude",
".",
"The",
"nodes",
"in",
"this",
"list",
"will",
"be",
"excluded",
"from",
"quantization",
"when",
"it",
"is",
"not",
"None",
".",
":",
"param",
"op_types_to_quantize",
":",
"specify",
"the",
"types",
"of",
"operators",
"to",
"quantize",
"like",
"[",
"Conv",
"]",
"to",
"quantize",
"Conv",
"only",
".",
"It",
"quantizes",
"all",
"supported",
"operators",
"by",
"default",
".",
":",
"return",
":",
"ModelProto",
"with",
"quantization"
] |
def quantize(model,
per_channel=False,
nbits=8,
quantization_mode=QuantizationMode.IntegerOps,
static=False,
force_fusions=False,
symmetric_activation=False,
symmetric_weight=False,
quantization_params=None,
nodes_to_quantize=None,
nodes_to_exclude=None,
op_types_to_quantize=[]):
'''
Given an onnx model, create a quantized onnx model and save it into a file
:param model: ModelProto to quantize
:param per_channel: quantize weights per channel
:param nbits: number of bits to represent quantized data. Currently only supporting 8-bit types
:param quantization_mode: Can be one of the QuantizationMode types.
IntegerOps:
the function will use integer ops. Only ConvInteger and MatMulInteger ops are supported now.
QLinearOps:
the function will use QLinear ops. Only QLinearConv and QLinearMatMul ops are supported now.
:param static:
True: The inputs/activations are quantized using static scale and zero point values
specified through quantization_params.
False: The inputs/activations are quantized using dynamic scale and zero point values
computed while running the model.
:param symmetric_activation:
True: activations are quantized into signed integers.
False: activations are quantized into unsigned integers.
:param symmetric_weight:
True: weights are quantized into signed integers.
False: weights are quantized into unsigned integers.
:param quantization_params:
Dictionary to specify the zero point and scale values for inputs to conv and matmul nodes.
Should be specified when static is set to True.
The quantization_params should be specified in the following format:
{
"input_name": [zero_point, scale]
}.
zero_point should be of type np.uint8 and scale should be of type np.float32.
example:
{
'resnet_model/Relu_1:0': [np.uint8(0), np.float32(0.019539741799235344)],
'resnet_model/Relu_2:0': [np.uint8(0), np.float32(0.011359662748873234)]
}
:param nodes_to_quantize:
List of nodes names to quantize. When this list is not None only the nodes in this list
are quantized.
example:
[
'Conv__224',
'Conv__252'
]
:param nodes_to_exclude:
List of nodes names to exclude. The nodes in this list will be excluded from quantization
when it is not None.
:param op_types_to_quantize: specify the types of operators to quantize, like ['Conv'] to quantize Conv only. It quantizes all supported operators by default.
:return: ModelProto with quantization
'''
logging.warning("onnxruntime.quantization.quantize is deprecated.\n\
Please use quantize_static for static quantization, quantize_dynamic for dynamic quantization.")
if nbits == 8 or nbits == 7:
mode = quantization_mode
copy_model = onnx_proto.ModelProto()
copy_model.CopyFrom(model)
if not op_types_to_quantize or len(op_types_to_quantize) == 0:
op_types_to_quantize = list(QLinearOpsRegistry.keys()) if static else list(IntegerOpsRegistry.keys())
quantizer = ONNXQuantizer(copy_model, per_channel, nbits == 7, mode, static, symmetric_weight,
symmetric_activation, quantization_params, nodes_to_quantize, nodes_to_exclude,
op_types_to_quantize)
quantizer.quantize_model()
return quantizer.model.model
else:
raise ValueError('Only 8 and 7 bit quantization is currently supported')
|
[
"def",
"quantize",
"(",
"model",
",",
"per_channel",
"=",
"False",
",",
"nbits",
"=",
"8",
",",
"quantization_mode",
"=",
"QuantizationMode",
".",
"IntegerOps",
",",
"static",
"=",
"False",
",",
"force_fusions",
"=",
"False",
",",
"symmetric_activation",
"=",
"False",
",",
"symmetric_weight",
"=",
"False",
",",
"quantization_params",
"=",
"None",
",",
"nodes_to_quantize",
"=",
"None",
",",
"nodes_to_exclude",
"=",
"None",
",",
"op_types_to_quantize",
"=",
"[",
"]",
")",
":",
"logging",
".",
"warning",
"(",
"\"onnxruntime.quantization.quantize is deprecated.\\n\\\n Please use quantize_static for static quantization, quantize_dynamic for dynamic quantization.\"",
")",
"if",
"nbits",
"==",
"8",
"or",
"nbits",
"==",
"7",
":",
"mode",
"=",
"quantization_mode",
"copy_model",
"=",
"onnx_proto",
".",
"ModelProto",
"(",
")",
"copy_model",
".",
"CopyFrom",
"(",
"model",
")",
"if",
"not",
"op_types_to_quantize",
"or",
"len",
"(",
"op_types_to_quantize",
")",
"==",
"0",
":",
"op_types_to_quantize",
"=",
"list",
"(",
"QLinearOpsRegistry",
".",
"keys",
"(",
")",
")",
"if",
"static",
"else",
"list",
"(",
"IntegerOpsRegistry",
".",
"keys",
"(",
")",
")",
"quantizer",
"=",
"ONNXQuantizer",
"(",
"copy_model",
",",
"per_channel",
",",
"nbits",
"==",
"7",
",",
"mode",
",",
"static",
",",
"symmetric_weight",
",",
"symmetric_activation",
",",
"quantization_params",
",",
"nodes_to_quantize",
",",
"nodes_to_exclude",
",",
"op_types_to_quantize",
")",
"quantizer",
".",
"quantize_model",
"(",
")",
"return",
"quantizer",
".",
"model",
".",
"model",
"else",
":",
"raise",
"ValueError",
"(",
"'Only 8 and 7 bit quantization is currently supported'",
")"
] |
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/quantization/quantize.py#L57-L134
|
||
FreeCAD/FreeCAD
|
ba42231b9c6889b89e064d6d563448ed81e376ec
|
src/Mod/Arch/ArchNesting.py
|
python
|
test
|
()
|
runs a test with selected shapes, container selected last
|
runs a test with selected shapes, container selected last
|
[
"runs",
"a",
"test",
"with",
"selected",
"shapes",
"container",
"selected",
"last"
] |
def test():
"runs a test with selected shapes, container selected last"
import FreeCADGui
sel = FreeCADGui.Selection.getSelection()
if sel:
container = sel.pop().Shape
shapes = [o.Shape for o in sel]
n = Nester(container,shapes)
result = n.run()
if result:
n.show()
|
[
"def",
"test",
"(",
")",
":",
"import",
"FreeCADGui",
"sel",
"=",
"FreeCADGui",
".",
"Selection",
".",
"getSelection",
"(",
")",
"if",
"sel",
":",
"container",
"=",
"sel",
".",
"pop",
"(",
")",
".",
"Shape",
"shapes",
"=",
"[",
"o",
".",
"Shape",
"for",
"o",
"in",
"sel",
"]",
"n",
"=",
"Nester",
"(",
"container",
",",
"shapes",
")",
"result",
"=",
"n",
".",
"run",
"(",
")",
"if",
"result",
":",
"n",
".",
"show",
"(",
")"
] |
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchNesting.py#L693-L705
|
||
bundy-dns/bundy
|
3d41934996b82b0cd2fe22dd74d2abc1daba835d
|
src/lib/python/bundy/config/config_data.py
|
python
|
_find_spec_part_single
|
(cur_spec, id_part)
|
Find the spec part for the given (partial) name. This partial
name does not contain separators ('/'), and the specification
part should be a direct child of the given specification part.
id_part may contain list selectors, which will be ignored.
Returns the child part.
Raises DataNotFoundError if it was not found.
|
Find the spec part for the given (partial) name. This partial
name does not contain separators ('/'), and the specification
part should be a direct child of the given specification part.
id_part may contain list selectors, which will be ignored.
Returns the child part.
Raises DataNotFoundError if it was not found.
|
[
"Find",
"the",
"spec",
"part",
"for",
"the",
"given",
"(",
"partial",
")",
"name",
".",
"This",
"partial",
"name",
"does",
"not",
"contain",
"separators",
"(",
"/",
")",
"and",
"the",
"specification",
"part",
"should",
"be",
"a",
"direct",
"child",
"of",
"the",
"given",
"specification",
"part",
".",
"id_part",
"may",
"contain",
"list",
"selectors",
"which",
"will",
"be",
"ignored",
".",
"Returns",
"the",
"child",
"part",
".",
"Raises",
"DataNotFoundError",
"if",
"it",
"was",
"not",
"found",
"."
] |
def _find_spec_part_single(cur_spec, id_part):
"""Find the spec part for the given (partial) name. This partial
name does not contain separators ('/'), and the specification
part should be a direct child of the given specification part.
id_part may contain list selectors, which will be ignored.
Returns the child part.
Raises DataNotFoundError if it was not found."""
# strip list selector part
# don't need it for the spec part, so just drop it
id, list_indices = bundy.cc.data.split_identifier_list_indices(id_part)
# The specification we want a sub-part for should be either a
# list or a map, which is internally represented by a dict with
# an element 'map_item_spec', a dict with an element 'list_item_spec',
# or a list (when it is the 'main' config_data element of a module).
if spec_part_is_map(cur_spec):
for cur_spec_item in cur_spec['map_item_spec']:
if cur_spec_item['item_name'] == id:
return cur_spec_item
# not found
raise bundy.cc.data.DataNotFoundError(id + " not found")
elif spec_part_is_list(cur_spec):
if cur_spec['item_name'] == id:
return cur_spec['list_item_spec']
# not found
raise bundy.cc.data.DataNotFoundError(id + " not found")
elif type(cur_spec) == dict and 'named_set_item_spec' in cur_spec.keys():
return cur_spec['named_set_item_spec']
elif type(cur_spec) == list:
for cur_spec_item in cur_spec:
if cur_spec_item['item_name'] == id:
return cur_spec_item
# not found
raise bundy.cc.data.DataNotFoundError(id + " not found")
else:
raise bundy.cc.data.DataNotFoundError("Not a correct config specification")
|
[
"def",
"_find_spec_part_single",
"(",
"cur_spec",
",",
"id_part",
")",
":",
"# strip list selector part",
"# don't need it for the spec part, so just drop it",
"id",
",",
"list_indices",
"=",
"bundy",
".",
"cc",
".",
"data",
".",
"split_identifier_list_indices",
"(",
"id_part",
")",
"# The specification we want a sub-part for should be either a",
"# list or a map, which is internally represented by a dict with",
"# an element 'map_item_spec', a dict with an element 'list_item_spec',",
"# or a list (when it is the 'main' config_data element of a module).",
"if",
"spec_part_is_map",
"(",
"cur_spec",
")",
":",
"for",
"cur_spec_item",
"in",
"cur_spec",
"[",
"'map_item_spec'",
"]",
":",
"if",
"cur_spec_item",
"[",
"'item_name'",
"]",
"==",
"id",
":",
"return",
"cur_spec_item",
"# not found",
"raise",
"bundy",
".",
"cc",
".",
"data",
".",
"DataNotFoundError",
"(",
"id",
"+",
"\" not found\"",
")",
"elif",
"spec_part_is_list",
"(",
"cur_spec",
")",
":",
"if",
"cur_spec",
"[",
"'item_name'",
"]",
"==",
"id",
":",
"return",
"cur_spec",
"[",
"'list_item_spec'",
"]",
"# not found",
"raise",
"bundy",
".",
"cc",
".",
"data",
".",
"DataNotFoundError",
"(",
"id",
"+",
"\" not found\"",
")",
"elif",
"type",
"(",
"cur_spec",
")",
"==",
"dict",
"and",
"'named_set_item_spec'",
"in",
"cur_spec",
".",
"keys",
"(",
")",
":",
"return",
"cur_spec",
"[",
"'named_set_item_spec'",
"]",
"elif",
"type",
"(",
"cur_spec",
")",
"==",
"list",
":",
"for",
"cur_spec_item",
"in",
"cur_spec",
":",
"if",
"cur_spec_item",
"[",
"'item_name'",
"]",
"==",
"id",
":",
"return",
"cur_spec_item",
"# not found",
"raise",
"bundy",
".",
"cc",
".",
"data",
".",
"DataNotFoundError",
"(",
"id",
"+",
"\" not found\"",
")",
"else",
":",
"raise",
"bundy",
".",
"cc",
".",
"data",
".",
"DataNotFoundError",
"(",
"\"Not a correct config specification\"",
")"
] |
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/config/config_data.py#L180-L215
|
||
chromiumembedded/cef
|
80caf947f3fe2210e5344713c5281d8af9bdc295
|
tools/file_util.py
|
python
|
write_file_if_changed
|
(name, data)
|
return False
|
Write a file if the contents have changed. Returns True if the file was written.
|
Write a file if the contents have changed. Returns True if the file was written.
|
[
"Write",
"a",
"file",
"if",
"the",
"contents",
"have",
"changed",
".",
"Returns",
"True",
"if",
"the",
"file",
"was",
"written",
"."
] |
def write_file_if_changed(name, data):
""" Write a file if the contents have changed. Returns True if the file was written. """
if path_exists(name):
old_contents = read_file(name)
else:
old_contents = ''
if (data != old_contents):
write_file(name, data)
return True
return False
|
[
"def",
"write_file_if_changed",
"(",
"name",
",",
"data",
")",
":",
"if",
"path_exists",
"(",
"name",
")",
":",
"old_contents",
"=",
"read_file",
"(",
"name",
")",
"else",
":",
"old_contents",
"=",
"''",
"if",
"(",
"data",
"!=",
"old_contents",
")",
":",
"write_file",
"(",
"name",
",",
"data",
")",
"return",
"True",
"return",
"False"
] |
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/file_util.py#L51-L61
|
|
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
third_party/catapult/third_party/Paste/paste/exceptions/collector.py
|
python
|
collect_exception
|
(t, v, tb, limit=None)
|
return col.collectException(t, v, tb, limit=limit)
|
Collection an exception from ``sys.exc_info()``.
Use like::
try:
blah blah
except:
exc_data = collect_exception(*sys.exc_info())
|
Collection an exception from ``sys.exc_info()``.
|
[
"Collection",
"an",
"exception",
"from",
"sys",
".",
"exc_info",
"()",
"."
] |
def collect_exception(t, v, tb, limit=None):
"""
Collection an exception from ``sys.exc_info()``.
Use like::
try:
blah blah
except:
exc_data = collect_exception(*sys.exc_info())
"""
return col.collectException(t, v, tb, limit=limit)
|
[
"def",
"collect_exception",
"(",
"t",
",",
"v",
",",
"tb",
",",
"limit",
"=",
"None",
")",
":",
"return",
"col",
".",
"collectException",
"(",
"t",
",",
"v",
",",
"tb",
",",
"limit",
"=",
"limit",
")"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/exceptions/collector.py#L512-L523
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/_gdi.py
|
python
|
Locale.GetLocale
|
(*args, **kwargs)
|
return _gdi_.Locale_GetLocale(*args, **kwargs)
|
GetLocale(self) -> String
|
GetLocale(self) -> String
|
[
"GetLocale",
"(",
"self",
")",
"-",
">",
"String"
] |
def GetLocale(*args, **kwargs):
"""GetLocale(self) -> String"""
return _gdi_.Locale_GetLocale(*args, **kwargs)
|
[
"def",
"GetLocale",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Locale_GetLocale",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3017-L3019
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/aui.py
|
python
|
AuiDockArt.SetColour
|
(*args, **kwargs)
|
return _aui.AuiDockArt_SetColour(*args, **kwargs)
|
SetColour(self, int id, Colour colour)
|
SetColour(self, int id, Colour colour)
|
[
"SetColour",
"(",
"self",
"int",
"id",
"Colour",
"colour",
")"
] |
def SetColour(*args, **kwargs):
"""SetColour(self, int id, Colour colour)"""
return _aui.AuiDockArt_SetColour(*args, **kwargs)
|
[
"def",
"SetColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiDockArt_SetColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L986-L988
|
|
lukasmonk/lucaschess
|
13e2e5cb13b38a720ccf897af649054a64bcb914
|
Code/Procesador.py
|
python
|
Procesador.cambiaRival
|
(self, nuevo)
|
Llamado desde DatosNueva, cuando elegimos otro motor para jugar.
|
Llamado desde DatosNueva, cuando elegimos otro motor para jugar.
|
[
"Llamado",
"desde",
"DatosNueva",
"cuando",
"elegimos",
"otro",
"motor",
"para",
"jugar",
"."
] |
def cambiaRival(self, nuevo):
"""
Llamado desde DatosNueva, cuando elegimos otro motor para jugar.
"""
self.configuracion.rival = self.configuracion.buscaRival(nuevo)
self.configuracion.graba()
|
[
"def",
"cambiaRival",
"(",
"self",
",",
"nuevo",
")",
":",
"self",
".",
"configuracion",
".",
"rival",
"=",
"self",
".",
"configuracion",
".",
"buscaRival",
"(",
"nuevo",
")",
"self",
".",
"configuracion",
".",
"graba",
"(",
")"
] |
https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/Procesador.py#L325-L330
|
||
giuspen/cherrytree
|
84712f206478fcf9acf30174009ad28c648c6344
|
pygtk2/modules/core.py
|
python
|
CherryTree.file_open
|
(self, *args)
|
Opens a dialog to browse for a cherrytree filepath
|
Opens a dialog to browse for a cherrytree filepath
|
[
"Opens",
"a",
"dialog",
"to",
"browse",
"for",
"a",
"cherrytree",
"filepath"
] |
def file_open(self, *args):
"""Opens a dialog to browse for a cherrytree filepath"""
filepath = support.dialog_file_select(filter_pattern=["*.ct*"],
filter_name=_("CherryTree Document"),
curr_folder=self.file_dir,
parent=self.window)
if not filepath: return
#self.filepath_boss_open(filepath, "")
self.filepath_open(filepath)
|
[
"def",
"file_open",
"(",
"self",
",",
"*",
"args",
")",
":",
"filepath",
"=",
"support",
".",
"dialog_file_select",
"(",
"filter_pattern",
"=",
"[",
"\"*.ct*\"",
"]",
",",
"filter_name",
"=",
"_",
"(",
"\"CherryTree Document\"",
")",
",",
"curr_folder",
"=",
"self",
".",
"file_dir",
",",
"parent",
"=",
"self",
".",
"window",
")",
"if",
"not",
"filepath",
":",
"return",
"#self.filepath_boss_open(filepath, \"\")",
"self",
".",
"filepath_open",
"(",
"filepath",
")"
] |
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L1776-L1784
|
||
mongodb/mongo
|
d8ff665343ad29cf286ee2cf4a1960d29371937b
|
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py
|
python
|
File.get_cachedir_csig
|
(self)
|
return self.cachedir_csig
|
Fetch a Node's content signature for purposes of computing
another Node's cachesig.
This is a wrapper around the normal get_csig() method that handles
the somewhat obscure case of using CacheDir with the -n option.
Any files that don't exist would normally be "built" by fetching
them from the cache, but the normal get_csig() method will try
to open up the local file, which doesn't exist because the -n
option meant we didn't actually pull the file from cachedir.
But since the file *does* actually exist in the cachedir, we
can use its contents for the csig.
|
Fetch a Node's content signature for purposes of computing
another Node's cachesig.
|
[
"Fetch",
"a",
"Node",
"s",
"content",
"signature",
"for",
"purposes",
"of",
"computing",
"another",
"Node",
"s",
"cachesig",
"."
] |
def get_cachedir_csig(self):
"""
Fetch a Node's content signature for purposes of computing
another Node's cachesig.
This is a wrapper around the normal get_csig() method that handles
the somewhat obscure case of using CacheDir with the -n option.
Any files that don't exist would normally be "built" by fetching
them from the cache, but the normal get_csig() method will try
to open up the local file, which doesn't exist because the -n
option meant we didn't actually pull the file from cachedir.
But since the file *does* actually exist in the cachedir, we
can use its contents for the csig.
"""
try:
return self.cachedir_csig
except AttributeError:
pass
cache = self.get_build_env().get_CacheDir()
cachedir, cachefile = cache.cachepath(self)
if not self.exists() and cachefile and os.path.exists(cachefile):
self.cachedir_csig = cache.get_cachedir_csig(self)
else:
self.cachedir_csig = self.get_csig()
return self.cachedir_csig
|
[
"def",
"get_cachedir_csig",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"cachedir_csig",
"except",
"AttributeError",
":",
"pass",
"cache",
"=",
"self",
".",
"get_build_env",
"(",
")",
".",
"get_CacheDir",
"(",
")",
"cachedir",
",",
"cachefile",
"=",
"cache",
".",
"cachepath",
"(",
"self",
")",
"if",
"not",
"self",
".",
"exists",
"(",
")",
"and",
"cachefile",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"cachefile",
")",
":",
"self",
".",
"cachedir_csig",
"=",
"cache",
".",
"get_cachedir_csig",
"(",
"self",
")",
"else",
":",
"self",
".",
"cachedir_csig",
"=",
"self",
".",
"get_csig",
"(",
")",
"return",
"self",
".",
"cachedir_csig"
] |
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py#L3593-L3618
|
|
benoitsteiner/tensorflow-opencl
|
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
|
tensorflow/python/platform/benchmark.py
|
python
|
Benchmark.report_benchmark
|
(
self,
iters=None,
cpu_time=None,
wall_time=None,
throughput=None,
extras=None,
name=None)
|
Report a benchmark.
Args:
iters: (optional) How many iterations were run
cpu_time: (optional) median or mean cpu time in seconds.
wall_time: (optional) median or mean wall time in seconds.
throughput: (optional) Throughput (in MB/s)
extras: (optional) Dict mapping string keys to additional benchmark info.
Values may be either floats or values that are convertible to strings.
name: (optional) Override the BenchmarkEntry name with `name`.
Otherwise it is inferred from the top-level method name.
|
Report a benchmark.
|
[
"Report",
"a",
"benchmark",
"."
] |
def report_benchmark(
self,
iters=None,
cpu_time=None,
wall_time=None,
throughput=None,
extras=None,
name=None):
"""Report a benchmark.
Args:
iters: (optional) How many iterations were run
cpu_time: (optional) median or mean cpu time in seconds.
wall_time: (optional) median or mean wall time in seconds.
throughput: (optional) Throughput (in MB/s)
extras: (optional) Dict mapping string keys to additional benchmark info.
Values may be either floats or values that are convertible to strings.
name: (optional) Override the BenchmarkEntry name with `name`.
Otherwise it is inferred from the top-level method name.
"""
name = self._get_name(overwrite_name=name)
_global_report_benchmark(
name=name, iters=iters, cpu_time=cpu_time, wall_time=wall_time,
throughput=throughput, extras=extras)
|
[
"def",
"report_benchmark",
"(",
"self",
",",
"iters",
"=",
"None",
",",
"cpu_time",
"=",
"None",
",",
"wall_time",
"=",
"None",
",",
"throughput",
"=",
"None",
",",
"extras",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"self",
".",
"_get_name",
"(",
"overwrite_name",
"=",
"name",
")",
"_global_report_benchmark",
"(",
"name",
"=",
"name",
",",
"iters",
"=",
"iters",
",",
"cpu_time",
"=",
"cpu_time",
",",
"wall_time",
"=",
"wall_time",
",",
"throughput",
"=",
"throughput",
",",
"extras",
"=",
"extras",
")"
] |
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/platform/benchmark.py#L160-L183
|
||
eclipse/sumo
|
7132a9b8b6eea734bdec38479026b4d8c4336d03
|
tools/contributed/sumopy/coremodules/demand/demand.py
|
python
|
Trips.get_writexmlinfo
|
(self, is_route=False, is_exclude_pedestrians=False, **kwargs)
|
return self.times_depart[ids], writefuncs, ids
|
Returns three array where the first array is the
begin time of the first vehicle and the second array is the
write function to be called for the respectice vehicle and
the third array contains the vehicle ids
Method used to sort trips when exporting to route or trip xml file
|
Returns three array where the first array is the
begin time of the first vehicle and the second array is the
write function to be called for the respectice vehicle and
the third array contains the vehicle ids
|
[
"Returns",
"three",
"array",
"where",
"the",
"first",
"array",
"is",
"the",
"begin",
"time",
"of",
"the",
"first",
"vehicle",
"and",
"the",
"second",
"array",
"is",
"the",
"write",
"function",
"to",
"be",
"called",
"for",
"the",
"respectice",
"vehicle",
"and",
"the",
"third",
"array",
"contains",
"the",
"vehicle",
"ids"
] |
def get_writexmlinfo(self, is_route=False, is_exclude_pedestrians=False, **kwargs):
"""
Returns three array where the first array is the
begin time of the first vehicle and the second array is the
write function to be called for the respectice vehicle and
the third array contains the vehicle ids
Method used to sort trips when exporting to route or trip xml file
"""
ids = self.get_ids()
if not is_exclude_pedestrians:
# define different route write functions for pedestriand and vehicles
n = len(ids)
writefuncs = np.zeros(n, dtype=np.object)
inds_ped = self.parent.vtypes.ids_mode[self.ids_vtype[ids]] == MODES['pedestrian']
writefuncs[inds_ped] = self.write_persontrip_xml
if is_route:
writefuncs[np.logical_not(inds_ped) & (self.ids_route_current[ids] > -1)] = self.write_vehroute_xml
# vehicles must have a route, this makes sure that OD are connected
writefuncs[np.logical_not(inds_ped) & (self.ids_route_current[ids] == -1)] = self.write_missingroute_xml
else:
# here we write vehicle trip, without explicit route export
# routing will be performed during simulation
writefuncs[np.logical_not(inds_ped) & (self.ids_route_current[ids] > -1)] = self.write_vehtrip_xml
# vehicles must have a route, this makes sure that OD are connected
writefuncs[np.logical_not(inds_ped) & (self.ids_route_current[ids] == -1)] = self.write_missingroute_xml
else:
# only vehicle types without peds
inds_noped = self.parent.vtypes.ids_mode[self.ids_vtype[ids]] != MODES['pedestrian']
ids = ids[inds_noped]
n = len(ids)
writefuncs = np.zeros(n, dtype=np.object)
if is_route:
writefuncs[self.ids_route_current[ids] > -1] = self.write_vehroute_xml
# vehicles must have a route, this makes sure that OD are connected
writefuncs[self.ids_route_current[ids] == -1] = self.write_missingroute_xml
else:
# here we write vehicle trip, without explicit route export
# routing will be performed during simulation
writefuncs[self.ids_route_current[ids] > -1] = self.write_vehtrip_xml
# vehicles must have a route, this makes sure that OD are connected
writefuncs[self.ids_route_current[ids] == -1] = self.write_missingroute_xml
return self.times_depart[ids], writefuncs, ids
|
[
"def",
"get_writexmlinfo",
"(",
"self",
",",
"is_route",
"=",
"False",
",",
"is_exclude_pedestrians",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ids",
"=",
"self",
".",
"get_ids",
"(",
")",
"if",
"not",
"is_exclude_pedestrians",
":",
"# define different route write functions for pedestriand and vehicles",
"n",
"=",
"len",
"(",
"ids",
")",
"writefuncs",
"=",
"np",
".",
"zeros",
"(",
"n",
",",
"dtype",
"=",
"np",
".",
"object",
")",
"inds_ped",
"=",
"self",
".",
"parent",
".",
"vtypes",
".",
"ids_mode",
"[",
"self",
".",
"ids_vtype",
"[",
"ids",
"]",
"]",
"==",
"MODES",
"[",
"'pedestrian'",
"]",
"writefuncs",
"[",
"inds_ped",
"]",
"=",
"self",
".",
"write_persontrip_xml",
"if",
"is_route",
":",
"writefuncs",
"[",
"np",
".",
"logical_not",
"(",
"inds_ped",
")",
"&",
"(",
"self",
".",
"ids_route_current",
"[",
"ids",
"]",
">",
"-",
"1",
")",
"]",
"=",
"self",
".",
"write_vehroute_xml",
"# vehicles must have a route, this makes sure that OD are connected",
"writefuncs",
"[",
"np",
".",
"logical_not",
"(",
"inds_ped",
")",
"&",
"(",
"self",
".",
"ids_route_current",
"[",
"ids",
"]",
"==",
"-",
"1",
")",
"]",
"=",
"self",
".",
"write_missingroute_xml",
"else",
":",
"# here we write vehicle trip, without explicit route export",
"# routing will be performed during simulation",
"writefuncs",
"[",
"np",
".",
"logical_not",
"(",
"inds_ped",
")",
"&",
"(",
"self",
".",
"ids_route_current",
"[",
"ids",
"]",
">",
"-",
"1",
")",
"]",
"=",
"self",
".",
"write_vehtrip_xml",
"# vehicles must have a route, this makes sure that OD are connected",
"writefuncs",
"[",
"np",
".",
"logical_not",
"(",
"inds_ped",
")",
"&",
"(",
"self",
".",
"ids_route_current",
"[",
"ids",
"]",
"==",
"-",
"1",
")",
"]",
"=",
"self",
".",
"write_missingroute_xml",
"else",
":",
"# only vehicle types without peds",
"inds_noped",
"=",
"self",
".",
"parent",
".",
"vtypes",
".",
"ids_mode",
"[",
"self",
".",
"ids_vtype",
"[",
"ids",
"]",
"]",
"!=",
"MODES",
"[",
"'pedestrian'",
"]",
"ids",
"=",
"ids",
"[",
"inds_noped",
"]",
"n",
"=",
"len",
"(",
"ids",
")",
"writefuncs",
"=",
"np",
".",
"zeros",
"(",
"n",
",",
"dtype",
"=",
"np",
".",
"object",
")",
"if",
"is_route",
":",
"writefuncs",
"[",
"self",
".",
"ids_route_current",
"[",
"ids",
"]",
">",
"-",
"1",
"]",
"=",
"self",
".",
"write_vehroute_xml",
"# vehicles must have a route, this makes sure that OD are connected",
"writefuncs",
"[",
"self",
".",
"ids_route_current",
"[",
"ids",
"]",
"==",
"-",
"1",
"]",
"=",
"self",
".",
"write_missingroute_xml",
"else",
":",
"# here we write vehicle trip, without explicit route export",
"# routing will be performed during simulation",
"writefuncs",
"[",
"self",
".",
"ids_route_current",
"[",
"ids",
"]",
">",
"-",
"1",
"]",
"=",
"self",
".",
"write_vehtrip_xml",
"# vehicles must have a route, this makes sure that OD are connected",
"writefuncs",
"[",
"self",
".",
"ids_route_current",
"[",
"ids",
"]",
"==",
"-",
"1",
"]",
"=",
"self",
".",
"write_missingroute_xml",
"return",
"self",
".",
"times_depart",
"[",
"ids",
"]",
",",
"writefuncs",
",",
"ids"
] |
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/demand.py#L1150-L1199
|
|
wisdompeak/LeetCode
|
ef729c1249ead3ead47f1a94b5eeb5958a69e152
|
Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops.py
|
python
|
Solution.findCheapestPrice
|
(self, n, flights, src, dst, K)
|
return dp[dst] if dp[dst]!=math.inf else -1
|
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
|
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
|
[
":",
"type",
"n",
":",
"int",
":",
"type",
"flights",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"type",
"src",
":",
"int",
":",
"type",
"dst",
":",
"int",
":",
"type",
"K",
":",
"int",
":",
"rtype",
":",
"int"
] |
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
dp = [math.inf for _ in range(n)]
dp[src] = 0
for k in range(K+1):
dp_temp = dp[:]
for (a,b,cost) in flights:
dp[b] = min(dp[b], dp_temp[a]+cost)
return dp[dst] if dp[dst]!=math.inf else -1
|
[
"def",
"findCheapestPrice",
"(",
"self",
",",
"n",
",",
"flights",
",",
"src",
",",
"dst",
",",
"K",
")",
":",
"dp",
"=",
"[",
"math",
".",
"inf",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"dp",
"[",
"src",
"]",
"=",
"0",
"for",
"k",
"in",
"range",
"(",
"K",
"+",
"1",
")",
":",
"dp_temp",
"=",
"dp",
"[",
":",
"]",
"for",
"(",
"a",
",",
"b",
",",
"cost",
")",
"in",
"flights",
":",
"dp",
"[",
"b",
"]",
"=",
"min",
"(",
"dp",
"[",
"b",
"]",
",",
"dp_temp",
"[",
"a",
"]",
"+",
"cost",
")",
"return",
"dp",
"[",
"dst",
"]",
"if",
"dp",
"[",
"dst",
"]",
"!=",
"math",
".",
"inf",
"else",
"-",
"1"
] |
https://github.com/wisdompeak/LeetCode/blob/ef729c1249ead3ead47f1a94b5eeb5958a69e152/Graph/787.Cheapest-Flights-Within-K-Stops/787.Cheapest-Flights-Within-K-Stops.py#L2-L17
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scipy/py3/scipy/signal/ltisys.py
|
python
|
_YT_real
|
(ker_pole, Q, transfer_matrix, i, j)
|
Applies algorithm from YT section 6.1 page 19 related to real pairs
|
Applies algorithm from YT section 6.1 page 19 related to real pairs
|
[
"Applies",
"algorithm",
"from",
"YT",
"section",
"6",
".",
"1",
"page",
"19",
"related",
"to",
"real",
"pairs"
] |
def _YT_real(ker_pole, Q, transfer_matrix, i, j):
"""
Applies algorithm from YT section 6.1 page 19 related to real pairs
"""
# step 1 page 19
u = Q[:, -2, np.newaxis]
v = Q[:, -1, np.newaxis]
# step 2 page 19
m = np.dot(np.dot(ker_pole[i].T, np.dot(u, v.T) -
np.dot(v, u.T)), ker_pole[j])
# step 3 page 19
um, sm, vm = np.linalg.svd(m)
# mu1, mu2 two first columns of U => 2 first lines of U.T
mu1, mu2 = um.T[:2, :, np.newaxis]
# VM is V.T with numpy we want the first two lines of V.T
nu1, nu2 = vm[:2, :, np.newaxis]
# what follows is a rough python translation of the formulas
# in section 6.2 page 20 (step 4)
transfer_matrix_j_mo_transfer_matrix_j = np.vstack((
transfer_matrix[:, i, np.newaxis],
transfer_matrix[:, j, np.newaxis]))
if not np.allclose(sm[0], sm[1]):
ker_pole_imo_mu1 = np.dot(ker_pole[i], mu1)
ker_pole_i_nu1 = np.dot(ker_pole[j], nu1)
ker_pole_mu_nu = np.vstack((ker_pole_imo_mu1, ker_pole_i_nu1))
else:
ker_pole_ij = np.vstack((
np.hstack((ker_pole[i],
np.zeros(ker_pole[i].shape))),
np.hstack((np.zeros(ker_pole[j].shape),
ker_pole[j]))
))
mu_nu_matrix = np.vstack(
(np.hstack((mu1, mu2)), np.hstack((nu1, nu2)))
)
ker_pole_mu_nu = np.dot(ker_pole_ij, mu_nu_matrix)
transfer_matrix_ij = np.dot(np.dot(ker_pole_mu_nu, ker_pole_mu_nu.T),
transfer_matrix_j_mo_transfer_matrix_j)
if not np.allclose(transfer_matrix_ij, 0):
transfer_matrix_ij = (np.sqrt(2)*transfer_matrix_ij /
np.linalg.norm(transfer_matrix_ij))
transfer_matrix[:, i] = transfer_matrix_ij[
:transfer_matrix[:, i].shape[0], 0
]
transfer_matrix[:, j] = transfer_matrix_ij[
transfer_matrix[:, i].shape[0]:, 0
]
else:
# As in knv0 if transfer_matrix_j_mo_transfer_matrix_j is orthogonal to
# Vect{ker_pole_mu_nu} assign transfer_matrixi/transfer_matrix_j to
# ker_pole_mu_nu and iterate. As we are looking for a vector in
# Vect{Matker_pole_MU_NU} (see section 6.1 page 19) this might help
# (that's a guess, not a claim !)
transfer_matrix[:, i] = ker_pole_mu_nu[
:transfer_matrix[:, i].shape[0], 0
]
transfer_matrix[:, j] = ker_pole_mu_nu[
transfer_matrix[:, i].shape[0]:, 0
]
|
[
"def",
"_YT_real",
"(",
"ker_pole",
",",
"Q",
",",
"transfer_matrix",
",",
"i",
",",
"j",
")",
":",
"# step 1 page 19",
"u",
"=",
"Q",
"[",
":",
",",
"-",
"2",
",",
"np",
".",
"newaxis",
"]",
"v",
"=",
"Q",
"[",
":",
",",
"-",
"1",
",",
"np",
".",
"newaxis",
"]",
"# step 2 page 19",
"m",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"ker_pole",
"[",
"i",
"]",
".",
"T",
",",
"np",
".",
"dot",
"(",
"u",
",",
"v",
".",
"T",
")",
"-",
"np",
".",
"dot",
"(",
"v",
",",
"u",
".",
"T",
")",
")",
",",
"ker_pole",
"[",
"j",
"]",
")",
"# step 3 page 19",
"um",
",",
"sm",
",",
"vm",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"m",
")",
"# mu1, mu2 two first columns of U => 2 first lines of U.T",
"mu1",
",",
"mu2",
"=",
"um",
".",
"T",
"[",
":",
"2",
",",
":",
",",
"np",
".",
"newaxis",
"]",
"# VM is V.T with numpy we want the first two lines of V.T",
"nu1",
",",
"nu2",
"=",
"vm",
"[",
":",
"2",
",",
":",
",",
"np",
".",
"newaxis",
"]",
"# what follows is a rough python translation of the formulas",
"# in section 6.2 page 20 (step 4)",
"transfer_matrix_j_mo_transfer_matrix_j",
"=",
"np",
".",
"vstack",
"(",
"(",
"transfer_matrix",
"[",
":",
",",
"i",
",",
"np",
".",
"newaxis",
"]",
",",
"transfer_matrix",
"[",
":",
",",
"j",
",",
"np",
".",
"newaxis",
"]",
")",
")",
"if",
"not",
"np",
".",
"allclose",
"(",
"sm",
"[",
"0",
"]",
",",
"sm",
"[",
"1",
"]",
")",
":",
"ker_pole_imo_mu1",
"=",
"np",
".",
"dot",
"(",
"ker_pole",
"[",
"i",
"]",
",",
"mu1",
")",
"ker_pole_i_nu1",
"=",
"np",
".",
"dot",
"(",
"ker_pole",
"[",
"j",
"]",
",",
"nu1",
")",
"ker_pole_mu_nu",
"=",
"np",
".",
"vstack",
"(",
"(",
"ker_pole_imo_mu1",
",",
"ker_pole_i_nu1",
")",
")",
"else",
":",
"ker_pole_ij",
"=",
"np",
".",
"vstack",
"(",
"(",
"np",
".",
"hstack",
"(",
"(",
"ker_pole",
"[",
"i",
"]",
",",
"np",
".",
"zeros",
"(",
"ker_pole",
"[",
"i",
"]",
".",
"shape",
")",
")",
")",
",",
"np",
".",
"hstack",
"(",
"(",
"np",
".",
"zeros",
"(",
"ker_pole",
"[",
"j",
"]",
".",
"shape",
")",
",",
"ker_pole",
"[",
"j",
"]",
")",
")",
")",
")",
"mu_nu_matrix",
"=",
"np",
".",
"vstack",
"(",
"(",
"np",
".",
"hstack",
"(",
"(",
"mu1",
",",
"mu2",
")",
")",
",",
"np",
".",
"hstack",
"(",
"(",
"nu1",
",",
"nu2",
")",
")",
")",
")",
"ker_pole_mu_nu",
"=",
"np",
".",
"dot",
"(",
"ker_pole_ij",
",",
"mu_nu_matrix",
")",
"transfer_matrix_ij",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"ker_pole_mu_nu",
",",
"ker_pole_mu_nu",
".",
"T",
")",
",",
"transfer_matrix_j_mo_transfer_matrix_j",
")",
"if",
"not",
"np",
".",
"allclose",
"(",
"transfer_matrix_ij",
",",
"0",
")",
":",
"transfer_matrix_ij",
"=",
"(",
"np",
".",
"sqrt",
"(",
"2",
")",
"*",
"transfer_matrix_ij",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"transfer_matrix_ij",
")",
")",
"transfer_matrix",
"[",
":",
",",
"i",
"]",
"=",
"transfer_matrix_ij",
"[",
":",
"transfer_matrix",
"[",
":",
",",
"i",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"0",
"]",
"transfer_matrix",
"[",
":",
",",
"j",
"]",
"=",
"transfer_matrix_ij",
"[",
"transfer_matrix",
"[",
":",
",",
"i",
"]",
".",
"shape",
"[",
"0",
"]",
":",
",",
"0",
"]",
"else",
":",
"# As in knv0 if transfer_matrix_j_mo_transfer_matrix_j is orthogonal to",
"# Vect{ker_pole_mu_nu} assign transfer_matrixi/transfer_matrix_j to",
"# ker_pole_mu_nu and iterate. As we are looking for a vector in",
"# Vect{Matker_pole_MU_NU} (see section 6.1 page 19) this might help",
"# (that's a guess, not a claim !)",
"transfer_matrix",
"[",
":",
",",
"i",
"]",
"=",
"ker_pole_mu_nu",
"[",
":",
"transfer_matrix",
"[",
":",
",",
"i",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"0",
"]",
"transfer_matrix",
"[",
":",
",",
"j",
"]",
"=",
"ker_pole_mu_nu",
"[",
"transfer_matrix",
"[",
":",
",",
"i",
"]",
".",
"shape",
"[",
"0",
"]",
":",
",",
"0",
"]"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/ltisys.py#L2615-L2677
|
||
epiqc/ScaffCC
|
66a79944ee4cd116b27bc1a69137276885461db8
|
clang/tools/scan-build-py/libear/__init__.py
|
python
|
Toolset.add_definitions
|
(self, defines)
|
part of public interface
|
part of public interface
|
[
"part",
"of",
"public",
"interface"
] |
def add_definitions(self, defines):
""" part of public interface """
self.c_flags.extend(defines)
|
[
"def",
"add_definitions",
"(",
"self",
",",
"defines",
")",
":",
"self",
".",
"c_flags",
".",
"extend",
"(",
"defines",
")"
] |
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/tools/scan-build-py/libear/__init__.py#L94-L96
|
||
echronos/echronos
|
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
|
external_tools/ply_info/example/ansic/cparse.py
|
python
|
p_iteration_statement_3
|
(t)
|
iteration_statement : DO statement WHILE LPAREN expression RPAREN SEMI
|
iteration_statement : DO statement WHILE LPAREN expression RPAREN SEMI
|
[
"iteration_statement",
":",
"DO",
"statement",
"WHILE",
"LPAREN",
"expression",
"RPAREN",
"SEMI"
] |
def p_iteration_statement_3(t):
'iteration_statement : DO statement WHILE LPAREN expression RPAREN SEMI'
pass
|
[
"def",
"p_iteration_statement_3",
"(",
"t",
")",
":",
"pass"
] |
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L535-L537
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py
|
python
|
_BaseV4._parse_octet
|
(cls, octet_str)
|
return octet_int
|
Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255].
|
Convert a decimal octet into an integer.
|
[
"Convert",
"a",
"decimal",
"octet",
"into",
"an",
"integer",
"."
] |
def _parse_octet(cls, octet_str):
"""Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255].
"""
if not octet_str:
raise ValueError("Empty octet not permitted")
# Whitelist the characters, since int() allows a lot of bizarre stuff.
if not cls._DECIMAL_DIGITS.issuperset(octet_str):
msg = "Only decimal digits permitted in %r"
raise ValueError(msg % octet_str)
# We do the length check second, since the invalid character error
# is likely to be more informative for the user
if len(octet_str) > 3:
msg = "At most 3 characters permitted in %r"
raise ValueError(msg % octet_str)
# Convert to integer (we know digits are legal)
octet_int = int(octet_str, 10)
# Any octets that look like they *might* be written in octal,
# and which don't look exactly the same in both octal and
# decimal are rejected as ambiguous
if octet_int > 7 and octet_str[0] == '0':
msg = "Ambiguous (octal/decimal) value in %r not permitted"
raise ValueError(msg % octet_str)
if octet_int > 255:
raise ValueError("Octet %d (> 255) not permitted" % octet_int)
return octet_int
|
[
"def",
"_parse_octet",
"(",
"cls",
",",
"octet_str",
")",
":",
"if",
"not",
"octet_str",
":",
"raise",
"ValueError",
"(",
"\"Empty octet not permitted\"",
")",
"# Whitelist the characters, since int() allows a lot of bizarre stuff.",
"if",
"not",
"cls",
".",
"_DECIMAL_DIGITS",
".",
"issuperset",
"(",
"octet_str",
")",
":",
"msg",
"=",
"\"Only decimal digits permitted in %r\"",
"raise",
"ValueError",
"(",
"msg",
"%",
"octet_str",
")",
"# We do the length check second, since the invalid character error",
"# is likely to be more informative for the user",
"if",
"len",
"(",
"octet_str",
")",
">",
"3",
":",
"msg",
"=",
"\"At most 3 characters permitted in %r\"",
"raise",
"ValueError",
"(",
"msg",
"%",
"octet_str",
")",
"# Convert to integer (we know digits are legal)",
"octet_int",
"=",
"int",
"(",
"octet_str",
",",
"10",
")",
"# Any octets that look like they *might* be written in octal,",
"# and which don't look exactly the same in both octal and",
"# decimal are rejected as ambiguous",
"if",
"octet_int",
">",
"7",
"and",
"octet_str",
"[",
"0",
"]",
"==",
"'0'",
":",
"msg",
"=",
"\"Ambiguous (octal/decimal) value in %r not permitted\"",
"raise",
"ValueError",
"(",
"msg",
"%",
"octet_str",
")",
"if",
"octet_int",
">",
"255",
":",
"raise",
"ValueError",
"(",
"\"Octet %d (> 255) not permitted\"",
"%",
"octet_int",
")",
"return",
"octet_int"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py#L1169-L1203
|
|
manutdzou/KITTI_SSD
|
5b620c2f291d36a0fe14489214f22a992f173f44
|
python/caffe/pycaffe.py
|
python
|
_Net_forward
|
(self, blobs=None, start=None, end=None, **kwargs)
|
return {out: self.blobs[out].data for out in outputs}
|
Forward pass: prepare inputs and run the net forward.
Parameters
----------
blobs : list of blobs to return in addition to output blobs.
kwargs : Keys are input blob names and values are blob ndarrays.
For formatting inputs for Caffe, see Net.preprocess().
If None, input is taken from data layers.
start : optional name of layer at which to begin the forward pass
end : optional name of layer at which to finish the forward pass
(inclusive)
Returns
-------
outs : {blob name: blob ndarray} dict.
|
Forward pass: prepare inputs and run the net forward.
|
[
"Forward",
"pass",
":",
"prepare",
"inputs",
"and",
"run",
"the",
"net",
"forward",
"."
] |
def _Net_forward(self, blobs=None, start=None, end=None, **kwargs):
"""
Forward pass: prepare inputs and run the net forward.
Parameters
----------
blobs : list of blobs to return in addition to output blobs.
kwargs : Keys are input blob names and values are blob ndarrays.
For formatting inputs for Caffe, see Net.preprocess().
If None, input is taken from data layers.
start : optional name of layer at which to begin the forward pass
end : optional name of layer at which to finish the forward pass
(inclusive)
Returns
-------
outs : {blob name: blob ndarray} dict.
"""
if blobs is None:
blobs = []
if start is not None:
start_ind = list(self._layer_names).index(start)
else:
start_ind = 0
if end is not None:
end_ind = list(self._layer_names).index(end)
outputs = set([end] + blobs)
else:
end_ind = len(self.layers) - 1
outputs = set(self.outputs + blobs)
if kwargs:
if set(kwargs.keys()) != set(self.inputs):
raise Exception('Input blob arguments do not match net inputs.')
# Set input according to defined shapes and make arrays single and
# C-contiguous as Caffe expects.
for in_, blob in six.iteritems(kwargs):
if blob.shape[0] != self.blobs[in_].shape[0]:
raise Exception('Input is not batch sized')
self.blobs[in_].data[...] = blob
self._forward(start_ind, end_ind)
# Unpack blobs to extract
return {out: self.blobs[out].data for out in outputs}
|
[
"def",
"_Net_forward",
"(",
"self",
",",
"blobs",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"blobs",
"is",
"None",
":",
"blobs",
"=",
"[",
"]",
"if",
"start",
"is",
"not",
"None",
":",
"start_ind",
"=",
"list",
"(",
"self",
".",
"_layer_names",
")",
".",
"index",
"(",
"start",
")",
"else",
":",
"start_ind",
"=",
"0",
"if",
"end",
"is",
"not",
"None",
":",
"end_ind",
"=",
"list",
"(",
"self",
".",
"_layer_names",
")",
".",
"index",
"(",
"end",
")",
"outputs",
"=",
"set",
"(",
"[",
"end",
"]",
"+",
"blobs",
")",
"else",
":",
"end_ind",
"=",
"len",
"(",
"self",
".",
"layers",
")",
"-",
"1",
"outputs",
"=",
"set",
"(",
"self",
".",
"outputs",
"+",
"blobs",
")",
"if",
"kwargs",
":",
"if",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"!=",
"set",
"(",
"self",
".",
"inputs",
")",
":",
"raise",
"Exception",
"(",
"'Input blob arguments do not match net inputs.'",
")",
"# Set input according to defined shapes and make arrays single and",
"# C-contiguous as Caffe expects.",
"for",
"in_",
",",
"blob",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"if",
"blob",
".",
"shape",
"[",
"0",
"]",
"!=",
"self",
".",
"blobs",
"[",
"in_",
"]",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"Exception",
"(",
"'Input is not batch sized'",
")",
"self",
".",
"blobs",
"[",
"in_",
"]",
".",
"data",
"[",
"...",
"]",
"=",
"blob",
"self",
".",
"_forward",
"(",
"start_ind",
",",
"end_ind",
")",
"# Unpack blobs to extract",
"return",
"{",
"out",
":",
"self",
".",
"blobs",
"[",
"out",
"]",
".",
"data",
"for",
"out",
"in",
"outputs",
"}"
] |
https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/python/caffe/pycaffe.py#L78-L124
|
|
FreeCAD/FreeCAD
|
ba42231b9c6889b89e064d6d563448ed81e376ec
|
src/Mod/PartDesign/WizardShaft/SegmentFunction.py
|
python
|
SegmentFunction.value
|
(self, xval)
|
return result
|
Return the value of the function at the specified x value
|
Return the value of the function at the specified x value
|
[
"Return",
"the",
"value",
"of",
"the",
"function",
"at",
"the",
"specified",
"x",
"value"
] |
def value(self, xval):
"Return the value of the function at the specified x value"
result = 0
for s in self.segments:
result = result + s.value(xval)
return result
|
[
"def",
"value",
"(",
"self",
",",
"xval",
")",
":",
"result",
"=",
"0",
"for",
"s",
"in",
"self",
".",
"segments",
":",
"result",
"=",
"result",
"+",
"s",
".",
"value",
"(",
"xval",
")",
"return",
"result"
] |
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/PartDesign/WizardShaft/SegmentFunction.py#L139-L144
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/client.py
|
python
|
ClientCreator._default_s3_presign_to_sigv2
|
(self, signature_version, **kwargs)
|
Returns the 's3' (sigv2) signer if presigning an s3 request. This is
intended to be used to set the default signature version for the signer
to sigv2.
:type signature_version: str
:param signature_version: The current client signature version.
:type signing_name: str
:param signing_name: The signing name of the service.
:return: 's3' if the request is an s3 presign request, None otherwise
|
Returns the 's3' (sigv2) signer if presigning an s3 request. This is
intended to be used to set the default signature version for the signer
to sigv2.
|
[
"Returns",
"the",
"s3",
"(",
"sigv2",
")",
"signer",
"if",
"presigning",
"an",
"s3",
"request",
".",
"This",
"is",
"intended",
"to",
"be",
"used",
"to",
"set",
"the",
"default",
"signature",
"version",
"for",
"the",
"signer",
"to",
"sigv2",
"."
] |
def _default_s3_presign_to_sigv2(self, signature_version, **kwargs):
"""
Returns the 's3' (sigv2) signer if presigning an s3 request. This is
intended to be used to set the default signature version for the signer
to sigv2.
:type signature_version: str
:param signature_version: The current client signature version.
:type signing_name: str
:param signing_name: The signing name of the service.
:return: 's3' if the request is an s3 presign request, None otherwise
"""
for suffix in ['-query', '-presign-post']:
if signature_version.endswith(suffix):
return 's3' + suffix
|
[
"def",
"_default_s3_presign_to_sigv2",
"(",
"self",
",",
"signature_version",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"suffix",
"in",
"[",
"'-query'",
",",
"'-presign-post'",
"]",
":",
"if",
"signature_version",
".",
"endswith",
"(",
"suffix",
")",
":",
"return",
"'s3'",
"+",
"suffix"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/client.py#L260-L276
|
||
Samsung/veles
|
95ed733c2e49bc011ad98ccf2416ecec23fbf352
|
veles/loader/fullbatch.py
|
python
|
IFullBatchLoader.load_data
|
()
|
Load the data here.
Must be set: class_lengths, original_data, [original_labels].
|
Load the data here.
Must be set: class_lengths, original_data, [original_labels].
|
[
"Load",
"the",
"data",
"here",
".",
"Must",
"be",
"set",
":",
"class_lengths",
"original_data",
"[",
"original_labels",
"]",
"."
] |
def load_data():
"""Load the data here.
Must be set: class_lengths, original_data, [original_labels].
"""
|
[
"def",
"load_data",
"(",
")",
":"
] |
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/loader/fullbatch.py#L72-L75
|
||
wujixiu/helmet-detection
|
8eff5c59ddfba5a29e0b76aeb48babcb49246178
|
hardhat-wearing-detection/SSD-RPA/python/caffe/pycaffe.py
|
python
|
_Net_get_id_name
|
(func, field)
|
return get_id_name
|
Generic property that maps func to the layer names into an OrderedDict.
Used for top_names and bottom_names.
Parameters
----------
func: function id -> [id]
field: implementation field name (cache)
Returns
------
A one-parameter function that can be set as a property.
|
Generic property that maps func to the layer names into an OrderedDict.
|
[
"Generic",
"property",
"that",
"maps",
"func",
"to",
"the",
"layer",
"names",
"into",
"an",
"OrderedDict",
"."
] |
def _Net_get_id_name(func, field):
"""
Generic property that maps func to the layer names into an OrderedDict.
Used for top_names and bottom_names.
Parameters
----------
func: function id -> [id]
field: implementation field name (cache)
Returns
------
A one-parameter function that can be set as a property.
"""
@property
def get_id_name(self):
if not hasattr(self, field):
id_to_name = list(self.blobs)
res = OrderedDict([(self._layer_names[i],
[id_to_name[j] for j in func(self, i)])
for i in range(len(self.layers))])
setattr(self, field, res)
return getattr(self, field)
return get_id_name
|
[
"def",
"_Net_get_id_name",
"(",
"func",
",",
"field",
")",
":",
"@",
"property",
"def",
"get_id_name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"field",
")",
":",
"id_to_name",
"=",
"list",
"(",
"self",
".",
"blobs",
")",
"res",
"=",
"OrderedDict",
"(",
"[",
"(",
"self",
".",
"_layer_names",
"[",
"i",
"]",
",",
"[",
"id_to_name",
"[",
"j",
"]",
"for",
"j",
"in",
"func",
"(",
"self",
",",
"i",
")",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"layers",
")",
")",
"]",
")",
"setattr",
"(",
"self",
",",
"field",
",",
"res",
")",
"return",
"getattr",
"(",
"self",
",",
"field",
")",
"return",
"get_id_name"
] |
https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/python/caffe/pycaffe.py#L295-L319
|
|
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/bdb.py
|
python
|
Bdb.set_return
|
(self, frame)
|
Stop when returning from the given frame.
|
Stop when returning from the given frame.
|
[
"Stop",
"when",
"returning",
"from",
"the",
"given",
"frame",
"."
] |
def set_return(self, frame):
"""Stop when returning from the given frame."""
self._set_stopinfo(frame.f_back, frame)
|
[
"def",
"set_return",
"(",
"self",
",",
"frame",
")",
":",
"self",
".",
"_set_stopinfo",
"(",
"frame",
".",
"f_back",
",",
"frame",
")"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/bdb.py#L208-L210
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/pandas/py3/pandas/core/indexes/base.py
|
python
|
Index.isna
|
(self)
|
return self._isnan
|
Detect missing values.
Return a boolean same-sized object indicating if the values are NA.
NA values, such as ``None``, :attr:`numpy.NaN` or :attr:`pd.NaT`, get
mapped to ``True`` values.
Everything else get mapped to ``False`` values. Characters such as
empty strings `''` or :attr:`numpy.inf` are not considered NA values
(unless you set ``pandas.options.mode.use_inf_as_na = True``).
Returns
-------
numpy.ndarray[bool]
A boolean array of whether my values are NA.
See Also
--------
Index.notna : Boolean inverse of isna.
Index.dropna : Omit entries with missing values.
isna : Top-level isna.
Series.isna : Detect missing values in Series object.
Examples
--------
Show which entries in a pandas.Index are NA. The result is an
array.
>>> idx = pd.Index([5.2, 6.0, np.NaN])
>>> idx
Float64Index([5.2, 6.0, nan], dtype='float64')
>>> idx.isna()
array([False, False, True])
Empty strings are not considered NA values. None is considered an NA
value.
>>> idx = pd.Index(['black', '', 'red', None])
>>> idx
Index(['black', '', 'red', None], dtype='object')
>>> idx.isna()
array([False, False, False, True])
For datetimes, `NaT` (Not a Time) is considered as an NA value.
>>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'),
... pd.Timestamp(''), None, pd.NaT])
>>> idx
DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'],
dtype='datetime64[ns]', freq=None)
>>> idx.isna()
array([False, True, True, True])
|
Detect missing values.
|
[
"Detect",
"missing",
"values",
"."
] |
def isna(self) -> np.ndarray:
"""
Detect missing values.
Return a boolean same-sized object indicating if the values are NA.
NA values, such as ``None``, :attr:`numpy.NaN` or :attr:`pd.NaT`, get
mapped to ``True`` values.
Everything else get mapped to ``False`` values. Characters such as
empty strings `''` or :attr:`numpy.inf` are not considered NA values
(unless you set ``pandas.options.mode.use_inf_as_na = True``).
Returns
-------
numpy.ndarray[bool]
A boolean array of whether my values are NA.
See Also
--------
Index.notna : Boolean inverse of isna.
Index.dropna : Omit entries with missing values.
isna : Top-level isna.
Series.isna : Detect missing values in Series object.
Examples
--------
Show which entries in a pandas.Index are NA. The result is an
array.
>>> idx = pd.Index([5.2, 6.0, np.NaN])
>>> idx
Float64Index([5.2, 6.0, nan], dtype='float64')
>>> idx.isna()
array([False, False, True])
Empty strings are not considered NA values. None is considered an NA
value.
>>> idx = pd.Index(['black', '', 'red', None])
>>> idx
Index(['black', '', 'red', None], dtype='object')
>>> idx.isna()
array([False, False, False, True])
For datetimes, `NaT` (Not a Time) is considered as an NA value.
>>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'),
... pd.Timestamp(''), None, pd.NaT])
>>> idx
DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'],
dtype='datetime64[ns]', freq=None)
>>> idx.isna()
array([False, True, True, True])
"""
return self._isnan
|
[
"def",
"isna",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"self",
".",
"_isnan"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L2455-L2508
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python/src/Lib/decimal.py
|
python
|
Context.is_finite
|
(self, a)
|
return a.is_finite()
|
Return True if the operand is finite; otherwise return False.
A Decimal instance is considered finite if it is neither
infinite nor a NaN.
>>> ExtendedContext.is_finite(Decimal('2.50'))
True
>>> ExtendedContext.is_finite(Decimal('-0.3'))
True
>>> ExtendedContext.is_finite(Decimal('0'))
True
>>> ExtendedContext.is_finite(Decimal('Inf'))
False
>>> ExtendedContext.is_finite(Decimal('NaN'))
False
>>> ExtendedContext.is_finite(1)
True
|
Return True if the operand is finite; otherwise return False.
|
[
"Return",
"True",
"if",
"the",
"operand",
"is",
"finite",
";",
"otherwise",
"return",
"False",
"."
] |
def is_finite(self, a):
"""Return True if the operand is finite; otherwise return False.
A Decimal instance is considered finite if it is neither
infinite nor a NaN.
>>> ExtendedContext.is_finite(Decimal('2.50'))
True
>>> ExtendedContext.is_finite(Decimal('-0.3'))
True
>>> ExtendedContext.is_finite(Decimal('0'))
True
>>> ExtendedContext.is_finite(Decimal('Inf'))
False
>>> ExtendedContext.is_finite(Decimal('NaN'))
False
>>> ExtendedContext.is_finite(1)
True
"""
a = _convert_other(a, raiseit=True)
return a.is_finite()
|
[
"def",
"is_finite",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"is_finite",
"(",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L4323-L4343
|
|
eventql/eventql
|
7ca0dbb2e683b525620ea30dc40540a22d5eb227
|
deps/3rdparty/spidermonkey/mozjs/build/upload.py
|
python
|
RequireEnvironmentVariable
|
(v)
|
return os.environ[v]
|
Return the value of the environment variable named v, or print
an error and exit if it's unset (or empty).
|
Return the value of the environment variable named v, or print
an error and exit if it's unset (or empty).
|
[
"Return",
"the",
"value",
"of",
"the",
"environment",
"variable",
"named",
"v",
"or",
"print",
"an",
"error",
"and",
"exit",
"if",
"it",
"s",
"unset",
"(",
"or",
"empty",
")",
"."
] |
def RequireEnvironmentVariable(v):
"""Return the value of the environment variable named v, or print
an error and exit if it's unset (or empty)."""
if not v in os.environ or os.environ[v] == "":
print "Error: required environment variable %s not set" % v
sys.exit(1)
return os.environ[v]
|
[
"def",
"RequireEnvironmentVariable",
"(",
"v",
")",
":",
"if",
"not",
"v",
"in",
"os",
".",
"environ",
"or",
"os",
".",
"environ",
"[",
"v",
"]",
"==",
"\"\"",
":",
"print",
"\"Error: required environment variable %s not set\"",
"%",
"v",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"os",
".",
"environ",
"[",
"v",
"]"
] |
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/upload.py#L30-L36
|
|
facebookincubator/BOLT
|
88c70afe9d388ad430cc150cc158641701397f70
|
clang/bindings/python/clang/cindex.py
|
python
|
Token.location
|
(self)
|
return conf.lib.clang_getTokenLocation(self._tu, self)
|
The SourceLocation this Token occurs at.
|
The SourceLocation this Token occurs at.
|
[
"The",
"SourceLocation",
"this",
"Token",
"occurs",
"at",
"."
] |
def location(self):
"""The SourceLocation this Token occurs at."""
return conf.lib.clang_getTokenLocation(self._tu, self)
|
[
"def",
"location",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTokenLocation",
"(",
"self",
".",
"_tu",
",",
"self",
")"
] |
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/bindings/python/clang/cindex.py#L3301-L3303
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/resources/collection.py
|
python
|
CollectionFactory._load_batch_actions
|
(self, attrs, resource_name, collection_model,
service_model, event_emitter)
|
Batch actions on the collection become methods on both
the collection manager and iterators.
|
Batch actions on the collection become methods on both
the collection manager and iterators.
|
[
"Batch",
"actions",
"on",
"the",
"collection",
"become",
"methods",
"on",
"both",
"the",
"collection",
"manager",
"and",
"iterators",
"."
] |
def _load_batch_actions(self, attrs, resource_name, collection_model,
service_model, event_emitter):
"""
Batch actions on the collection become methods on both
the collection manager and iterators.
"""
for action_model in collection_model.batch_actions:
snake_cased = xform_name(action_model.name)
attrs[snake_cased] = self._create_batch_action(
resource_name, snake_cased, action_model, collection_model,
service_model, event_emitter)
|
[
"def",
"_load_batch_actions",
"(",
"self",
",",
"attrs",
",",
"resource_name",
",",
"collection_model",
",",
"service_model",
",",
"event_emitter",
")",
":",
"for",
"action_model",
"in",
"collection_model",
".",
"batch_actions",
":",
"snake_cased",
"=",
"xform_name",
"(",
"action_model",
".",
"name",
")",
"attrs",
"[",
"snake_cased",
"]",
"=",
"self",
".",
"_create_batch_action",
"(",
"resource_name",
",",
"snake_cased",
",",
"action_model",
",",
"collection_model",
",",
"service_model",
",",
"event_emitter",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/resources/collection.py#L428-L438
|
||
cksystemsgroup/scalloc
|
049857919b5fa1d539c9e4206e353daca2e87394
|
tools/cpplint.py
|
python
|
PrintCategories
|
()
|
Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter.
|
Prints a list of all the error-categories used by error messages.
|
[
"Prints",
"a",
"list",
"of",
"all",
"the",
"error",
"-",
"categories",
"used",
"by",
"error",
"messages",
"."
] |
def PrintCategories():
"""Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter.
"""
sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
sys.exit(0)
|
[
"def",
"PrintCategories",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"''",
".",
"join",
"(",
"' %s\\n'",
"%",
"cat",
"for",
"cat",
"in",
"_ERROR_CATEGORIES",
")",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] |
https://github.com/cksystemsgroup/scalloc/blob/049857919b5fa1d539c9e4206e353daca2e87394/tools/cpplint.py#L4655-L4661
|
||
root-project/root
|
fcd3583bb14852bf2e8cd2415717cbaac0e75896
|
interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py
|
python
|
Type.get_align
|
(self)
|
return conf.lib.clang_Type_getAlignOf(self)
|
Retrieve the alignment of the record.
|
Retrieve the alignment of the record.
|
[
"Retrieve",
"the",
"alignment",
"of",
"the",
"record",
"."
] |
def get_align(self):
"""
Retrieve the alignment of the record.
"""
return conf.lib.clang_Type_getAlignOf(self)
|
[
"def",
"get_align",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Type_getAlignOf",
"(",
"self",
")"
] |
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py#L2377-L2381
|
|
pytorch/pytorch
|
7176c92687d3cc847cc046bf002269c6949a21c2
|
torch/nn/modules/transformer.py
|
python
|
TransformerDecoderLayer.forward
|
(self, tgt: Tensor, memory: Tensor, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None,
tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None)
|
return x
|
r"""Pass the inputs (and mask) through the decoder layer.
Args:
tgt: the sequence to the decoder layer (required).
memory: the sequence from the last layer of the encoder (required).
tgt_mask: the mask for the tgt sequence (optional).
memory_mask: the mask for the memory sequence (optional).
tgt_key_padding_mask: the mask for the tgt keys per batch (optional).
memory_key_padding_mask: the mask for the memory keys per batch (optional).
Shape:
see the docs in Transformer class.
|
r"""Pass the inputs (and mask) through the decoder layer.
|
[
"r",
"Pass",
"the",
"inputs",
"(",
"and",
"mask",
")",
"through",
"the",
"decoder",
"layer",
"."
] |
def forward(self, tgt: Tensor, memory: Tensor, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None,
tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None) -> Tensor:
r"""Pass the inputs (and mask) through the decoder layer.
Args:
tgt: the sequence to the decoder layer (required).
memory: the sequence from the last layer of the encoder (required).
tgt_mask: the mask for the tgt sequence (optional).
memory_mask: the mask for the memory sequence (optional).
tgt_key_padding_mask: the mask for the tgt keys per batch (optional).
memory_key_padding_mask: the mask for the memory keys per batch (optional).
Shape:
see the docs in Transformer class.
"""
# see Fig. 1 of https://arxiv.org/pdf/2002.04745v1.pdf
x = tgt
if self.norm_first:
x = x + self._sa_block(self.norm1(x), tgt_mask, tgt_key_padding_mask)
x = x + self._mha_block(self.norm2(x), memory, memory_mask, memory_key_padding_mask)
x = x + self._ff_block(self.norm3(x))
else:
x = self.norm1(x + self._sa_block(x, tgt_mask, tgt_key_padding_mask))
x = self.norm2(x + self._mha_block(x, memory, memory_mask, memory_key_padding_mask))
x = self.norm3(x + self._ff_block(x))
return x
|
[
"def",
"forward",
"(",
"self",
",",
"tgt",
":",
"Tensor",
",",
"memory",
":",
"Tensor",
",",
"tgt_mask",
":",
"Optional",
"[",
"Tensor",
"]",
"=",
"None",
",",
"memory_mask",
":",
"Optional",
"[",
"Tensor",
"]",
"=",
"None",
",",
"tgt_key_padding_mask",
":",
"Optional",
"[",
"Tensor",
"]",
"=",
"None",
",",
"memory_key_padding_mask",
":",
"Optional",
"[",
"Tensor",
"]",
"=",
"None",
")",
"->",
"Tensor",
":",
"# see Fig. 1 of https://arxiv.org/pdf/2002.04745v1.pdf",
"x",
"=",
"tgt",
"if",
"self",
".",
"norm_first",
":",
"x",
"=",
"x",
"+",
"self",
".",
"_sa_block",
"(",
"self",
".",
"norm1",
"(",
"x",
")",
",",
"tgt_mask",
",",
"tgt_key_padding_mask",
")",
"x",
"=",
"x",
"+",
"self",
".",
"_mha_block",
"(",
"self",
".",
"norm2",
"(",
"x",
")",
",",
"memory",
",",
"memory_mask",
",",
"memory_key_padding_mask",
")",
"x",
"=",
"x",
"+",
"self",
".",
"_ff_block",
"(",
"self",
".",
"norm3",
"(",
"x",
")",
")",
"else",
":",
"x",
"=",
"self",
".",
"norm1",
"(",
"x",
"+",
"self",
".",
"_sa_block",
"(",
"x",
",",
"tgt_mask",
",",
"tgt_key_padding_mask",
")",
")",
"x",
"=",
"self",
".",
"norm2",
"(",
"x",
"+",
"self",
".",
"_mha_block",
"(",
"x",
",",
"memory",
",",
"memory_mask",
",",
"memory_key_padding_mask",
")",
")",
"x",
"=",
"self",
".",
"norm3",
"(",
"x",
"+",
"self",
".",
"_ff_block",
"(",
"x",
")",
")",
"return",
"x"
] |
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/modules/transformer.py#L434-L461
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/propgrid.py
|
python
|
EditEnumProperty.__init__
|
(self, *args)
|
__init__(self, String label, String name, wxChar labels, long values,
String value) -> EditEnumProperty
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
wxArrayString labels=wxArrayString(),
wxArrayInt values=wxArrayInt(),
String value=wxEmptyString) -> EditEnumProperty
__init__(self, String label, String name, PGChoices choices, String value=wxEmptyString) -> EditEnumProperty
__init__(self, String label, String name, wxChar labels, long values,
PGChoices choicesCache, String value) -> EditEnumProperty
|
__init__(self, String label, String name, wxChar labels, long values,
String value) -> EditEnumProperty
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
wxArrayString labels=wxArrayString(),
wxArrayInt values=wxArrayInt(),
String value=wxEmptyString) -> EditEnumProperty
__init__(self, String label, String name, PGChoices choices, String value=wxEmptyString) -> EditEnumProperty
__init__(self, String label, String name, wxChar labels, long values,
PGChoices choicesCache, String value) -> EditEnumProperty
|
[
"__init__",
"(",
"self",
"String",
"label",
"String",
"name",
"wxChar",
"labels",
"long",
"values",
"String",
"value",
")",
"-",
">",
"EditEnumProperty",
"__init__",
"(",
"self",
"String",
"label",
"=",
"(",
"*",
"wxPGProperty",
"::",
"sm_wxPG_LABEL",
")",
"String",
"name",
"=",
"(",
"*",
"wxPGProperty",
"::",
"sm_wxPG_LABEL",
")",
"wxArrayString",
"labels",
"=",
"wxArrayString",
"()",
"wxArrayInt",
"values",
"=",
"wxArrayInt",
"()",
"String",
"value",
"=",
"wxEmptyString",
")",
"-",
">",
"EditEnumProperty",
"__init__",
"(",
"self",
"String",
"label",
"String",
"name",
"PGChoices",
"choices",
"String",
"value",
"=",
"wxEmptyString",
")",
"-",
">",
"EditEnumProperty",
"__init__",
"(",
"self",
"String",
"label",
"String",
"name",
"wxChar",
"labels",
"long",
"values",
"PGChoices",
"choicesCache",
"String",
"value",
")",
"-",
">",
"EditEnumProperty"
] |
def __init__(self, *args):
"""
__init__(self, String label, String name, wxChar labels, long values,
String value) -> EditEnumProperty
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
wxArrayString labels=wxArrayString(),
wxArrayInt values=wxArrayInt(),
String value=wxEmptyString) -> EditEnumProperty
__init__(self, String label, String name, PGChoices choices, String value=wxEmptyString) -> EditEnumProperty
__init__(self, String label, String name, wxChar labels, long values,
PGChoices choicesCache, String value) -> EditEnumProperty
"""
_propgrid.EditEnumProperty_swiginit(self,_propgrid.new_EditEnumProperty(*args))
|
[
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_propgrid",
".",
"EditEnumProperty_swiginit",
"(",
"self",
",",
"_propgrid",
".",
"new_EditEnumProperty",
"(",
"*",
"args",
")",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3015-L3027
|
||
eclipse/sumo
|
7132a9b8b6eea734bdec38479026b4d8c4336d03
|
tools/contributed/sumopy/plugins/hcprt/hcprt.py
|
python
|
HcPrtTransits.append_stage
|
(self, id_plan, time_start=-1.0,
duration=0.0,
id_fromedge=-1, id_toedge=-1, **kwargs)
|
return id_stage, time_end
|
Appends a PRT transit stage to plan id_plan.
|
Appends a PRT transit stage to plan id_plan.
|
[
"Appends",
"a",
"PRT",
"transit",
"stage",
"to",
"plan",
"id_plan",
"."
] |
def append_stage(self, id_plan, time_start=-1.0,
duration=0.0,
id_fromedge=-1, id_toedge=-1, **kwargs):
"""
Appends a PRT transit stage to plan id_plan.
"""
# print 'HcPrtTransits.append_stage',id_stage
id_stage, time_end = StageTypeMixin.append_stage(self,
id_plan,
time_start,
durations=duration,
ids_fromedge=id_fromedge,
ids_toedge=id_toedge,
)
# add this stage to the vehicle database
# ind_ride gives the index of this ride (within the same plan??)
#ind_ride = self.parent.get_individualvehicles().append_ride(id_veh, id_stage)
return id_stage, time_end
|
[
"def",
"append_stage",
"(",
"self",
",",
"id_plan",
",",
"time_start",
"=",
"-",
"1.0",
",",
"duration",
"=",
"0.0",
",",
"id_fromedge",
"=",
"-",
"1",
",",
"id_toedge",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"# print 'HcPrtTransits.append_stage',id_stage",
"id_stage",
",",
"time_end",
"=",
"StageTypeMixin",
".",
"append_stage",
"(",
"self",
",",
"id_plan",
",",
"time_start",
",",
"durations",
"=",
"duration",
",",
"ids_fromedge",
"=",
"id_fromedge",
",",
"ids_toedge",
"=",
"id_toedge",
",",
")",
"# add this stage to the vehicle database",
"# ind_ride gives the index of this ride (within the same plan??)",
"#ind_ride = self.parent.get_individualvehicles().append_ride(id_veh, id_stage)",
"return",
"id_stage",
",",
"time_end"
] |
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/hcprt/hcprt.py#L6639-L6659
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/_windows.py
|
python
|
PageSetupDialogData.EnableHelp
|
(*args, **kwargs)
|
return _windows_.PageSetupDialogData_EnableHelp(*args, **kwargs)
|
EnableHelp(self, bool flag)
|
EnableHelp(self, bool flag)
|
[
"EnableHelp",
"(",
"self",
"bool",
"flag",
")"
] |
def EnableHelp(*args, **kwargs):
"""EnableHelp(self, bool flag)"""
return _windows_.PageSetupDialogData_EnableHelp(*args, **kwargs)
|
[
"def",
"EnableHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_EnableHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L4874-L4876
|
|
limbo018/DREAMPlace
|
146c3b9fd003d1acd52c96d9fd02e3f0a05154e4
|
dreamplace/NesterovAcceleratedGradientOptimizer.py
|
python
|
NesterovAcceleratedGradientOptimizer.__init__
|
(self, params, lr=required, obj_and_grad_fn=required, constraint_fn=None)
|
@brief initialization
@param params variable to optimize
@param lr learning rate
@param obj_and_grad_fn a callable function to get objective and gradient
@param constraint_fn a callable function to force variables to satisfy all the constraints
|
[] |
def __init__(self, params, lr=required, obj_and_grad_fn=required, constraint_fn=None):
"""
@brief initialization
@param params variable to optimize
@param lr learning rate
@param obj_and_grad_fn a callable function to get objective and gradient
@param constraint_fn a callable function to force variables to satisfy all the constraints
"""
if lr is not required and lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
# u_k is major solution
# v_k is reference solution
# obj_k is the objective at v_k
# a_k is optimization parameter
# alpha_k is the step size
# v_k_1 is previous reference solution
# g_k_1 is gradient to v_k_1
# obj_k_1 is the objective at v_k_1
defaults = dict(lr=lr,
u_k=[], v_k=[], g_k=[], obj_k=[], a_k=[], alpha_k=[],
v_k_1=[], g_k_1=[], obj_k_1=[],
v_kp1 = [None],
obj_eval_count=0)
super(NesterovAcceleratedGradientOptimizer, self).__init__(params, defaults)
self.obj_and_grad_fn = obj_and_grad_fn
self.constraint_fn = constraint_fn
# I do not know how to get generator's length
if len(self.param_groups) != 1:
raise ValueError("Only parameters with single tensor is supported")
|
[
"def",
"__init__",
"(",
"self",
",",
"params",
",",
"lr",
"=",
"required",
",",
"obj_and_grad_fn",
"=",
"required",
",",
"constraint_fn",
"=",
"None",
")",
":",
"if",
"lr",
"is",
"not",
"required",
"and",
"lr",
"<",
"0.0",
":",
"raise",
"ValueError",
"(",
"\"Invalid learning rate: {}\"",
".",
"format",
"(",
"lr",
")",
")",
"# u_k is major solution",
"# v_k is reference solution",
"# obj_k is the objective at v_k",
"# a_k is optimization parameter",
"# alpha_k is the step size",
"# v_k_1 is previous reference solution",
"# g_k_1 is gradient to v_k_1",
"# obj_k_1 is the objective at v_k_1",
"defaults",
"=",
"dict",
"(",
"lr",
"=",
"lr",
",",
"u_k",
"=",
"[",
"]",
",",
"v_k",
"=",
"[",
"]",
",",
"g_k",
"=",
"[",
"]",
",",
"obj_k",
"=",
"[",
"]",
",",
"a_k",
"=",
"[",
"]",
",",
"alpha_k",
"=",
"[",
"]",
",",
"v_k_1",
"=",
"[",
"]",
",",
"g_k_1",
"=",
"[",
"]",
",",
"obj_k_1",
"=",
"[",
"]",
",",
"v_kp1",
"=",
"[",
"None",
"]",
",",
"obj_eval_count",
"=",
"0",
")",
"super",
"(",
"NesterovAcceleratedGradientOptimizer",
",",
"self",
")",
".",
"__init__",
"(",
"params",
",",
"defaults",
")",
"self",
".",
"obj_and_grad_fn",
"=",
"obj_and_grad_fn",
"self",
".",
"constraint_fn",
"=",
"constraint_fn",
"# I do not know how to get generator's length",
"if",
"len",
"(",
"self",
".",
"param_groups",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Only parameters with single tensor is supported\"",
")"
] |
https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/NesterovAcceleratedGradientOptimizer.py#L23-L53
|
|||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/richtext.py
|
python
|
RichTextBuffer.GetRenderer
|
(*args, **kwargs)
|
return _richtext.RichTextBuffer_GetRenderer(*args, **kwargs)
|
GetRenderer() -> RichTextRenderer
|
GetRenderer() -> RichTextRenderer
|
[
"GetRenderer",
"()",
"-",
">",
"RichTextRenderer"
] |
def GetRenderer(*args, **kwargs):
"""GetRenderer() -> RichTextRenderer"""
return _richtext.RichTextBuffer_GetRenderer(*args, **kwargs)
|
[
"def",
"GetRenderer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_GetRenderer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2605-L2607
|
|
miyosuda/TensorFlowAndroidDemo
|
35903e0221aa5f109ea2dbef27f20b52e317f42d
|
jni-build/jni/include/tensorflow/python/platform/flags.py
|
python
|
_FlagValues.__setattr__
|
(self, name, value)
|
Sets the 'value' attribute of the flag --name.
|
Sets the 'value' attribute of the flag --name.
|
[
"Sets",
"the",
"value",
"attribute",
"of",
"the",
"flag",
"--",
"name",
"."
] |
def __setattr__(self, name, value):
"""Sets the 'value' attribute of the flag --name."""
if not self.__dict__['__parsed']:
self._parse_flags()
self.__dict__['__flags'][name] = value
|
[
"def",
"__setattr__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"__dict__",
"[",
"'__parsed'",
"]",
":",
"self",
".",
"_parse_flags",
"(",
")",
"self",
".",
"__dict__",
"[",
"'__flags'",
"]",
"[",
"name",
"]",
"=",
"value"
] |
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/platform/flags.py#L46-L50
|
||
openvinotoolkit/openvino
|
dedcbeafa8b84cccdc55ca64b8da516682b381c7
|
src/bindings/python/src/compatibility/ngraph/opset1/ops.py
|
python
|
reduce_prod
|
(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
)
|
return _get_node_factory_opset1().create(
"ReduceProd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
|
Product-reduction operation on input tensor, eliminating the specified reduction axes.
:param node: The tensor we want to product-reduce.
:param reduction_axes: The axes to eliminate through product operation.
:param keep_dims: If set to True it holds axes that are used for reduction
:param name: Optional name for output node.
:return: The new node performing product-reduction operation.
|
Product-reduction operation on input tensor, eliminating the specified reduction axes.
|
[
"Product",
"-",
"reduction",
"operation",
"on",
"input",
"tensor",
"eliminating",
"the",
"specified",
"reduction",
"axes",
"."
] |
def reduce_prod(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
) -> Node:
"""Product-reduction operation on input tensor, eliminating the specified reduction axes.
:param node: The tensor we want to product-reduce.
:param reduction_axes: The axes to eliminate through product operation.
:param keep_dims: If set to True it holds axes that are used for reduction
:param name: Optional name for output node.
:return: The new node performing product-reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceProd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
|
[
"def",
"reduce_prod",
"(",
"node",
":",
"NodeInput",
",",
"reduction_axes",
":",
"NodeInput",
",",
"keep_dims",
":",
"bool",
"=",
"False",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Node",
":",
"return",
"_get_node_factory_opset1",
"(",
")",
".",
"create",
"(",
"\"ReduceProd\"",
",",
"as_nodes",
"(",
"node",
",",
"reduction_axes",
")",
",",
"{",
"\"keep_dims\"",
":",
"keep_dims",
"}",
")"
] |
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset1/ops.py#L2341-L2354
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py
|
python
|
FontPage.var_changed_space_num
|
(self, *params)
|
Store change to indentation size.
|
Store change to indentation size.
|
[
"Store",
"change",
"to",
"indentation",
"size",
"."
] |
def var_changed_space_num(self, *params):
"Store change to indentation size."
value = self.space_num.get()
changes.add_option('main', 'Indent', 'num-spaces', value)
|
[
"def",
"var_changed_space_num",
"(",
"self",
",",
"*",
"params",
")",
":",
"value",
"=",
"self",
".",
"space_num",
".",
"get",
"(",
")",
"changes",
".",
"add_option",
"(",
"'main'",
",",
"'Indent'",
",",
"'num-spaces'",
",",
"value",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L680-L683
|
||
apache/parquet-cpp
|
642da055adf009652689b20e68a198cffb857651
|
build-support/cpplint.py
|
python
|
ShouldCheckNamespaceIndentation
|
(nesting_state, is_namespace_indent_item,
raw_lines_no_comments, linenum)
|
return IsBlockInNameSpace(nesting_state, is_forward_declaration)
|
This method determines if we should apply our namespace indentation check.
Args:
nesting_state: The current nesting state.
is_namespace_indent_item: If we just put a new class on the stack, True.
If the top of the stack is not a class, or we did not recently
add the class, False.
raw_lines_no_comments: The lines without the comments.
linenum: The current line number we are processing.
Returns:
True if we should apply our namespace indentation check. Currently, it
only works for classes and namespaces inside of a namespace.
|
This method determines if we should apply our namespace indentation check.
|
[
"This",
"method",
"determines",
"if",
"we",
"should",
"apply",
"our",
"namespace",
"indentation",
"check",
"."
] |
def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
raw_lines_no_comments, linenum):
"""This method determines if we should apply our namespace indentation check.
Args:
nesting_state: The current nesting state.
is_namespace_indent_item: If we just put a new class on the stack, True.
If the top of the stack is not a class, or we did not recently
add the class, False.
raw_lines_no_comments: The lines without the comments.
linenum: The current line number we are processing.
Returns:
True if we should apply our namespace indentation check. Currently, it
only works for classes and namespaces inside of a namespace.
"""
is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
linenum)
if not (is_namespace_indent_item or is_forward_declaration):
return False
# If we are in a macro, we do not want to check the namespace indentation.
if IsMacroDefinition(raw_lines_no_comments, linenum):
return False
return IsBlockInNameSpace(nesting_state, is_forward_declaration)
|
[
"def",
"ShouldCheckNamespaceIndentation",
"(",
"nesting_state",
",",
"is_namespace_indent_item",
",",
"raw_lines_no_comments",
",",
"linenum",
")",
":",
"is_forward_declaration",
"=",
"IsForwardClassDeclaration",
"(",
"raw_lines_no_comments",
",",
"linenum",
")",
"if",
"not",
"(",
"is_namespace_indent_item",
"or",
"is_forward_declaration",
")",
":",
"return",
"False",
"# If we are in a macro, we do not want to check the namespace indentation.",
"if",
"IsMacroDefinition",
"(",
"raw_lines_no_comments",
",",
"linenum",
")",
":",
"return",
"False",
"return",
"IsBlockInNameSpace",
"(",
"nesting_state",
",",
"is_forward_declaration",
")"
] |
https://github.com/apache/parquet-cpp/blob/642da055adf009652689b20e68a198cffb857651/build-support/cpplint.py#L5865-L5892
|
|
FreeCAD/FreeCAD
|
ba42231b9c6889b89e064d6d563448ed81e376ec
|
src/Mod/Path/PathScripts/PathPocketBase.py
|
python
|
ObjectPocket.areaOpFeatures
|
(self, obj)
|
return (
PathOp.FeatureBaseFaces
| PathOp.FeatureFinishDepth
| self.pocketOpFeatures(obj)
)
|
areaOpFeatures(obj) ... Pockets have a FinishDepth and work on Faces
|
areaOpFeatures(obj) ... Pockets have a FinishDepth and work on Faces
|
[
"areaOpFeatures",
"(",
"obj",
")",
"...",
"Pockets",
"have",
"a",
"FinishDepth",
"and",
"work",
"on",
"Faces"
] |
def areaOpFeatures(self, obj):
"""areaOpFeatures(obj) ... Pockets have a FinishDepth and work on Faces"""
return (
PathOp.FeatureBaseFaces
| PathOp.FeatureFinishDepth
| self.pocketOpFeatures(obj)
)
|
[
"def",
"areaOpFeatures",
"(",
"self",
",",
"obj",
")",
":",
"return",
"(",
"PathOp",
".",
"FeatureBaseFaces",
"|",
"PathOp",
".",
"FeatureFinishDepth",
"|",
"self",
".",
"pocketOpFeatures",
"(",
"obj",
")",
")"
] |
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathPocketBase.py#L93-L99
|
|
llvm/llvm-project
|
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
|
clang/tools/include-mapping/cppreference_parser.py
|
python
|
_ParseIndexPage
|
(index_page_html)
|
return symbols
|
Parse index page.
The index page lists all std symbols and hrefs to their detailed pages
(which contain the defined header). An example:
<a href="abs.html" title="abs"><tt>abs()</tt></a> (int) <br>
<a href="acos.html" title="acos"><tt>acos()</tt></a> <br>
Returns a list of tuple (symbol_name, relative_path_to_symbol_page, variant).
|
Parse index page.
The index page lists all std symbols and hrefs to their detailed pages
(which contain the defined header). An example:
|
[
"Parse",
"index",
"page",
".",
"The",
"index",
"page",
"lists",
"all",
"std",
"symbols",
"and",
"hrefs",
"to",
"their",
"detailed",
"pages",
"(",
"which",
"contain",
"the",
"defined",
"header",
")",
".",
"An",
"example",
":"
] |
def _ParseIndexPage(index_page_html):
"""Parse index page.
The index page lists all std symbols and hrefs to their detailed pages
(which contain the defined header). An example:
<a href="abs.html" title="abs"><tt>abs()</tt></a> (int) <br>
<a href="acos.html" title="acos"><tt>acos()</tt></a> <br>
Returns a list of tuple (symbol_name, relative_path_to_symbol_page, variant).
"""
symbols = []
soup = BeautifulSoup(index_page_html, "html.parser")
for symbol_href in soup.select("a[title]"):
# Ignore annotated symbols like "acos<>() (std::complex)".
# These tend to be overloads, and we the primary is more useful.
# This accidentally accepts begin/end despite the (iterator) caption: the
# (since C++11) note is first. They are good symbols, so the bug is unfixed.
caption = symbol_href.next_sibling
variant = None
if isinstance(caption, NavigableString) and "(" in caption:
variant = caption.text.strip(" ()")
symbol_tt = symbol_href.find("tt")
if symbol_tt:
symbols.append((symbol_tt.text.rstrip("<>()"), # strip any trailing <>()
symbol_href["href"], variant))
return symbols
|
[
"def",
"_ParseIndexPage",
"(",
"index_page_html",
")",
":",
"symbols",
"=",
"[",
"]",
"soup",
"=",
"BeautifulSoup",
"(",
"index_page_html",
",",
"\"html.parser\"",
")",
"for",
"symbol_href",
"in",
"soup",
".",
"select",
"(",
"\"a[title]\"",
")",
":",
"# Ignore annotated symbols like \"acos<>() (std::complex)\".",
"# These tend to be overloads, and we the primary is more useful.",
"# This accidentally accepts begin/end despite the (iterator) caption: the",
"# (since C++11) note is first. They are good symbols, so the bug is unfixed.",
"caption",
"=",
"symbol_href",
".",
"next_sibling",
"variant",
"=",
"None",
"if",
"isinstance",
"(",
"caption",
",",
"NavigableString",
")",
"and",
"\"(\"",
"in",
"caption",
":",
"variant",
"=",
"caption",
".",
"text",
".",
"strip",
"(",
"\" ()\"",
")",
"symbol_tt",
"=",
"symbol_href",
".",
"find",
"(",
"\"tt\"",
")",
"if",
"symbol_tt",
":",
"symbols",
".",
"append",
"(",
"(",
"symbol_tt",
".",
"text",
".",
"rstrip",
"(",
"\"<>()\"",
")",
",",
"# strip any trailing <>()",
"symbol_href",
"[",
"\"href\"",
"]",
",",
"variant",
")",
")",
"return",
"symbols"
] |
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/tools/include-mapping/cppreference_parser.py#L88-L113
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py
|
python
|
ParseBaseException.markInputline
|
( self, markerString = ">!<" )
|
return line_str.strip()
|
Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
|
Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
|
[
"Extracts",
"the",
"exception",
"line",
"from",
"the",
"input",
"string",
"and",
"marks",
"the",
"location",
"of",
"the",
"exception",
"with",
"a",
"special",
"symbol",
"."
] |
def markInputline( self, markerString = ">!<" ):
"""Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join((line_str[:line_column],
markerString, line_str[line_column:]))
return line_str.strip()
|
[
"def",
"markInputline",
"(",
"self",
",",
"markerString",
"=",
"\">!<\"",
")",
":",
"line_str",
"=",
"self",
".",
"line",
"line_column",
"=",
"self",
".",
"column",
"-",
"1",
"if",
"markerString",
":",
"line_str",
"=",
"\"\"",
".",
"join",
"(",
"(",
"line_str",
"[",
":",
"line_column",
"]",
",",
"markerString",
",",
"line_str",
"[",
"line_column",
":",
"]",
")",
")",
"return",
"line_str",
".",
"strip",
"(",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py#L248-L257
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/stc.py
|
python
|
StyledTextCtrl.StyleSetCase
|
(*args, **kwargs)
|
return _stc.StyledTextCtrl_StyleSetCase(*args, **kwargs)
|
StyleSetCase(self, int style, int caseForce)
Set a style to be mixed case, or to force upper or lower case.
|
StyleSetCase(self, int style, int caseForce)
|
[
"StyleSetCase",
"(",
"self",
"int",
"style",
"int",
"caseForce",
")"
] |
def StyleSetCase(*args, **kwargs):
"""
StyleSetCase(self, int style, int caseForce)
Set a style to be mixed case, or to force upper or lower case.
"""
return _stc.StyledTextCtrl_StyleSetCase(*args, **kwargs)
|
[
"def",
"StyleSetCase",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_StyleSetCase",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L2691-L2697
|
|
maidsafe-archive/MaidSafe
|
defd65e1c8cfb6a1cbdeaaa0eee31d065421792d
|
tools/cpplint.py
|
python
|
_ClassifyInclude
|
(fileinfo, include, is_system)
|
return _OTHER_HEADER
|
Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER
|
Figures out what kind of header 'include' is.
|
[
"Figures",
"out",
"what",
"kind",
"of",
"header",
"include",
"is",
"."
] |
def _ClassifyInclude(fileinfo, include, is_system):
"""Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER
"""
# This is a list of all standard c++ header files, except
# those already checked for above.
is_stl_h = include in _STL_HEADERS
is_cpp_h = is_stl_h or include in _CPP_HEADERS
if is_system:
if is_cpp_h:
return _CPP_SYS_HEADER
else:
return _C_SYS_HEADER
# If the target file and the include we're checking share a
# basename when we drop common extensions, and the include
# lives in . , then it's likely to be owned by the target file.
target_dir, target_base = (
os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
if target_base == include_base and (
include_dir == target_dir or
include_dir == os.path.normpath(target_dir + '/../public')):
return _LIKELY_MY_HEADER
# If the target and include share some initial basename
# component, it's possible the target is implementing the
# include, so it's allowed to be first, but we'll never
# complain if it's not there.
target_first_component = _RE_FIRST_COMPONENT.match(target_base)
include_first_component = _RE_FIRST_COMPONENT.match(include_base)
if (target_first_component and include_first_component and
target_first_component.group(0) ==
include_first_component.group(0)):
return _POSSIBLE_MY_HEADER
return _OTHER_HEADER
|
[
"def",
"_ClassifyInclude",
"(",
"fileinfo",
",",
"include",
",",
"is_system",
")",
":",
"# This is a list of all standard c++ header files, except",
"# those already checked for above.",
"is_stl_h",
"=",
"include",
"in",
"_STL_HEADERS",
"is_cpp_h",
"=",
"is_stl_h",
"or",
"include",
"in",
"_CPP_HEADERS",
"if",
"is_system",
":",
"if",
"is_cpp_h",
":",
"return",
"_CPP_SYS_HEADER",
"else",
":",
"return",
"_C_SYS_HEADER",
"# If the target file and the include we're checking share a",
"# basename when we drop common extensions, and the include",
"# lives in . , then it's likely to be owned by the target file.",
"target_dir",
",",
"target_base",
"=",
"(",
"os",
".",
"path",
".",
"split",
"(",
"_DropCommonSuffixes",
"(",
"fileinfo",
".",
"RepositoryName",
"(",
")",
")",
")",
")",
"include_dir",
",",
"include_base",
"=",
"os",
".",
"path",
".",
"split",
"(",
"_DropCommonSuffixes",
"(",
"include",
")",
")",
"if",
"target_base",
"==",
"include_base",
"and",
"(",
"include_dir",
"==",
"target_dir",
"or",
"include_dir",
"==",
"os",
".",
"path",
".",
"normpath",
"(",
"target_dir",
"+",
"'/../public'",
")",
")",
":",
"return",
"_LIKELY_MY_HEADER",
"# If the target and include share some initial basename",
"# component, it's possible the target is implementing the",
"# include, so it's allowed to be first, but we'll never",
"# complain if it's not there.",
"target_first_component",
"=",
"_RE_FIRST_COMPONENT",
".",
"match",
"(",
"target_base",
")",
"include_first_component",
"=",
"_RE_FIRST_COMPONENT",
".",
"match",
"(",
"include_base",
")",
"if",
"(",
"target_first_component",
"and",
"include_first_component",
"and",
"target_first_component",
".",
"group",
"(",
"0",
")",
"==",
"include_first_component",
".",
"group",
"(",
"0",
")",
")",
":",
"return",
"_POSSIBLE_MY_HEADER",
"return",
"_OTHER_HEADER"
] |
https://github.com/maidsafe-archive/MaidSafe/blob/defd65e1c8cfb6a1cbdeaaa0eee31d065421792d/tools/cpplint.py#L2966-L3023
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py
|
python
|
RequestsCookieJar.get_dict
|
(self, domain=None, path=None)
|
return dictionary
|
Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.
:rtype: dict
|
Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.
|
[
"Takes",
"as",
"an",
"argument",
"an",
"optional",
"domain",
"and",
"path",
"and",
"returns",
"a",
"plain",
"old",
"Python",
"dict",
"of",
"name",
"-",
"value",
"pairs",
"of",
"cookies",
"that",
"meet",
"the",
"requirements",
"."
] |
def get_dict(self, domain=None, path=None):
"""Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.
:rtype: dict
"""
dictionary = {}
for cookie in iter(self):
if (
(domain is None or cookie.domain == domain) and
(path is None or cookie.path == path)
):
dictionary[cookie.name] = cookie.value
return dictionary
|
[
"def",
"get_dict",
"(",
"self",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"dictionary",
"=",
"{",
"}",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"if",
"(",
"(",
"domain",
"is",
"None",
"or",
"cookie",
".",
"domain",
"==",
"domain",
")",
"and",
"(",
"path",
"is",
"None",
"or",
"cookie",
".",
"path",
"==",
"path",
")",
")",
":",
"dictionary",
"[",
"cookie",
".",
"name",
"]",
"=",
"cookie",
".",
"value",
"return",
"dictionary"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py#L299-L313
|
|
giuspen/cherrytree
|
84712f206478fcf9acf30174009ad28c648c6344
|
pygtk2/modules/exports.py
|
python
|
Export2Html.nodes_all_export_to_html_iter
|
(self, tree_iter)
|
Export All Nodes To HTML - iter
|
Export All Nodes To HTML - iter
|
[
"Export",
"All",
"Nodes",
"To",
"HTML",
"-",
"iter"
] |
def nodes_all_export_to_html_iter(self, tree_iter):
"""Export All Nodes To HTML - iter"""
self.node_export_to_html(tree_iter)
child_tree_iter = self.dad.treestore.iter_children(tree_iter)
while child_tree_iter:
self.nodes_all_export_to_html_iter(child_tree_iter)
child_tree_iter = self.dad.treestore.iter_next(child_tree_iter)
|
[
"def",
"nodes_all_export_to_html_iter",
"(",
"self",
",",
"tree_iter",
")",
":",
"self",
".",
"node_export_to_html",
"(",
"tree_iter",
")",
"child_tree_iter",
"=",
"self",
".",
"dad",
".",
"treestore",
".",
"iter_children",
"(",
"tree_iter",
")",
"while",
"child_tree_iter",
":",
"self",
".",
"nodes_all_export_to_html_iter",
"(",
"child_tree_iter",
")",
"child_tree_iter",
"=",
"self",
".",
"dad",
".",
"treestore",
".",
"iter_next",
"(",
"child_tree_iter",
")"
] |
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/exports.py#L639-L645
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.