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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/decimal.py | python | _dec_from_triple | (sign, coefficient, exponent, special=False) | return self | Create a decimal instance directly, without any validation,
normalization (e.g. removal of leading zeros) or argument
conversion.
This function is for *internal use only*. | Create a decimal instance directly, without any validation,
normalization (e.g. removal of leading zeros) or argument
conversion. | [
"Create",
"a",
"decimal",
"instance",
"directly",
"without",
"any",
"validation",
"normalization",
"(",
"e",
".",
"g",
".",
"removal",
"of",
"leading",
"zeros",
")",
"or",
"argument",
"conversion",
"."
] | def _dec_from_triple(sign, coefficient, exponent, special=False):
"""Create a decimal instance directly, without any validation,
normalization (e.g. removal of leading zeros) or argument
conversion.
This function is for *internal use only*.
"""
self = object.__new__(Decimal)
self._sign = sign
self._int = coefficient
self._exp = exponent
self._is_special = special
return self | [
"def",
"_dec_from_triple",
"(",
"sign",
",",
"coefficient",
",",
"exponent",
",",
"special",
"=",
"False",
")",
":",
"self",
"=",
"object",
".",
"__new__",
"(",
"Decimal",
")",
"self",
".",
"_sign",
"=",
"sign",
"self",
".",
"_int",
"=",
"coefficient",
"self",
".",
"_exp",
"=",
"exponent",
"self",
".",
"_is_special",
"=",
"special",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L3724-L3738 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | FontEnumerator_GetFacenames | (*args) | return _gdi_.FontEnumerator_GetFacenames(*args) | FontEnumerator_GetFacenames() -> PyObject | FontEnumerator_GetFacenames() -> PyObject | [
"FontEnumerator_GetFacenames",
"()",
"-",
">",
"PyObject"
] | def FontEnumerator_GetFacenames(*args):
"""FontEnumerator_GetFacenames() -> PyObject"""
return _gdi_.FontEnumerator_GetFacenames(*args) | [
"def",
"FontEnumerator_GetFacenames",
"(",
"*",
"args",
")",
":",
"return",
"_gdi_",
".",
"FontEnumerator_GetFacenames",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L2695-L2697 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/input.py | python | BuildTargetsDict | (data) | return targets | Builds a dict mapping fully-qualified target names to their target dicts.
|data| is a dict mapping loaded build files by pathname relative to the
current directory. Values in |data| are build file contents. For each
|data| value with a "targets" key, the value of the "targets" key is taken
as a list containing target dicts. Each target's fully-qualified name is
constructed from the pathname of the build file (|data| key) and its
"target_name" property. These fully-qualified names are used as the keys
in the returned dict. These keys provide access to the target dicts,
the dicts in the "targets" lists. | Builds a dict mapping fully-qualified target names to their target dicts. | [
"Builds",
"a",
"dict",
"mapping",
"fully",
"-",
"qualified",
"target",
"names",
"to",
"their",
"target",
"dicts",
"."
] | def BuildTargetsDict(data):
"""Builds a dict mapping fully-qualified target names to their target dicts.
|data| is a dict mapping loaded build files by pathname relative to the
current directory. Values in |data| are build file contents. For each
|data| value with a "targets" key, the value of the "targets" key is taken
as a list containing target dicts. Each target's fully-qualified name is
constructed from the pathname of the build file (|data| key) and its
"target_name" property. These fully-qualified names are used as the keys
in the returned dict. These keys provide access to the target dicts,
the dicts in the "targets" lists.
"""
targets = {}
for build_file in data['target_build_files']:
for target in data[build_file].get('targets', []):
target_name = gyp.common.QualifiedTarget(build_file,
target['target_name'],
target['toolset'])
if target_name in targets:
raise GypError('Duplicate target definitions for ' + target_name)
targets[target_name] = target
return targets | [
"def",
"BuildTargetsDict",
"(",
"data",
")",
":",
"targets",
"=",
"{",
"}",
"for",
"build_file",
"in",
"data",
"[",
"'target_build_files'",
"]",
":",
"for",
"target",
"in",
"data",
"[",
"build_file",
"]",
".",
"get",
"(",
"'targets'",
",",
"[",
"]",
")",
":",
"target_name",
"=",
"gyp",
".",
"common",
".",
"QualifiedTarget",
"(",
"build_file",
",",
"target",
"[",
"'target_name'",
"]",
",",
"target",
"[",
"'toolset'",
"]",
")",
"if",
"target_name",
"in",
"targets",
":",
"raise",
"GypError",
"(",
"'Duplicate target definitions for '",
"+",
"target_name",
")",
"targets",
"[",
"target_name",
"]",
"=",
"target",
"return",
"targets"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/input.py#L1333-L1356 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/order.py | python | Order.symbol | (self, symbol) | Sets the symbol of this Order.
:param symbol: The symbol of this Order. # noqa: E501
:type: str | Sets the symbol of this Order. | [
"Sets",
"the",
"symbol",
"of",
"this",
"Order",
"."
] | def symbol(self, symbol):
"""Sets the symbol of this Order.
:param symbol: The symbol of this Order. # noqa: E501
:type: str
"""
self._symbol = symbol | [
"def",
"symbol",
"(",
"self",
",",
"symbol",
")",
":",
"self",
".",
"_symbol",
"=",
"symbol"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/order.py#L306-L314 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/ndarray/ndarray.py | python | NDArray.__lt__ | (self, other) | return lesser(self, other) | x.__lt__(y) <=> x<y <=> mx.nd.lesser(x, y) | x.__lt__(y) <=> x<y <=> mx.nd.lesser(x, y) | [
"x",
".",
"__lt__",
"(",
"y",
")",
"<",
"=",
">",
"x<y",
"<",
"=",
">",
"mx",
".",
"nd",
".",
"lesser",
"(",
"x",
"y",
")"
] | def __lt__(self, other):
"""x.__lt__(y) <=> x<y <=> mx.nd.lesser(x, y) """
return lesser(self, other) | [
"def",
"__lt__",
"(",
"self",
",",
"other",
")",
":",
"return",
"lesser",
"(",
"self",
",",
"other",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L342-L344 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/concept.py | python | ConceptDomain.replace_concept | (self, concept, new) | concept is a concept name, and new is a list of names to replace it with | concept is a concept name, and new is a list of names to replace it with | [
"concept",
"is",
"a",
"concept",
"name",
"and",
"new",
"is",
"a",
"list",
"of",
"names",
"to",
"replace",
"it",
"with"
] | def replace_concept(self, concept, new):
"""
concept is a concept name, and new is a list of names to replace it with
"""
for k, v in self.concepts.iteritems():
if not isinstance(v,Concept) and not isinstance(v,ConceptSet):
self.concepts[k] = _replace_name(v, concept, new)
self.combinations = [
combination[:1] + tuple(_replace_name(x, concept, new) for x in combination[1:])
for combination in self.combinations
] | [
"def",
"replace_concept",
"(",
"self",
",",
"concept",
",",
"new",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"concepts",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"Concept",
")",
"and",
"not",
"isinstance",
"(",
"v",
",",
"ConceptSet",
")",
":",
"self",
".",
"concepts",
"[",
"k",
"]",
"=",
"_replace_name",
"(",
"v",
",",
"concept",
",",
"new",
")",
"self",
".",
"combinations",
"=",
"[",
"combination",
"[",
":",
"1",
"]",
"+",
"tuple",
"(",
"_replace_name",
"(",
"x",
",",
"concept",
",",
"new",
")",
"for",
"x",
"in",
"combination",
"[",
"1",
":",
"]",
")",
"for",
"combination",
"in",
"self",
".",
"combinations",
"]"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/concept.py#L317-L327 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/layers/tensor.py | python | has_nan | (x) | return out | Test if any of x contains a NAN
Args:
x (Tensor): The Tensor to be checked.
Returns:
Tensor: The tensor variable storing the output, only a bool value, indicating that whether there is NAN in x or not.
Examples:
.. code-block:: python
import paddle
data = paddle.randn(shape=[2,3], dtype="float32")
res = paddle.fluid.layers.has_nan(data)
# [False] | Test if any of x contains a NAN | [
"Test",
"if",
"any",
"of",
"x",
"contains",
"a",
"NAN"
] | def has_nan(x):
"""
Test if any of x contains a NAN
Args:
x (Tensor): The Tensor to be checked.
Returns:
Tensor: The tensor variable storing the output, only a bool value, indicating that whether there is NAN in x or not.
Examples:
.. code-block:: python
import paddle
data = paddle.randn(shape=[2,3], dtype="float32")
res = paddle.fluid.layers.has_nan(data)
# [False]
"""
if in_dygraph_mode():
return _C_ops.isnan(x)
check_type(x, 'x', (Variable), 'has_nan')
helper = LayerHelper("isnan", **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(type="isnan", inputs={"X": x}, outputs={"Out": out})
return out | [
"def",
"has_nan",
"(",
"x",
")",
":",
"if",
"in_dygraph_mode",
"(",
")",
":",
"return",
"_C_ops",
".",
"isnan",
"(",
"x",
")",
"check_type",
"(",
"x",
",",
"'x'",
",",
"(",
"Variable",
")",
",",
"'has_nan'",
")",
"helper",
"=",
"LayerHelper",
"(",
"\"isnan\"",
",",
"*",
"*",
"locals",
"(",
")",
")",
"out",
"=",
"helper",
".",
"create_variable_for_type_inference",
"(",
"dtype",
"=",
"x",
".",
"dtype",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"isnan\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"x",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"out",
"}",
")",
"return",
"out"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/tensor.py#L1309-L1335 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/qt4.py | python | qxx.add_moc_tasks | (self) | Create the moc tasks by looking in ``bld.raw_deps[self.uid()]`` | Create the moc tasks by looking in ``bld.raw_deps[self.uid()]`` | [
"Create",
"the",
"moc",
"tasks",
"by",
"looking",
"in",
"bld",
".",
"raw_deps",
"[",
"self",
".",
"uid",
"()",
"]"
] | def add_moc_tasks(self):
"""
Create the moc tasks by looking in ``bld.raw_deps[self.uid()]``
"""
node = self.inputs[0]
bld = self.generator.bld
try:
# compute the signature once to know if there is a moc file to create
self.signature()
except KeyError:
# the moc file may be referenced somewhere else
pass
else:
# remove the signature, it must be recomputed with the moc task
delattr(self, 'cache_sig')
moctasks=[]
mocfiles=[]
try:
tmp_lst = bld.raw_deps[self.uid()]
bld.raw_deps[self.uid()] = []
except KeyError:
tmp_lst = []
for d in tmp_lst:
if not d.endswith('.moc'):
continue
# paranoid check
if d in mocfiles:
Logs.error("paranoia owns")
continue
# process that base.moc only once
mocfiles.append(d)
# find the extension - this search is done only once
h_node = None
try: ext = Options.options.qt_header_ext.split()
except AttributeError: pass
if not ext: ext = MOC_H
base2 = d[:-4]
for x in [node.parent] + self.generator.includes_nodes:
for e in ext:
h_node = x.find_node(base2 + e)
if h_node:
break
if h_node:
m_node = h_node.change_ext('.moc')
break
else:
for k in EXT_QT4:
if base2.endswith(k):
for x in [node.parent] + self.generator.includes_nodes:
h_node = x.find_node(base2)
if h_node:
break
if h_node:
m_node = h_node.change_ext(k + '.moc')
break
if not h_node:
raise Errors.WafError('no header found for %r which is a moc file' % d)
# next time we will not search for the extension (look at the 'for' loop below)
bld.node_deps[(self.inputs[0].parent.abspath(), m_node.name)] = h_node
# create the task
task = self.create_moc_task(h_node, m_node)
moctasks.append(task)
# remove raw deps except the moc files to save space (optimization)
tmp_lst = bld.raw_deps[self.uid()] = mocfiles
# look at the file inputs, it is set right above
lst = bld.node_deps.get(self.uid(), ())
for d in lst:
name = d.name
if name.endswith('.moc'):
task = self.create_moc_task(bld.node_deps[(self.inputs[0].parent.abspath(), name)], d)
moctasks.append(task)
# simple scheduler dependency: run the moc task before others
self.run_after.update(set(moctasks))
self.moc_done = 1 | [
"def",
"add_moc_tasks",
"(",
"self",
")",
":",
"node",
"=",
"self",
".",
"inputs",
"[",
"0",
"]",
"bld",
"=",
"self",
".",
"generator",
".",
"bld",
"try",
":",
"# compute the signature once to know if there is a moc file to create",
"self",
".",
"signature",
"(",
")",
"except",
"KeyError",
":",
"# the moc file may be referenced somewhere else",
"pass",
"else",
":",
"# remove the signature, it must be recomputed with the moc task",
"delattr",
"(",
"self",
",",
"'cache_sig'",
")",
"moctasks",
"=",
"[",
"]",
"mocfiles",
"=",
"[",
"]",
"try",
":",
"tmp_lst",
"=",
"bld",
".",
"raw_deps",
"[",
"self",
".",
"uid",
"(",
")",
"]",
"bld",
".",
"raw_deps",
"[",
"self",
".",
"uid",
"(",
")",
"]",
"=",
"[",
"]",
"except",
"KeyError",
":",
"tmp_lst",
"=",
"[",
"]",
"for",
"d",
"in",
"tmp_lst",
":",
"if",
"not",
"d",
".",
"endswith",
"(",
"'.moc'",
")",
":",
"continue",
"# paranoid check",
"if",
"d",
"in",
"mocfiles",
":",
"Logs",
".",
"error",
"(",
"\"paranoia owns\"",
")",
"continue",
"# process that base.moc only once",
"mocfiles",
".",
"append",
"(",
"d",
")",
"# find the extension - this search is done only once",
"h_node",
"=",
"None",
"try",
":",
"ext",
"=",
"Options",
".",
"options",
".",
"qt_header_ext",
".",
"split",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"if",
"not",
"ext",
":",
"ext",
"=",
"MOC_H",
"base2",
"=",
"d",
"[",
":",
"-",
"4",
"]",
"for",
"x",
"in",
"[",
"node",
".",
"parent",
"]",
"+",
"self",
".",
"generator",
".",
"includes_nodes",
":",
"for",
"e",
"in",
"ext",
":",
"h_node",
"=",
"x",
".",
"find_node",
"(",
"base2",
"+",
"e",
")",
"if",
"h_node",
":",
"break",
"if",
"h_node",
":",
"m_node",
"=",
"h_node",
".",
"change_ext",
"(",
"'.moc'",
")",
"break",
"else",
":",
"for",
"k",
"in",
"EXT_QT4",
":",
"if",
"base2",
".",
"endswith",
"(",
"k",
")",
":",
"for",
"x",
"in",
"[",
"node",
".",
"parent",
"]",
"+",
"self",
".",
"generator",
".",
"includes_nodes",
":",
"h_node",
"=",
"x",
".",
"find_node",
"(",
"base2",
")",
"if",
"h_node",
":",
"break",
"if",
"h_node",
":",
"m_node",
"=",
"h_node",
".",
"change_ext",
"(",
"k",
"+",
"'.moc'",
")",
"break",
"if",
"not",
"h_node",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"'no header found for %r which is a moc file'",
"%",
"d",
")",
"# next time we will not search for the extension (look at the 'for' loop below)",
"bld",
".",
"node_deps",
"[",
"(",
"self",
".",
"inputs",
"[",
"0",
"]",
".",
"parent",
".",
"abspath",
"(",
")",
",",
"m_node",
".",
"name",
")",
"]",
"=",
"h_node",
"# create the task",
"task",
"=",
"self",
".",
"create_moc_task",
"(",
"h_node",
",",
"m_node",
")",
"moctasks",
".",
"append",
"(",
"task",
")",
"# remove raw deps except the moc files to save space (optimization)",
"tmp_lst",
"=",
"bld",
".",
"raw_deps",
"[",
"self",
".",
"uid",
"(",
")",
"]",
"=",
"mocfiles",
"# look at the file inputs, it is set right above",
"lst",
"=",
"bld",
".",
"node_deps",
".",
"get",
"(",
"self",
".",
"uid",
"(",
")",
",",
"(",
")",
")",
"for",
"d",
"in",
"lst",
":",
"name",
"=",
"d",
".",
"name",
"if",
"name",
".",
"endswith",
"(",
"'.moc'",
")",
":",
"task",
"=",
"self",
".",
"create_moc_task",
"(",
"bld",
".",
"node_deps",
"[",
"(",
"self",
".",
"inputs",
"[",
"0",
"]",
".",
"parent",
".",
"abspath",
"(",
")",
",",
"name",
")",
"]",
",",
"d",
")",
"moctasks",
".",
"append",
"(",
"task",
")",
"# simple scheduler dependency: run the moc task before others",
"self",
".",
"run_after",
".",
"update",
"(",
"set",
"(",
"moctasks",
")",
")",
"self",
".",
"moc_done",
"=",
"1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/qt4.py#L177-L260 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py | python | NeuralNetworkBuilder.add_floor_div_broadcastable | (self, name, input_names, output_name) | return spec_layer | Add a floor_div_broadcastable layer to the model that performs floor
division operation with broadcast support.
Refer to the **FloorDivBroadcastableLayerParams** message in specification (NeuralNetwork.proto) for more details.
Parameters
----------
name: str
The name of this layer.
input_names: list of str
The input blob names of this layer.
output_name: str
The output blob name of this layer.
See Also
--------
add_divide_broadcastable | Add a floor_div_broadcastable layer to the model that performs floor
division operation with broadcast support.
Refer to the **FloorDivBroadcastableLayerParams** message in specification (NeuralNetwork.proto) for more details. | [
"Add",
"a",
"floor_div_broadcastable",
"layer",
"to",
"the",
"model",
"that",
"performs",
"floor",
"division",
"operation",
"with",
"broadcast",
"support",
".",
"Refer",
"to",
"the",
"**",
"FloorDivBroadcastableLayerParams",
"**",
"message",
"in",
"specification",
"(",
"NeuralNetwork",
".",
"proto",
")",
"for",
"more",
"details",
"."
] | def add_floor_div_broadcastable(self, name, input_names, output_name):
"""
Add a floor_div_broadcastable layer to the model that performs floor
division operation with broadcast support.
Refer to the **FloorDivBroadcastableLayerParams** message in specification (NeuralNetwork.proto) for more details.
Parameters
----------
name: str
The name of this layer.
input_names: list of str
The input blob names of this layer.
output_name: str
The output blob name of this layer.
See Also
--------
add_divide_broadcastable
"""
spec_layer = self._add_generic_layer(name, input_names, [output_name])
spec_layer.floorDivBroadcastable.MergeFromString(b"")
self._set_max_input_rank(input_names, output_name)
return spec_layer | [
"def",
"add_floor_div_broadcastable",
"(",
"self",
",",
"name",
",",
"input_names",
",",
"output_name",
")",
":",
"spec_layer",
"=",
"self",
".",
"_add_generic_layer",
"(",
"name",
",",
"input_names",
",",
"[",
"output_name",
"]",
")",
"spec_layer",
".",
"floorDivBroadcastable",
".",
"MergeFromString",
"(",
"b\"\"",
")",
"self",
".",
"_set_max_input_rank",
"(",
"input_names",
",",
"output_name",
")",
"return",
"spec_layer"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L5119-L5142 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | DC.StartPage | (*args, **kwargs) | return _gdi_.DC_StartPage(*args, **kwargs) | StartPage(self)
Starts a document page (only relevant when outputting to a printer). | StartPage(self) | [
"StartPage",
"(",
"self",
")"
] | def StartPage(*args, **kwargs):
"""
StartPage(self)
Starts a document page (only relevant when outputting to a printer).
"""
return _gdi_.DC_StartPage(*args, **kwargs) | [
"def",
"StartPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_StartPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3990-L3996 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/layers/recurrent.py | python | _generate_zero_filled_state | (batch_size_tensor, state_size, dtype) | Generate a zero filled tensor with shape [batch_size, state_size]. | Generate a zero filled tensor with shape [batch_size, state_size]. | [
"Generate",
"a",
"zero",
"filled",
"tensor",
"with",
"shape",
"[",
"batch_size",
"state_size",
"]",
"."
] | def _generate_zero_filled_state(batch_size_tensor, state_size, dtype):
"""Generate a zero filled tensor with shape [batch_size, state_size]."""
if batch_size_tensor is None or dtype is None:
raise ValueError(
'batch_size and dtype cannot be None while constructing initial state: '
'batch_size={}, dtype={}'.format(batch_size_tensor, dtype))
def create_zeros(unnested_state_size):
flat_dims = tensor_shape.TensorShape(unnested_state_size).as_list()
init_state_size = [batch_size_tensor] + flat_dims
return array_ops.zeros(init_state_size, dtype=dtype)
if nest.is_nested(state_size):
return nest.map_structure(create_zeros, state_size)
else:
return create_zeros(state_size) | [
"def",
"_generate_zero_filled_state",
"(",
"batch_size_tensor",
",",
"state_size",
",",
"dtype",
")",
":",
"if",
"batch_size_tensor",
"is",
"None",
"or",
"dtype",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'batch_size and dtype cannot be None while constructing initial state: '",
"'batch_size={}, dtype={}'",
".",
"format",
"(",
"batch_size_tensor",
",",
"dtype",
")",
")",
"def",
"create_zeros",
"(",
"unnested_state_size",
")",
":",
"flat_dims",
"=",
"tensor_shape",
".",
"TensorShape",
"(",
"unnested_state_size",
")",
".",
"as_list",
"(",
")",
"init_state_size",
"=",
"[",
"batch_size_tensor",
"]",
"+",
"flat_dims",
"return",
"array_ops",
".",
"zeros",
"(",
"init_state_size",
",",
"dtype",
"=",
"dtype",
")",
"if",
"nest",
".",
"is_nested",
"(",
"state_size",
")",
":",
"return",
"nest",
".",
"map_structure",
"(",
"create_zeros",
",",
"state_size",
")",
"else",
":",
"return",
"create_zeros",
"(",
"state_size",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/layers/recurrent.py#L3010-L3025 | ||
JoseExposito/touchegg | 1f3fda214358d071c05da4bf17c070c33d67b5eb | cmake/cpplint.py | python | _SetVerboseLevel | (level) | return _cpplint_state.SetVerboseLevel(level) | Sets the module's verbosity, and returns the previous setting. | Sets the module's verbosity, and returns the previous setting. | [
"Sets",
"the",
"module",
"s",
"verbosity",
"and",
"returns",
"the",
"previous",
"setting",
"."
] | def _SetVerboseLevel(level):
"""Sets the module's verbosity, and returns the previous setting."""
return _cpplint_state.SetVerboseLevel(level) | [
"def",
"_SetVerboseLevel",
"(",
"level",
")",
":",
"return",
"_cpplint_state",
".",
"SetVerboseLevel",
"(",
"level",
")"
] | https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L986-L988 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/spatial/_spherical_voronoi.py | python | SphericalVoronoi._calc_vertices_regions | (self) | Calculates the Voronoi vertices and regions of the generators stored
in self.points. The vertices will be stored in self.vertices and the
regions in self.regions.
This algorithm was discussed at PyData London 2015 by
Tyler Reddy, Ross Hemsley and Nikolai Nowaczyk | Calculates the Voronoi vertices and regions of the generators stored
in self.points. The vertices will be stored in self.vertices and the
regions in self.regions. | [
"Calculates",
"the",
"Voronoi",
"vertices",
"and",
"regions",
"of",
"the",
"generators",
"stored",
"in",
"self",
".",
"points",
".",
"The",
"vertices",
"will",
"be",
"stored",
"in",
"self",
".",
"vertices",
"and",
"the",
"regions",
"in",
"self",
".",
"regions",
"."
] | def _calc_vertices_regions(self):
"""
Calculates the Voronoi vertices and regions of the generators stored
in self.points. The vertices will be stored in self.vertices and the
regions in self.regions.
This algorithm was discussed at PyData London 2015 by
Tyler Reddy, Ross Hemsley and Nikolai Nowaczyk
"""
# perform 3D Delaunay triangulation on data set
# (here ConvexHull can also be used, and is faster)
self._tri = scipy.spatial.ConvexHull(self.points)
# add the center to each of the simplices in tri to get the same
# tetrahedrons we'd have gotten from Delaunay tetrahedralization
tetrahedrons = self._tri.points[self._tri.simplices]
tetrahedrons = np.insert(
tetrahedrons,
3,
np.array([self.center]),
axis=1
)
# produce circumcenters of tetrahedrons from 3D Delaunay
circumcenters = calc_circumcenters(tetrahedrons)
# project tetrahedron circumcenters to the surface of the sphere
self.vertices = project_to_sphere(
circumcenters,
self.center,
self.radius
)
# calculate regions from triangulation
generator_indices = np.arange(self.points.shape[0])
filter_tuple = np.where((np.expand_dims(self._tri.simplices,
-1) == generator_indices).any(axis=1))
list_tuples_associations = zip(filter_tuple[1],
filter_tuple[0])
list_tuples_associations = sorted(list_tuples_associations,
key=lambda t: t[0])
# group by generator indices to produce
# unsorted regions in nested list
groups = []
for k, g in itertools.groupby(list_tuples_associations,
lambda t: t[0]):
groups.append([element[1] for element in list(g)])
self.regions = groups | [
"def",
"_calc_vertices_regions",
"(",
"self",
")",
":",
"# perform 3D Delaunay triangulation on data set",
"# (here ConvexHull can also be used, and is faster)",
"self",
".",
"_tri",
"=",
"scipy",
".",
"spatial",
".",
"ConvexHull",
"(",
"self",
".",
"points",
")",
"# add the center to each of the simplices in tri to get the same",
"# tetrahedrons we'd have gotten from Delaunay tetrahedralization",
"tetrahedrons",
"=",
"self",
".",
"_tri",
".",
"points",
"[",
"self",
".",
"_tri",
".",
"simplices",
"]",
"tetrahedrons",
"=",
"np",
".",
"insert",
"(",
"tetrahedrons",
",",
"3",
",",
"np",
".",
"array",
"(",
"[",
"self",
".",
"center",
"]",
")",
",",
"axis",
"=",
"1",
")",
"# produce circumcenters of tetrahedrons from 3D Delaunay",
"circumcenters",
"=",
"calc_circumcenters",
"(",
"tetrahedrons",
")",
"# project tetrahedron circumcenters to the surface of the sphere",
"self",
".",
"vertices",
"=",
"project_to_sphere",
"(",
"circumcenters",
",",
"self",
".",
"center",
",",
"self",
".",
"radius",
")",
"# calculate regions from triangulation",
"generator_indices",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"points",
".",
"shape",
"[",
"0",
"]",
")",
"filter_tuple",
"=",
"np",
".",
"where",
"(",
"(",
"np",
".",
"expand_dims",
"(",
"self",
".",
"_tri",
".",
"simplices",
",",
"-",
"1",
")",
"==",
"generator_indices",
")",
".",
"any",
"(",
"axis",
"=",
"1",
")",
")",
"list_tuples_associations",
"=",
"zip",
"(",
"filter_tuple",
"[",
"1",
"]",
",",
"filter_tuple",
"[",
"0",
"]",
")",
"list_tuples_associations",
"=",
"sorted",
"(",
"list_tuples_associations",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")",
"# group by generator indices to produce",
"# unsorted regions in nested list",
"groups",
"=",
"[",
"]",
"for",
"k",
",",
"g",
"in",
"itertools",
".",
"groupby",
"(",
"list_tuples_associations",
",",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")",
":",
"groups",
".",
"append",
"(",
"[",
"element",
"[",
"1",
"]",
"for",
"element",
"in",
"list",
"(",
"g",
")",
"]",
")",
"self",
".",
"regions",
"=",
"groups"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/spatial/_spherical_voronoi.py#L231-L283 | ||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | tools/Polygraphy/polygraphy/tools/script.py | python | make_invocable | (type_str, *args, **kwargs) | return make_invocable_impl(type_str, *args, **kwargs)[0] | Creates a string representation that will invoke the specified object,
with the specified arguments.
Args:
type_str (str): A string representing the object that should be invoked.
args, kwargs:
Arguments to pass along to the object. If a keyword argument
is set to None, it will be omitted.
Returns:
str: A string representation that invokes the object specified.
Examples:
make_invocable("MyClass", 0, 1, last=3)
-> "MyClass(0, 1, last=3)"
make_invocable("my_func", 0, 1, last=None)
-> "my_func(0, 1)" | Creates a string representation that will invoke the specified object,
with the specified arguments. | [
"Creates",
"a",
"string",
"representation",
"that",
"will",
"invoke",
"the",
"specified",
"object",
"with",
"the",
"specified",
"arguments",
"."
] | def make_invocable(type_str, *args, **kwargs):
"""
Creates a string representation that will invoke the specified object,
with the specified arguments.
Args:
type_str (str): A string representing the object that should be invoked.
args, kwargs:
Arguments to pass along to the object. If a keyword argument
is set to None, it will be omitted.
Returns:
str: A string representation that invokes the object specified.
Examples:
make_invocable("MyClass", 0, 1, last=3)
-> "MyClass(0, 1, last=3)"
make_invocable("my_func", 0, 1, last=None)
-> "my_func(0, 1)"
"""
return make_invocable_impl(type_str, *args, **kwargs)[0] | [
"def",
"make_invocable",
"(",
"type_str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"make_invocable_impl",
"(",
"type_str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"[",
"0",
"]"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/Polygraphy/polygraphy/tools/script.py#L112-L133 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/labelbook.py | python | FlatBookBase.ChangeSelection | (self, page) | return oldPage | Changes the selection for the given page, returning the previous selection.
:param `page`: an integer specifying the page to be selected.
:note: The call to this function does not generate the page changing events. | Changes the selection for the given page, returning the previous selection. | [
"Changes",
"the",
"selection",
"for",
"the",
"given",
"page",
"returning",
"the",
"previous",
"selection",
"."
] | def ChangeSelection(self, page):
"""
Changes the selection for the given page, returning the previous selection.
:param `page`: an integer specifying the page to be selected.
:note: The call to this function does not generate the page changing events.
"""
if page < 0 or page >= self.GetPageCount():
return
oldPage = self.GetSelection()
self.DoSetSelection(page)
return oldPage | [
"def",
"ChangeSelection",
"(",
"self",
",",
"page",
")",
":",
"if",
"page",
"<",
"0",
"or",
"page",
">=",
"self",
".",
"GetPageCount",
"(",
")",
":",
"return",
"oldPage",
"=",
"self",
".",
"GetSelection",
"(",
")",
"self",
".",
"DoSetSelection",
"(",
"page",
")",
"return",
"oldPage"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/labelbook.py#L2820-L2835 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/base.py | python | TensorFlowEstimator.partial_fit | (self, x, y) | return self.fit(x, y) | Incremental fit on a batch of samples.
This method is expected to be called several times consecutively
on different or the same chunks of the dataset. This either can
implement iterative training or out-of-core/online training.
This is especially useful when the whole dataset is too big to
fit in memory at the same time. Or when model is taking long time
to converge, and you want to split up training into subparts.
Args:
x: matrix or tensor of shape [n_samples, n_features...]. Can be
iterator that returns arrays of features. The training input
samples for fitting the model.
y: vector or matrix [n_samples] or [n_samples, n_outputs]. Can be
iterator that returns array of targets. The training target values
(class label in classification, real numbers in regression).
Returns:
Returns self. | Incremental fit on a batch of samples. | [
"Incremental",
"fit",
"on",
"a",
"batch",
"of",
"samples",
"."
] | def partial_fit(self, x, y):
"""Incremental fit on a batch of samples.
This method is expected to be called several times consecutively
on different or the same chunks of the dataset. This either can
implement iterative training or out-of-core/online training.
This is especially useful when the whole dataset is too big to
fit in memory at the same time. Or when model is taking long time
to converge, and you want to split up training into subparts.
Args:
x: matrix or tensor of shape [n_samples, n_features...]. Can be
iterator that returns arrays of features. The training input
samples for fitting the model.
y: vector or matrix [n_samples] or [n_samples, n_outputs]. Can be
iterator that returns array of targets. The training target values
(class label in classification, real numbers in regression).
Returns:
Returns self.
"""
return self.fit(x, y) | [
"def",
"partial_fit",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"self",
".",
"fit",
"(",
"x",
",",
"y",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/base.py#L180-L201 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/function_base.py | python | corrcoef | (x, y=None, rowvar=1, bias=0, ddof=None) | return c/sqrt(multiply.outer(d, d)) | Return correlation coefficients.
Please refer to the documentation for `cov` for more detail. The
relationship between the correlation coefficient matrix, `P`, and the
covariance matrix, `C`, is
.. math:: P_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } }
The values of `P` are between -1 and 1, inclusive.
Parameters
----------
x : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `m` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same
shape as `m`.
rowvar : int, optional
If `rowvar` is non-zero (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : int, optional
Default normalization is by ``(N - 1)``, where ``N`` is the number of
observations (unbiased estimate). If `bias` is 1, then
normalization is by ``N``. These values can be overridden by using
the keyword ``ddof`` in numpy versions >= 1.5.
ddof : {None, int}, optional
.. versionadded:: 1.5
If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is
the number of observations; this overrides the value implied by
``bias``. The default value is ``None``.
Returns
-------
out : ndarray
The correlation coefficient matrix of the variables.
See Also
--------
cov : Covariance matrix | Return correlation coefficients. | [
"Return",
"correlation",
"coefficients",
"."
] | def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None):
"""
Return correlation coefficients.
Please refer to the documentation for `cov` for more detail. The
relationship between the correlation coefficient matrix, `P`, and the
covariance matrix, `C`, is
.. math:: P_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } }
The values of `P` are between -1 and 1, inclusive.
Parameters
----------
x : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `m` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same
shape as `m`.
rowvar : int, optional
If `rowvar` is non-zero (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : int, optional
Default normalization is by ``(N - 1)``, where ``N`` is the number of
observations (unbiased estimate). If `bias` is 1, then
normalization is by ``N``. These values can be overridden by using
the keyword ``ddof`` in numpy versions >= 1.5.
ddof : {None, int}, optional
.. versionadded:: 1.5
If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is
the number of observations; this overrides the value implied by
``bias``. The default value is ``None``.
Returns
-------
out : ndarray
The correlation coefficient matrix of the variables.
See Also
--------
cov : Covariance matrix
"""
c = cov(x, y, rowvar, bias, ddof)
if c.size == 0:
# handle empty arrays
return c
try:
d = diag(c)
except ValueError: # scalar covariance
return 1
return c/sqrt(multiply.outer(d, d)) | [
"def",
"corrcoef",
"(",
"x",
",",
"y",
"=",
"None",
",",
"rowvar",
"=",
"1",
",",
"bias",
"=",
"0",
",",
"ddof",
"=",
"None",
")",
":",
"c",
"=",
"cov",
"(",
"x",
",",
"y",
",",
"rowvar",
",",
"bias",
",",
"ddof",
")",
"if",
"c",
".",
"size",
"==",
"0",
":",
"# handle empty arrays",
"return",
"c",
"try",
":",
"d",
"=",
"diag",
"(",
"c",
")",
"except",
"ValueError",
":",
"# scalar covariance",
"return",
"1",
"return",
"c",
"/",
"sqrt",
"(",
"multiply",
".",
"outer",
"(",
"d",
",",
"d",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/function_base.py#L1769-L1824 | |
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | ppocr/data/imaug/sast_process.py | python | SASTProcessTrain.gen_min_area_quad_from_poly | (self, poly) | return min_area_quad, center_point | Generate min area quad from poly. | Generate min area quad from poly. | [
"Generate",
"min",
"area",
"quad",
"from",
"poly",
"."
] | def gen_min_area_quad_from_poly(self, poly):
"""
Generate min area quad from poly.
"""
point_num = poly.shape[0]
min_area_quad = np.zeros((4, 2), dtype=np.float32)
if point_num == 4:
min_area_quad = poly
center_point = np.sum(poly, axis=0) / 4
else:
rect = cv2.minAreaRect(poly.astype(
np.int32)) # (center (x,y), (width, height), angle of rotation)
center_point = rect[0]
box = np.array(cv2.boxPoints(rect))
first_point_idx = 0
min_dist = 1e4
for i in range(4):
dist = np.linalg.norm(box[(i + 0) % 4] - poly[0]) + \
np.linalg.norm(box[(i + 1) % 4] - poly[point_num // 2 - 1]) + \
np.linalg.norm(box[(i + 2) % 4] - poly[point_num // 2]) + \
np.linalg.norm(box[(i + 3) % 4] - poly[-1])
if dist < min_dist:
min_dist = dist
first_point_idx = i
for i in range(4):
min_area_quad[i] = box[(first_point_idx + i) % 4]
return min_area_quad, center_point | [
"def",
"gen_min_area_quad_from_poly",
"(",
"self",
",",
"poly",
")",
":",
"point_num",
"=",
"poly",
".",
"shape",
"[",
"0",
"]",
"min_area_quad",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"2",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"if",
"point_num",
"==",
"4",
":",
"min_area_quad",
"=",
"poly",
"center_point",
"=",
"np",
".",
"sum",
"(",
"poly",
",",
"axis",
"=",
"0",
")",
"/",
"4",
"else",
":",
"rect",
"=",
"cv2",
".",
"minAreaRect",
"(",
"poly",
".",
"astype",
"(",
"np",
".",
"int32",
")",
")",
"# (center (x,y), (width, height), angle of rotation)",
"center_point",
"=",
"rect",
"[",
"0",
"]",
"box",
"=",
"np",
".",
"array",
"(",
"cv2",
".",
"boxPoints",
"(",
"rect",
")",
")",
"first_point_idx",
"=",
"0",
"min_dist",
"=",
"1e4",
"for",
"i",
"in",
"range",
"(",
"4",
")",
":",
"dist",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"box",
"[",
"(",
"i",
"+",
"0",
")",
"%",
"4",
"]",
"-",
"poly",
"[",
"0",
"]",
")",
"+",
"np",
".",
"linalg",
".",
"norm",
"(",
"box",
"[",
"(",
"i",
"+",
"1",
")",
"%",
"4",
"]",
"-",
"poly",
"[",
"point_num",
"//",
"2",
"-",
"1",
"]",
")",
"+",
"np",
".",
"linalg",
".",
"norm",
"(",
"box",
"[",
"(",
"i",
"+",
"2",
")",
"%",
"4",
"]",
"-",
"poly",
"[",
"point_num",
"//",
"2",
"]",
")",
"+",
"np",
".",
"linalg",
".",
"norm",
"(",
"box",
"[",
"(",
"i",
"+",
"3",
")",
"%",
"4",
"]",
"-",
"poly",
"[",
"-",
"1",
"]",
")",
"if",
"dist",
"<",
"min_dist",
":",
"min_dist",
"=",
"dist",
"first_point_idx",
"=",
"i",
"for",
"i",
"in",
"range",
"(",
"4",
")",
":",
"min_area_quad",
"[",
"i",
"]",
"=",
"box",
"[",
"(",
"first_point_idx",
"+",
"i",
")",
"%",
"4",
"]",
"return",
"min_area_quad",
",",
"center_point"
] | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/data/imaug/sast_process.py#L427-L456 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/commands/check.py | python | command_line_options | (subparser, parent) | Define the 'check' command. | Define the 'check' command. | [
"Define",
"the",
"check",
"command",
"."
] | def command_line_options(subparser, parent):
"""Define the 'check' command."""
parser = subparser.add_parser('check',
parents=[parent],
help="Tool for performing SQA error checking and "
"creating/updating documentation stub pages.")
parser.add_argument('--config', type=str, default='sqa_reports.yml',
help="The YAML config file for performing SQA checks.")
parser.add_argument('--reports', nargs='+', default=['doc', 'req', 'app'], choices=['doc', 'req', 'app'],
help='Select the reports to produce.')
parser.add_argument('--show-warnings', action='store_true',
help='Display all report warnings.')
parser.add_argument('--generate', nargs='+', default=None, help='Deprecated')
parser.add_argument('--dump', nargs='+', default=None, help='Deprecated')
parser.add_argument('--app-reports', nargs='+', default=None,
help='Limit to the following application reports (e.g. --app-reports navier_stokes')
parser.add_argument('--req-reports', nargs='+', default=None,
help='Limit to the following requirement reports (e.g. --req-reports navier_stokes') | [
"def",
"command_line_options",
"(",
"subparser",
",",
"parent",
")",
":",
"parser",
"=",
"subparser",
".",
"add_parser",
"(",
"'check'",
",",
"parents",
"=",
"[",
"parent",
"]",
",",
"help",
"=",
"\"Tool for performing SQA error checking and \"",
"\"creating/updating documentation stub pages.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--config'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'sqa_reports.yml'",
",",
"help",
"=",
"\"The YAML config file for performing SQA checks.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--reports'",
",",
"nargs",
"=",
"'+'",
",",
"default",
"=",
"[",
"'doc'",
",",
"'req'",
",",
"'app'",
"]",
",",
"choices",
"=",
"[",
"'doc'",
",",
"'req'",
",",
"'app'",
"]",
",",
"help",
"=",
"'Select the reports to produce.'",
")",
"parser",
".",
"add_argument",
"(",
"'--show-warnings'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Display all report warnings.'",
")",
"parser",
".",
"add_argument",
"(",
"'--generate'",
",",
"nargs",
"=",
"'+'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Deprecated'",
")",
"parser",
".",
"add_argument",
"(",
"'--dump'",
",",
"nargs",
"=",
"'+'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Deprecated'",
")",
"parser",
".",
"add_argument",
"(",
"'--app-reports'",
",",
"nargs",
"=",
"'+'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Limit to the following application reports (e.g. --app-reports navier_stokes'",
")",
"parser",
".",
"add_argument",
"(",
"'--req-reports'",
",",
"nargs",
"=",
"'+'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Limit to the following requirement reports (e.g. --req-reports navier_stokes'",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/commands/check.py#L29-L51 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/ceph_manager.py | python | CephManager.revive_osd | (self, osd, timeout=360, skip_admin_check=False) | Revive osds by either power cycling (if indicated by the config)
or by restarting. | Revive osds by either power cycling (if indicated by the config)
or by restarting. | [
"Revive",
"osds",
"by",
"either",
"power",
"cycling",
"(",
"if",
"indicated",
"by",
"the",
"config",
")",
"or",
"by",
"restarting",
"."
] | def revive_osd(self, osd, timeout=360, skip_admin_check=False):
"""
Revive osds by either power cycling (if indicated by the config)
or by restarting.
"""
if self.config.get('powercycle'):
remote = self.find_remote('osd', osd)
self.log('kill_osd on osd.{o} doing powercycle of {s}'.
format(o=osd, s=remote.name))
self._assert_ipmi(remote)
remote.console.power_on()
if not remote.console.check_status(300):
raise Exception('Failed to revive osd.{o} via ipmi'.
format(o=osd))
teuthology.reconnect(self.ctx, 60, [remote])
mount_osd_data(self.ctx, remote, self.cluster, str(osd))
self.make_admin_daemon_dir(remote)
self.ctx.daemons.get_daemon('osd', osd, self.cluster).reset()
self.ctx.daemons.get_daemon('osd', osd, self.cluster).restart()
if not skip_admin_check:
# wait for dump_ops_in_flight; this command doesn't appear
# until after the signal handler is installed and it is safe
# to stop the osd again without making valgrind leak checks
# unhappy. see #5924.
self.wait_run_admin_socket('osd', osd,
args=['dump_ops_in_flight'],
timeout=timeout, stdout=DEVNULL) | [
"def",
"revive_osd",
"(",
"self",
",",
"osd",
",",
"timeout",
"=",
"360",
",",
"skip_admin_check",
"=",
"False",
")",
":",
"if",
"self",
".",
"config",
".",
"get",
"(",
"'powercycle'",
")",
":",
"remote",
"=",
"self",
".",
"find_remote",
"(",
"'osd'",
",",
"osd",
")",
"self",
".",
"log",
"(",
"'kill_osd on osd.{o} doing powercycle of {s}'",
".",
"format",
"(",
"o",
"=",
"osd",
",",
"s",
"=",
"remote",
".",
"name",
")",
")",
"self",
".",
"_assert_ipmi",
"(",
"remote",
")",
"remote",
".",
"console",
".",
"power_on",
"(",
")",
"if",
"not",
"remote",
".",
"console",
".",
"check_status",
"(",
"300",
")",
":",
"raise",
"Exception",
"(",
"'Failed to revive osd.{o} via ipmi'",
".",
"format",
"(",
"o",
"=",
"osd",
")",
")",
"teuthology",
".",
"reconnect",
"(",
"self",
".",
"ctx",
",",
"60",
",",
"[",
"remote",
"]",
")",
"mount_osd_data",
"(",
"self",
".",
"ctx",
",",
"remote",
",",
"self",
".",
"cluster",
",",
"str",
"(",
"osd",
")",
")",
"self",
".",
"make_admin_daemon_dir",
"(",
"remote",
")",
"self",
".",
"ctx",
".",
"daemons",
".",
"get_daemon",
"(",
"'osd'",
",",
"osd",
",",
"self",
".",
"cluster",
")",
".",
"reset",
"(",
")",
"self",
".",
"ctx",
".",
"daemons",
".",
"get_daemon",
"(",
"'osd'",
",",
"osd",
",",
"self",
".",
"cluster",
")",
".",
"restart",
"(",
")",
"if",
"not",
"skip_admin_check",
":",
"# wait for dump_ops_in_flight; this command doesn't appear",
"# until after the signal handler is installed and it is safe",
"# to stop the osd again without making valgrind leak checks",
"# unhappy. see #5924.",
"self",
".",
"wait_run_admin_socket",
"(",
"'osd'",
",",
"osd",
",",
"args",
"=",
"[",
"'dump_ops_in_flight'",
"]",
",",
"timeout",
"=",
"timeout",
",",
"stdout",
"=",
"DEVNULL",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph_manager.py#L2994-L3021 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/telnetlib.py | python | Telnet.mt_interact | (self) | Multithreaded version of interact(). | Multithreaded version of interact(). | [
"Multithreaded",
"version",
"of",
"interact",
"()",
"."
] | def mt_interact(self):
"""Multithreaded version of interact()."""
import _thread
_thread.start_new_thread(self.listener, ())
while 1:
line = sys.stdin.readline()
if not line:
break
self.write(line.encode('ascii')) | [
"def",
"mt_interact",
"(",
"self",
")",
":",
"import",
"_thread",
"_thread",
".",
"start_new_thread",
"(",
"self",
".",
"listener",
",",
"(",
")",
")",
"while",
"1",
":",
"line",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"self",
".",
"write",
"(",
"line",
".",
"encode",
"(",
"'ascii'",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/telnetlib.py#L561-L569 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py | python | SpectraToFoilPeriodMap.get_index | (self, spectrum_no, foil_state_no) | return foil_period_no - 1 | Returns an index that can be used to access the Workspace within
a WorkspaceGroup that corresponds to the foil state given
@param spectrum_no :: A spectrum number (1->nspectra)
@param foil_state_no :: A number between 1 & 6(inclusive) that defines which
foil state is required
@returns The index in a WorkspaceGroup that gives the associated Workspace | Returns an index that can be used to access the Workspace within
a WorkspaceGroup that corresponds to the foil state given | [
"Returns",
"an",
"index",
"that",
"can",
"be",
"used",
"to",
"access",
"the",
"Workspace",
"within",
"a",
"WorkspaceGroup",
"that",
"corresponds",
"to",
"the",
"foil",
"state",
"given"
] | def get_index(self, spectrum_no, foil_state_no):
"""Returns an index that can be used to access the Workspace within
a WorkspaceGroup that corresponds to the foil state given
@param spectrum_no :: A spectrum number (1->nspectra)
@param foil_state_no :: A number between 1 & 6(inclusive) that defines which
foil state is required
@returns The index in a WorkspaceGroup that gives the associated Workspace
"""
self._validate_foil_number(foil_state_no)
self._validate_spectrum_number(spectrum_no)
# For the back scattering banks or foil states > 6 then there is a 1:1 map
if foil_state_no > 6 or spectrum_no < 135:
foil_periods = self._one_to_one
elif (135 <= spectrum_no <= 142) or \
(151 <= spectrum_no <= 158) or \
(167 <= spectrum_no <= 174) or \
(183 <= spectrum_no <= 190):
# For each alternating forward scattering bank :: foil_in = 1,3,5, foil out = 2,4,6
foil_periods = self._odd_even
else:
# foil_in = 2,4,6 foil out = 1,3,5
foil_periods = self._even_odd
foil_period_no = foil_periods[foil_state_no]
return foil_period_no - 1 | [
"def",
"get_index",
"(",
"self",
",",
"spectrum_no",
",",
"foil_state_no",
")",
":",
"self",
".",
"_validate_foil_number",
"(",
"foil_state_no",
")",
"self",
".",
"_validate_spectrum_number",
"(",
"spectrum_no",
")",
"# For the back scattering banks or foil states > 6 then there is a 1:1 map",
"if",
"foil_state_no",
">",
"6",
"or",
"spectrum_no",
"<",
"135",
":",
"foil_periods",
"=",
"self",
".",
"_one_to_one",
"elif",
"(",
"135",
"<=",
"spectrum_no",
"<=",
"142",
")",
"or",
"(",
"151",
"<=",
"spectrum_no",
"<=",
"158",
")",
"or",
"(",
"167",
"<=",
"spectrum_no",
"<=",
"174",
")",
"or",
"(",
"183",
"<=",
"spectrum_no",
"<=",
"190",
")",
":",
"# For each alternating forward scattering bank :: foil_in = 1,3,5, foil out = 2,4,6",
"foil_periods",
"=",
"self",
".",
"_odd_even",
"else",
":",
"# foil_in = 2,4,6 foil out = 1,3,5",
"foil_periods",
"=",
"self",
".",
"_even_odd",
"foil_period_no",
"=",
"foil_periods",
"[",
"foil_state_no",
"]",
"return",
"foil_period_no",
"-",
"1"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py#L1136-L1162 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/motionplanning.py | python | CSpaceInterface.setNeighborhoodSampler | (self, pySamp: "PyObject *") | return _motionplanning.CSpaceInterface_setNeighborhoodSampler(self, pySamp) | r"""
setNeighborhoodSampler(CSpaceInterface self, PyObject * pySamp) | r"""
setNeighborhoodSampler(CSpaceInterface self, PyObject * pySamp) | [
"r",
"setNeighborhoodSampler",
"(",
"CSpaceInterface",
"self",
"PyObject",
"*",
"pySamp",
")"
] | def setNeighborhoodSampler(self, pySamp: "PyObject *") -> "void":
r"""
setNeighborhoodSampler(CSpaceInterface self, PyObject * pySamp)
"""
return _motionplanning.CSpaceInterface_setNeighborhoodSampler(self, pySamp) | [
"def",
"setNeighborhoodSampler",
"(",
"self",
",",
"pySamp",
":",
"\"PyObject *\"",
")",
"->",
"\"void\"",
":",
"return",
"_motionplanning",
".",
"CSpaceInterface_setNeighborhoodSampler",
"(",
"self",
",",
"pySamp",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/motionplanning.py#L550-L556 | |
schwehr/libais | 1e19605942c8e155cd02fde6d1acde75ecd15d75 | third_party/gmock/scripts/upload.py | python | AbstractRpcServer.Send | (self, request_path, payload=None,
content_type="application/octet-stream",
timeout=None,
**kwargs) | Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for large requests on OS X, the timeout doesn't work right.)
kwargs: Any keyword arguments are converted into query string parameters.
Returns:
The response body, as a string. | Sends an RPC and returns the response. | [
"Sends",
"an",
"RPC",
"and",
"returns",
"the",
"response",
"."
] | def Send(self, request_path, payload=None,
content_type="application/octet-stream",
timeout=None,
**kwargs):
"""Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for large requests on OS X, the timeout doesn't work right.)
kwargs: Any keyword arguments are converted into query string parameters.
Returns:
The response body, as a string.
"""
# TODO: Don't require authentication. Let the server say
# whether it is necessary.
if not self.authenticated:
self._Authenticate()
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeout)
try:
tries = 0
while True:
tries += 1
args = dict(kwargs)
url = "http://%s%s" % (self.host, request_path)
if args:
url += "?" + urllib.urlencode(args)
req = self._CreateRequest(url=url, data=payload)
req.add_header("Content-Type", content_type)
try:
f = self.opener.open(req)
response = f.read()
f.close()
return response
except urllib2.HTTPError, e:
if tries > 3:
raise
elif e.code == 401:
self._Authenticate()
## elif e.code >= 500 and e.code < 600:
## # Server Error - try again.
## continue
else:
raise
finally:
socket.setdefaulttimeout(old_timeout) | [
"def",
"Send",
"(",
"self",
",",
"request_path",
",",
"payload",
"=",
"None",
",",
"content_type",
"=",
"\"application/octet-stream\"",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Don't require authentication. Let the server say",
"# whether it is necessary.",
"if",
"not",
"self",
".",
"authenticated",
":",
"self",
".",
"_Authenticate",
"(",
")",
"old_timeout",
"=",
"socket",
".",
"getdefaulttimeout",
"(",
")",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"try",
":",
"tries",
"=",
"0",
"while",
"True",
":",
"tries",
"+=",
"1",
"args",
"=",
"dict",
"(",
"kwargs",
")",
"url",
"=",
"\"http://%s%s\"",
"%",
"(",
"self",
".",
"host",
",",
"request_path",
")",
"if",
"args",
":",
"url",
"+=",
"\"?\"",
"+",
"urllib",
".",
"urlencode",
"(",
"args",
")",
"req",
"=",
"self",
".",
"_CreateRequest",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"payload",
")",
"req",
".",
"add_header",
"(",
"\"Content-Type\"",
",",
"content_type",
")",
"try",
":",
"f",
"=",
"self",
".",
"opener",
".",
"open",
"(",
"req",
")",
"response",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"return",
"response",
"except",
"urllib2",
".",
"HTTPError",
",",
"e",
":",
"if",
"tries",
">",
"3",
":",
"raise",
"elif",
"e",
".",
"code",
"==",
"401",
":",
"self",
".",
"_Authenticate",
"(",
")",
"## elif e.code >= 500 and e.code < 600:",
"## # Server Error - try again.",
"## continue",
"else",
":",
"raise",
"finally",
":",
"socket",
".",
"setdefaulttimeout",
"(",
"old_timeout",
")"
] | https://github.com/schwehr/libais/blob/1e19605942c8e155cd02fde6d1acde75ecd15d75/third_party/gmock/scripts/upload.py#L291-L341 | ||
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/pyratemp.py | python | dummy_raise | (exception, value) | return mydummy | Create an exception-raising dummy function.
:Returns: dummy function, raising ``exception(value)`` | Create an exception-raising dummy function. | [
"Create",
"an",
"exception",
"-",
"raising",
"dummy",
"function",
"."
] | def dummy_raise(exception, value):
"""Create an exception-raising dummy function.
:Returns: dummy function, raising ``exception(value)``
"""
def mydummy(*args, **kwargs):
raise exception(value)
return mydummy | [
"def",
"dummy_raise",
"(",
"exception",
",",
"value",
")",
":",
"def",
"mydummy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"exception",
"(",
"value",
")",
"return",
"mydummy"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/pyratemp.py#L238-L245 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py | python | dictOf | ( key, value ) | return Dict( ZeroOrMore( Group ( key + value ) ) ) | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields. | [
"Helper",
"to",
"easily",
"and",
"clearly",
"define",
"a",
"dictionary",
"by",
"specifying",
"the",
"respective",
"patterns",
"for",
"the",
"key",
"and",
"value",
".",
"Takes",
"care",
"of",
"defining",
"the",
"C",
"{",
"L",
"{",
"Dict",
"}}",
"C",
"{",
"L",
"{",
"ZeroOrMore",
"}}",
"and",
"C",
"{",
"L",
"{",
"Group",
"}}",
"tokens",
"in",
"the",
"proper",
"order",
".",
"The",
"key",
"pattern",
"can",
"include",
"delimiting",
"markers",
"or",
"punctuation",
"as",
"long",
"as",
"they",
"are",
"suppressed",
"thereby",
"leaving",
"the",
"significant",
"key",
"text",
".",
"The",
"value",
"pattern",
"can",
"include",
"named",
"results",
"so",
"that",
"the",
"C",
"{",
"Dict",
"}",
"results",
"can",
"include",
"named",
"token",
"fields",
"."
] | def dictOf( key, value ):
"""
Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
"""
return Dict( ZeroOrMore( Group ( key + value ) ) ) | [
"def",
"dictOf",
"(",
"key",
",",
"value",
")",
":",
"return",
"Dict",
"(",
"ZeroOrMore",
"(",
"Group",
"(",
"key",
"+",
"value",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py#L4646-L4679 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | PlatformInformation.GetToolkitMinorVersion | (*args, **kwargs) | return _misc_.PlatformInformation_GetToolkitMinorVersion(*args, **kwargs) | GetToolkitMinorVersion(self) -> int | GetToolkitMinorVersion(self) -> int | [
"GetToolkitMinorVersion",
"(",
"self",
")",
"-",
">",
"int"
] | def GetToolkitMinorVersion(*args, **kwargs):
"""GetToolkitMinorVersion(self) -> int"""
return _misc_.PlatformInformation_GetToolkitMinorVersion(*args, **kwargs) | [
"def",
"GetToolkitMinorVersion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"PlatformInformation_GetToolkitMinorVersion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L1077-L1079 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/platforms/osx.py | python | HomebrewResolution.__init__ | (self, package, install_flags, options) | :param package: Homebrew package name, possibly fully qualified
with tap.
:param install_flags: List of strings of additional flags for
``brew install`` and ``brew deps`` command which are not
options (e.g. ``--HEAD``)
:param options: List of strings of options for the homebrew
package. | :param package: Homebrew package name, possibly fully qualified
with tap.
:param install_flags: List of strings of additional flags for
``brew install`` and ``brew deps`` command which are not
options (e.g. ``--HEAD``)
:param options: List of strings of options for the homebrew
package. | [
":",
"param",
"package",
":",
"Homebrew",
"package",
"name",
"possibly",
"fully",
"qualified",
"with",
"tap",
".",
":",
"param",
"install_flags",
":",
"List",
"of",
"strings",
"of",
"additional",
"flags",
"for",
"brew",
"install",
"and",
"brew",
"deps",
"command",
"which",
"are",
"not",
"options",
"(",
"e",
".",
"g",
".",
"--",
"HEAD",
")",
":",
"param",
"options",
":",
"List",
"of",
"strings",
"of",
"options",
"for",
"the",
"homebrew",
"package",
"."
] | def __init__(self, package, install_flags, options):
"""
:param package: Homebrew package name, possibly fully qualified
with tap.
:param install_flags: List of strings of additional flags for
``brew install`` and ``brew deps`` command which are not
options (e.g. ``--HEAD``)
:param options: List of strings of options for the homebrew
package.
"""
self.package = package
self.install_flags = install_flags
self.options = options | [
"def",
"__init__",
"(",
"self",
",",
"package",
",",
"install_flags",
",",
"options",
")",
":",
"self",
".",
"package",
"=",
"package",
"self",
".",
"install_flags",
"=",
"install_flags",
"self",
".",
"options",
"=",
"options"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/platforms/osx.py#L118-L130 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/lexer.py | python | count_newlines | (value) | return len(newline_re.findall(value)) | Count the number of newline characters in the string. This is
useful for extensions that filter a stream. | Count the number of newline characters in the string. This is
useful for extensions that filter a stream. | [
"Count",
"the",
"number",
"of",
"newline",
"characters",
"in",
"the",
"string",
".",
"This",
"is",
"useful",
"for",
"extensions",
"that",
"filter",
"a",
"stream",
"."
] | def count_newlines(value):
"""Count the number of newline characters in the string. This is
useful for extensions that filter a stream.
"""
return len(newline_re.findall(value)) | [
"def",
"count_newlines",
"(",
"value",
")",
":",
"return",
"len",
"(",
"newline_re",
".",
"findall",
"(",
"value",
")",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/lexer.py#L189-L193 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/campus-bikes-ii.py | python | Solution.assignBikes | (self, workers, bikes) | return min(dp[len(workers)%2]) | :type workers: List[List[int]]
:type bikes: List[List[int]]
:rtype: int | :type workers: List[List[int]]
:type bikes: List[List[int]]
:rtype: int | [
":",
"type",
"workers",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"type",
"bikes",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"int"
] | def assignBikes(self, workers, bikes):
"""
:type workers: List[List[int]]
:type bikes: List[List[int]]
:rtype: int
"""
def manhattan(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
dp = [[float("inf")]*((1<<len(bikes))) for _ in xrange(2)]
dp[0][0] = 0
for i in xrange(len(workers)):
dp[(i+1)%2] = [float("inf")] * ((1<<len(bikes)))
for j in xrange(len(bikes)):
for taken in xrange((1<<len(bikes))):
if taken & (1<<j):
continue
dp[(i+1)%2][taken|(1<<j)] = \
min(dp[(i+1)%2][taken|(1<<j)],
dp[i%2][taken] +
manhattan(workers[i], bikes[j]))
return min(dp[len(workers)%2]) | [
"def",
"assignBikes",
"(",
"self",
",",
"workers",
",",
"bikes",
")",
":",
"def",
"manhattan",
"(",
"p1",
",",
"p2",
")",
":",
"return",
"abs",
"(",
"p1",
"[",
"0",
"]",
"-",
"p2",
"[",
"0",
"]",
")",
"+",
"abs",
"(",
"p1",
"[",
"1",
"]",
"-",
"p2",
"[",
"1",
"]",
")",
"dp",
"=",
"[",
"[",
"float",
"(",
"\"inf\"",
")",
"]",
"*",
"(",
"(",
"1",
"<<",
"len",
"(",
"bikes",
")",
")",
")",
"for",
"_",
"in",
"xrange",
"(",
"2",
")",
"]",
"dp",
"[",
"0",
"]",
"[",
"0",
"]",
"=",
"0",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"workers",
")",
")",
":",
"dp",
"[",
"(",
"i",
"+",
"1",
")",
"%",
"2",
"]",
"=",
"[",
"float",
"(",
"\"inf\"",
")",
"]",
"*",
"(",
"(",
"1",
"<<",
"len",
"(",
"bikes",
")",
")",
")",
"for",
"j",
"in",
"xrange",
"(",
"len",
"(",
"bikes",
")",
")",
":",
"for",
"taken",
"in",
"xrange",
"(",
"(",
"1",
"<<",
"len",
"(",
"bikes",
")",
")",
")",
":",
"if",
"taken",
"&",
"(",
"1",
"<<",
"j",
")",
":",
"continue",
"dp",
"[",
"(",
"i",
"+",
"1",
")",
"%",
"2",
"]",
"[",
"taken",
"|",
"(",
"1",
"<<",
"j",
")",
"]",
"=",
"min",
"(",
"dp",
"[",
"(",
"i",
"+",
"1",
")",
"%",
"2",
"]",
"[",
"taken",
"|",
"(",
"1",
"<<",
"j",
")",
"]",
",",
"dp",
"[",
"i",
"%",
"2",
"]",
"[",
"taken",
"]",
"+",
"manhattan",
"(",
"workers",
"[",
"i",
"]",
",",
"bikes",
"[",
"j",
"]",
")",
")",
"return",
"min",
"(",
"dp",
"[",
"len",
"(",
"workers",
")",
"%",
"2",
"]",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/campus-bikes-ii.py#L7-L28 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/mindrecord/filewriter.py | python | FileWriter.add_index | (self, index_fields) | return self._header.add_index_fields(index_fields) | Select index fields from schema to accelerate reading.
Note:
The index fields should be primitive type. e.g. int/float/str.
If the function is not called, the fields of the primitive type
in schema are set as indexes by default.
Please refer to the Examples of class: `mindspore.mindrecord.FileWriter`.
Args:
index_fields (list[str]): fields from schema.
Returns:
MSRStatus, SUCCESS or FAILED.
Raises:
ParamTypeError: If index field is invalid.
MRMDefineIndexError: If index field is not primitive type.
MRMAddIndexError: If failed to add index field.
MRMGetMetaError: If the schema is not set or failed to get meta. | Select index fields from schema to accelerate reading. | [
"Select",
"index",
"fields",
"from",
"schema",
"to",
"accelerate",
"reading",
"."
] | def add_index(self, index_fields):
"""
Select index fields from schema to accelerate reading.
Note:
The index fields should be primitive type. e.g. int/float/str.
If the function is not called, the fields of the primitive type
in schema are set as indexes by default.
Please refer to the Examples of class: `mindspore.mindrecord.FileWriter`.
Args:
index_fields (list[str]): fields from schema.
Returns:
MSRStatus, SUCCESS or FAILED.
Raises:
ParamTypeError: If index field is invalid.
MRMDefineIndexError: If index field is not primitive type.
MRMAddIndexError: If failed to add index field.
MRMGetMetaError: If the schema is not set or failed to get meta.
"""
if not index_fields or not isinstance(index_fields, list):
raise ParamTypeError('index_fields', 'list')
for field in index_fields:
if field in self._header.blob_fields:
raise MRMDefineIndexError("Failed to set field {} since it's not primitive type.".format(field))
if not isinstance(field, str):
raise ParamTypeError('index field', 'str')
return self._header.add_index_fields(index_fields) | [
"def",
"add_index",
"(",
"self",
",",
"index_fields",
")",
":",
"if",
"not",
"index_fields",
"or",
"not",
"isinstance",
"(",
"index_fields",
",",
"list",
")",
":",
"raise",
"ParamTypeError",
"(",
"'index_fields'",
",",
"'list'",
")",
"for",
"field",
"in",
"index_fields",
":",
"if",
"field",
"in",
"self",
".",
"_header",
".",
"blob_fields",
":",
"raise",
"MRMDefineIndexError",
"(",
"\"Failed to set field {} since it's not primitive type.\"",
".",
"format",
"(",
"field",
")",
")",
"if",
"not",
"isinstance",
"(",
"field",
",",
"str",
")",
":",
"raise",
"ParamTypeError",
"(",
"'index field'",
",",
"'str'",
")",
"return",
"self",
".",
"_header",
".",
"add_index_fields",
"(",
"index_fields",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/filewriter.py#L184-L215 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/summary_ops_v2.py | python | create_summary_file_writer | (*args, **kwargs) | return create_file_writer(*args, **kwargs) | Please use `tf.contrib.summary.create_file_writer`. | Please use `tf.contrib.summary.create_file_writer`. | [
"Please",
"use",
"tf",
".",
"contrib",
".",
"summary",
".",
"create_file_writer",
"."
] | def create_summary_file_writer(*args, **kwargs):
"""Please use `tf.contrib.summary.create_file_writer`."""
logging.warning("Deprecation Warning: create_summary_file_writer was renamed "
"to create_file_writer")
return create_file_writer(*args, **kwargs) | [
"def",
"create_summary_file_writer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"warning",
"(",
"\"Deprecation Warning: create_summary_file_writer was renamed \"",
"\"to create_file_writer\"",
")",
"return",
"create_file_writer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/summary_ops_v2.py#L1133-L1137 | |
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | tools/extra/plot_loss_trends.py | python | plot_top1_accuracy_trends | (train_log, out_dir) | plot top-1 accuracy trend of train logs | plot top-1 accuracy trend of train logs | [
"plot",
"top",
"-",
"1",
"accuracy",
"trend",
"of",
"train",
"logs"
] | def plot_top1_accuracy_trends(train_log, out_dir):
'''plot top-1 accuracy trend of train logs'''
if train_log.is_detection: return
y_items = {'top-1 accuracy' : train_log.top1_accuracies}
x_items = {'Test iterations' : train_log.test_iterations}
plot_trend = PlotTrend(y_items, x_items, out_dir)
plot_trend.plot() | [
"def",
"plot_top1_accuracy_trends",
"(",
"train_log",
",",
"out_dir",
")",
":",
"if",
"train_log",
".",
"is_detection",
":",
"return",
"y_items",
"=",
"{",
"'top-1 accuracy'",
":",
"train_log",
".",
"top1_accuracies",
"}",
"x_items",
"=",
"{",
"'Test iterations'",
":",
"train_log",
".",
"test_iterations",
"}",
"plot_trend",
"=",
"PlotTrend",
"(",
"y_items",
",",
"x_items",
",",
"out_dir",
")",
"plot_trend",
".",
"plot",
"(",
")"
] | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/tools/extra/plot_loss_trends.py#L235-L241 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/monitors.py | python | EveryN.__init__ | (self, every_n_steps=100, first_n_steps=1) | Initializes an `EveryN` monitor.
Args:
every_n_steps: `int`, the number of steps to allow between callbacks.
first_n_steps: `int`, specifying the number of initial steps during
which the callbacks will always be executed, regardless of the value
of `every_n_steps`. Note that this value is relative to the global step | Initializes an `EveryN` monitor. | [
"Initializes",
"an",
"EveryN",
"monitor",
"."
] | def __init__(self, every_n_steps=100, first_n_steps=1):
"""Initializes an `EveryN` monitor.
Args:
every_n_steps: `int`, the number of steps to allow between callbacks.
first_n_steps: `int`, specifying the number of initial steps during
which the callbacks will always be executed, regardless of the value
of `every_n_steps`. Note that this value is relative to the global step
"""
super(EveryN, self).__init__()
self._every_n_steps = every_n_steps
self._first_n_steps = first_n_steps
# Last step in the model.
self._last_successful_step = None
# Last step at which we called one of the every_n methods
self._last_active_step = 0
self._every_n_step_begin_called = False | [
"def",
"__init__",
"(",
"self",
",",
"every_n_steps",
"=",
"100",
",",
"first_n_steps",
"=",
"1",
")",
":",
"super",
"(",
"EveryN",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_every_n_steps",
"=",
"every_n_steps",
"self",
".",
"_first_n_steps",
"=",
"first_n_steps",
"# Last step in the model.",
"self",
".",
"_last_successful_step",
"=",
"None",
"# Last step at which we called one of the every_n methods",
"self",
".",
"_last_active_step",
"=",
"0",
"self",
".",
"_every_n_step_begin_called",
"=",
"False"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/monitors.py#L270-L286 | ||
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/mox.py | python | Comparator.equals | (self, rhs) | Special equals method that all comparators must implement.
Args:
rhs: any python object | Special equals method that all comparators must implement. | [
"Special",
"equals",
"method",
"that",
"all",
"comparators",
"must",
"implement",
"."
] | def equals(self, rhs):
"""Special equals method that all comparators must implement.
Args:
rhs: any python object
"""
raise NotImplementedError, 'method must be implemented by a subclass.' | [
"def",
"equals",
"(",
"self",
",",
"rhs",
")",
":",
"raise",
"NotImplementedError",
",",
"'method must be implemented by a subclass.'"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/mox.py#L774-L781 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.ComputeOutputParts | (self, spec) | return (target_stem, target_ext) | Return the 'output basename' of a gyp spec, split into filename + ext.
Android libraries must be named the same thing as their module name,
otherwise the linker can't find them, so product_name and so on must be
ignored if we are building a library, and the "lib" prepending is
not done for Android. | Return the 'output basename' of a gyp spec, split into filename + ext. | [
"Return",
"the",
"output",
"basename",
"of",
"a",
"gyp",
"spec",
"split",
"into",
"filename",
"+",
"ext",
"."
] | def ComputeOutputParts(self, spec):
"""Return the 'output basename' of a gyp spec, split into filename + ext.
Android libraries must be named the same thing as their module name,
otherwise the linker can't find them, so product_name and so on must be
ignored if we are building a library, and the "lib" prepending is
not done for Android.
"""
assert self.type != 'loadable_module' # TODO: not supported?
target = spec['target_name']
target_prefix = ''
target_ext = ''
if self.type == 'static_library':
target = self.ComputeAndroidModule(spec)
target_ext = '.a'
elif self.type == 'shared_library':
target = self.ComputeAndroidModule(spec)
target_ext = '.so'
elif self.type == 'none':
target_ext = '.stamp'
elif self.type != 'executable':
print("ERROR: What output file should be generated?",
"type", self.type, "target", target)
if self.type != 'static_library' and self.type != 'shared_library':
target_prefix = spec.get('product_prefix', target_prefix)
target = spec.get('product_name', target)
product_ext = spec.get('product_extension')
if product_ext:
target_ext = '.' + product_ext
target_stem = target_prefix + target
return (target_stem, target_ext) | [
"def",
"ComputeOutputParts",
"(",
"self",
",",
"spec",
")",
":",
"assert",
"self",
".",
"type",
"!=",
"'loadable_module'",
"# TODO: not supported?",
"target",
"=",
"spec",
"[",
"'target_name'",
"]",
"target_prefix",
"=",
"''",
"target_ext",
"=",
"''",
"if",
"self",
".",
"type",
"==",
"'static_library'",
":",
"target",
"=",
"self",
".",
"ComputeAndroidModule",
"(",
"spec",
")",
"target_ext",
"=",
"'.a'",
"elif",
"self",
".",
"type",
"==",
"'shared_library'",
":",
"target",
"=",
"self",
".",
"ComputeAndroidModule",
"(",
"spec",
")",
"target_ext",
"=",
"'.so'",
"elif",
"self",
".",
"type",
"==",
"'none'",
":",
"target_ext",
"=",
"'.stamp'",
"elif",
"self",
".",
"type",
"!=",
"'executable'",
":",
"print",
"(",
"\"ERROR: What output file should be generated?\"",
",",
"\"type\"",
",",
"self",
".",
"type",
",",
"\"target\"",
",",
"target",
")",
"if",
"self",
".",
"type",
"!=",
"'static_library'",
"and",
"self",
".",
"type",
"!=",
"'shared_library'",
":",
"target_prefix",
"=",
"spec",
".",
"get",
"(",
"'product_prefix'",
",",
"target_prefix",
")",
"target",
"=",
"spec",
".",
"get",
"(",
"'product_name'",
",",
"target",
")",
"product_ext",
"=",
"spec",
".",
"get",
"(",
"'product_extension'",
")",
"if",
"product_ext",
":",
"target_ext",
"=",
"'.'",
"+",
"product_ext",
"target_stem",
"=",
"target_prefix",
"+",
"target",
"return",
"(",
"target_stem",
",",
"target_ext",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/android.py#L619-L652 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | build/android/gyp/process_resources.py | python | MoveImagesToNonMdpiFolders | (res_root) | Move images from drawable-*-mdpi-* folders to drawable-* folders.
Why? http://crbug.com/289843 | Move images from drawable-*-mdpi-* folders to drawable-* folders. | [
"Move",
"images",
"from",
"drawable",
"-",
"*",
"-",
"mdpi",
"-",
"*",
"folders",
"to",
"drawable",
"-",
"*",
"folders",
"."
] | def MoveImagesToNonMdpiFolders(res_root):
"""Move images from drawable-*-mdpi-* folders to drawable-* folders.
Why? http://crbug.com/289843
"""
for src_dir_name in os.listdir(res_root):
src_components = src_dir_name.split('-')
if src_components[0] != 'drawable' or 'mdpi' not in src_components:
continue
src_dir = os.path.join(res_root, src_dir_name)
if not os.path.isdir(src_dir):
continue
dst_components = [c for c in src_components if c != 'mdpi']
assert dst_components != src_components
dst_dir_name = '-'.join(dst_components)
dst_dir = os.path.join(res_root, dst_dir_name)
build_utils.MakeDirectory(dst_dir)
for src_file_name in os.listdir(src_dir):
if not src_file_name.endswith('.png'):
continue
src_file = os.path.join(src_dir, src_file_name)
dst_file = os.path.join(dst_dir, src_file_name)
assert not os.path.lexists(dst_file)
shutil.move(src_file, dst_file) | [
"def",
"MoveImagesToNonMdpiFolders",
"(",
"res_root",
")",
":",
"for",
"src_dir_name",
"in",
"os",
".",
"listdir",
"(",
"res_root",
")",
":",
"src_components",
"=",
"src_dir_name",
".",
"split",
"(",
"'-'",
")",
"if",
"src_components",
"[",
"0",
"]",
"!=",
"'drawable'",
"or",
"'mdpi'",
"not",
"in",
"src_components",
":",
"continue",
"src_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"res_root",
",",
"src_dir_name",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"src_dir",
")",
":",
"continue",
"dst_components",
"=",
"[",
"c",
"for",
"c",
"in",
"src_components",
"if",
"c",
"!=",
"'mdpi'",
"]",
"assert",
"dst_components",
"!=",
"src_components",
"dst_dir_name",
"=",
"'-'",
".",
"join",
"(",
"dst_components",
")",
"dst_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"res_root",
",",
"dst_dir_name",
")",
"build_utils",
".",
"MakeDirectory",
"(",
"dst_dir",
")",
"for",
"src_file_name",
"in",
"os",
".",
"listdir",
"(",
"src_dir",
")",
":",
"if",
"not",
"src_file_name",
".",
"endswith",
"(",
"'.png'",
")",
":",
"continue",
"src_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"src_dir",
",",
"src_file_name",
")",
"dst_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst_dir",
",",
"src_file_name",
")",
"assert",
"not",
"os",
".",
"path",
".",
"lexists",
"(",
"dst_file",
")",
"shutil",
".",
"move",
"(",
"src_file",
",",
"dst_file",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/gyp/process_resources.py#L54-L77 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/FrameDecorator.py | python | FrameDecorator.filename | (self) | Return the filename associated with this frame, detecting
and returning the appropriate library name is this is a shared
library. | Return the filename associated with this frame, detecting
and returning the appropriate library name is this is a shared
library. | [
"Return",
"the",
"filename",
"associated",
"with",
"this",
"frame",
"detecting",
"and",
"returning",
"the",
"appropriate",
"library",
"name",
"is",
"this",
"is",
"a",
"shared",
"library",
"."
] | def filename(self):
""" Return the filename associated with this frame, detecting
and returning the appropriate library name is this is a shared
library."""
if hasattr(self._base, "filename"):
return self._base.filename()
frame = self.inferior_frame()
sal = frame.find_sal()
if not sal.symtab or not sal.symtab.filename:
pc = frame.pc()
return gdb.solib_name(pc)
else:
return sal.symtab.filename | [
"def",
"filename",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_base",
",",
"\"filename\"",
")",
":",
"return",
"self",
".",
"_base",
".",
"filename",
"(",
")",
"frame",
"=",
"self",
".",
"inferior_frame",
"(",
")",
"sal",
"=",
"frame",
".",
"find_sal",
"(",
")",
"if",
"not",
"sal",
".",
"symtab",
"or",
"not",
"sal",
".",
"symtab",
".",
"filename",
":",
"pc",
"=",
"frame",
".",
"pc",
"(",
")",
"return",
"gdb",
".",
"solib_name",
"(",
"pc",
")",
"else",
":",
"return",
"sal",
".",
"symtab",
".",
"filename"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/FrameDecorator.py#L131-L145 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | BoolArgument.GetValidClientSideCmdArg | (self, func, offset, index) | return 'true' | Gets a valid value for this argument. | Gets a valid value for this argument. | [
"Gets",
"a",
"valid",
"value",
"for",
"this",
"argument",
"."
] | def GetValidClientSideCmdArg(self, func, offset, index):
"""Gets a valid value for this argument."""
return 'true' | [
"def",
"GetValidClientSideCmdArg",
"(",
"self",
",",
"func",
",",
"offset",
",",
"index",
")",
":",
"return",
"'true'"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5875-L5877 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/hmac.py | python | HMAC.hexdigest | (self) | return h.hexdigest() | Like digest(), but returns a string of hexadecimal digits instead. | Like digest(), but returns a string of hexadecimal digits instead. | [
"Like",
"digest",
"()",
"but",
"returns",
"a",
"string",
"of",
"hexadecimal",
"digits",
"instead",
"."
] | def hexdigest(self):
"""Like digest(), but returns a string of hexadecimal digits instead.
"""
h = self._current()
return h.hexdigest() | [
"def",
"hexdigest",
"(",
"self",
")",
":",
"h",
"=",
"self",
".",
"_current",
"(",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/hmac.py#L136-L140 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/Paste/paste/cgiapp.py | python | proc_communicate | (proc, stdin=None, stdout=None, stderr=None) | Run the given process, piping input/output/errors to the given
file-like objects (which need not be actual file objects, unlike
the arguments passed to Popen). Wait for process to terminate.
Note: this is taken from the posix version of
subprocess.Popen.communicate, but made more general through the
use of file-like objects. | Run the given process, piping input/output/errors to the given
file-like objects (which need not be actual file objects, unlike
the arguments passed to Popen). Wait for process to terminate. | [
"Run",
"the",
"given",
"process",
"piping",
"input",
"/",
"output",
"/",
"errors",
"to",
"the",
"given",
"file",
"-",
"like",
"objects",
"(",
"which",
"need",
"not",
"be",
"actual",
"file",
"objects",
"unlike",
"the",
"arguments",
"passed",
"to",
"Popen",
")",
".",
"Wait",
"for",
"process",
"to",
"terminate",
"."
] | def proc_communicate(proc, stdin=None, stdout=None, stderr=None):
"""
Run the given process, piping input/output/errors to the given
file-like objects (which need not be actual file objects, unlike
the arguments passed to Popen). Wait for process to terminate.
Note: this is taken from the posix version of
subprocess.Popen.communicate, but made more general through the
use of file-like objects.
"""
read_set = []
write_set = []
input_buffer = b''
trans_nl = proc.universal_newlines and hasattr(open, 'newlines')
if proc.stdin:
# Flush stdio buffer. This might block, if the user has
# been writing to .stdin in an uncontrolled fashion.
proc.stdin.flush()
if input:
write_set.append(proc.stdin)
else:
proc.stdin.close()
else:
assert stdin is None
if proc.stdout:
read_set.append(proc.stdout)
else:
assert stdout is None
if proc.stderr:
read_set.append(proc.stderr)
else:
assert stderr is None
while read_set or write_set:
rlist, wlist, xlist = select.select(read_set, write_set, [])
if proc.stdin in wlist:
# When select has indicated that the file is writable,
# we can write up to PIPE_BUF bytes without risk
# blocking. POSIX defines PIPE_BUF >= 512
next, input_buffer = input_buffer, b''
next_len = 512-len(next)
if next_len:
next += stdin.read(next_len)
if not next:
proc.stdin.close()
write_set.remove(proc.stdin)
else:
bytes_written = os.write(proc.stdin.fileno(), next)
if bytes_written < len(next):
input_buffer = next[bytes_written:]
if proc.stdout in rlist:
data = os.read(proc.stdout.fileno(), 1024)
if data == b"":
proc.stdout.close()
read_set.remove(proc.stdout)
if trans_nl:
data = proc._translate_newlines(data)
stdout.write(data)
if proc.stderr in rlist:
data = os.read(proc.stderr.fileno(), 1024)
if data == b"":
proc.stderr.close()
read_set.remove(proc.stderr)
if trans_nl:
data = proc._translate_newlines(data)
stderr.write(data)
try:
proc.wait()
except OSError as e:
if e.errno != 10:
raise | [
"def",
"proc_communicate",
"(",
"proc",
",",
"stdin",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"read_set",
"=",
"[",
"]",
"write_set",
"=",
"[",
"]",
"input_buffer",
"=",
"b''",
"trans_nl",
"=",
"proc",
".",
"universal_newlines",
"and",
"hasattr",
"(",
"open",
",",
"'newlines'",
")",
"if",
"proc",
".",
"stdin",
":",
"# Flush stdio buffer. This might block, if the user has",
"# been writing to .stdin in an uncontrolled fashion.",
"proc",
".",
"stdin",
".",
"flush",
"(",
")",
"if",
"input",
":",
"write_set",
".",
"append",
"(",
"proc",
".",
"stdin",
")",
"else",
":",
"proc",
".",
"stdin",
".",
"close",
"(",
")",
"else",
":",
"assert",
"stdin",
"is",
"None",
"if",
"proc",
".",
"stdout",
":",
"read_set",
".",
"append",
"(",
"proc",
".",
"stdout",
")",
"else",
":",
"assert",
"stdout",
"is",
"None",
"if",
"proc",
".",
"stderr",
":",
"read_set",
".",
"append",
"(",
"proc",
".",
"stderr",
")",
"else",
":",
"assert",
"stderr",
"is",
"None",
"while",
"read_set",
"or",
"write_set",
":",
"rlist",
",",
"wlist",
",",
"xlist",
"=",
"select",
".",
"select",
"(",
"read_set",
",",
"write_set",
",",
"[",
"]",
")",
"if",
"proc",
".",
"stdin",
"in",
"wlist",
":",
"# When select has indicated that the file is writable,",
"# we can write up to PIPE_BUF bytes without risk",
"# blocking. POSIX defines PIPE_BUF >= 512",
"next",
",",
"input_buffer",
"=",
"input_buffer",
",",
"b''",
"next_len",
"=",
"512",
"-",
"len",
"(",
"next",
")",
"if",
"next_len",
":",
"next",
"+=",
"stdin",
".",
"read",
"(",
"next_len",
")",
"if",
"not",
"next",
":",
"proc",
".",
"stdin",
".",
"close",
"(",
")",
"write_set",
".",
"remove",
"(",
"proc",
".",
"stdin",
")",
"else",
":",
"bytes_written",
"=",
"os",
".",
"write",
"(",
"proc",
".",
"stdin",
".",
"fileno",
"(",
")",
",",
"next",
")",
"if",
"bytes_written",
"<",
"len",
"(",
"next",
")",
":",
"input_buffer",
"=",
"next",
"[",
"bytes_written",
":",
"]",
"if",
"proc",
".",
"stdout",
"in",
"rlist",
":",
"data",
"=",
"os",
".",
"read",
"(",
"proc",
".",
"stdout",
".",
"fileno",
"(",
")",
",",
"1024",
")",
"if",
"data",
"==",
"b\"\"",
":",
"proc",
".",
"stdout",
".",
"close",
"(",
")",
"read_set",
".",
"remove",
"(",
"proc",
".",
"stdout",
")",
"if",
"trans_nl",
":",
"data",
"=",
"proc",
".",
"_translate_newlines",
"(",
"data",
")",
"stdout",
".",
"write",
"(",
"data",
")",
"if",
"proc",
".",
"stderr",
"in",
"rlist",
":",
"data",
"=",
"os",
".",
"read",
"(",
"proc",
".",
"stderr",
".",
"fileno",
"(",
")",
",",
"1024",
")",
"if",
"data",
"==",
"b\"\"",
":",
"proc",
".",
"stderr",
".",
"close",
"(",
")",
"read_set",
".",
"remove",
"(",
"proc",
".",
"stderr",
")",
"if",
"trans_nl",
":",
"data",
"=",
"proc",
".",
"_translate_newlines",
"(",
"data",
")",
"stderr",
".",
"write",
"(",
"data",
")",
"try",
":",
"proc",
".",
"wait",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"10",
":",
"raise"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/cgiapp.py#L187-L262 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | PrintData.GetDuplex | (*args, **kwargs) | return _windows_.PrintData_GetDuplex(*args, **kwargs) | GetDuplex(self) -> int | GetDuplex(self) -> int | [
"GetDuplex",
"(",
"self",
")",
"-",
">",
"int"
] | def GetDuplex(*args, **kwargs):
"""GetDuplex(self) -> int"""
return _windows_.PrintData_GetDuplex(*args, **kwargs) | [
"def",
"GetDuplex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintData_GetDuplex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L4739-L4741 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/tensorflow_builder/config_detector/config_detector.py | python | get_platform | () | return PLATFORM | Retrieves platform information.
Currently the script only support linux. If other platoforms such as Windows
or MacOS is detected, it throws an error and terminates.
Returns:
String that is platform type.
e.g. 'linux' | Retrieves platform information. | [
"Retrieves",
"platform",
"information",
"."
] | def get_platform():
"""Retrieves platform information.
Currently the script only support linux. If other platoforms such as Windows
or MacOS is detected, it throws an error and terminates.
Returns:
String that is platform type.
e.g. 'linux'
"""
global PLATFORM
cmd = "uname"
out, err = run_shell_cmd(cmd)
platform_detected = out.strip().lower()
if platform_detected != "linux":
if err and FLAGS.debug:
print("Error in detecting platform:\n %s" % str(err))
print("Error: Detected unsupported operating system.\nStopping...")
sys.exit(1)
else:
PLATFORM = platform_detected
return PLATFORM | [
"def",
"get_platform",
"(",
")",
":",
"global",
"PLATFORM",
"cmd",
"=",
"\"uname\"",
"out",
",",
"err",
"=",
"run_shell_cmd",
"(",
"cmd",
")",
"platform_detected",
"=",
"out",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"platform_detected",
"!=",
"\"linux\"",
":",
"if",
"err",
"and",
"FLAGS",
".",
"debug",
":",
"print",
"(",
"\"Error in detecting platform:\\n %s\"",
"%",
"str",
"(",
"err",
")",
")",
"print",
"(",
"\"Error: Detected unsupported operating system.\\nStopping...\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"else",
":",
"PLATFORM",
"=",
"platform_detected",
"return",
"PLATFORM"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/tensorflow_builder/config_detector/config_detector.py#L150-L173 | |
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/mox.py | python | MockMethod.GetPossibleGroup | (self) | return group | Returns a possible group from the end of the call queue or None if no
other methods are on the stack. | Returns a possible group from the end of the call queue or None if no
other methods are on the stack. | [
"Returns",
"a",
"possible",
"group",
"from",
"the",
"end",
"of",
"the",
"call",
"queue",
"or",
"None",
"if",
"no",
"other",
"methods",
"are",
"on",
"the",
"stack",
"."
] | def GetPossibleGroup(self):
"""Returns a possible group from the end of the call queue or None if no
other methods are on the stack.
"""
# Remove this method from the tail of the queue so we can add it to a group.
this_method = self._call_queue.pop()
assert this_method == self
# Determine if the tail of the queue is a group, or just a regular ordered
# mock method.
group = None
try:
group = self._call_queue[-1]
except IndexError:
pass
return group | [
"def",
"GetPossibleGroup",
"(",
"self",
")",
":",
"# Remove this method from the tail of the queue so we can add it to a group.",
"this_method",
"=",
"self",
".",
"_call_queue",
".",
"pop",
"(",
")",
"assert",
"this_method",
"==",
"self",
"# Determine if the tail of the queue is a group, or just a regular ordered",
"# mock method.",
"group",
"=",
"None",
"try",
":",
"group",
"=",
"self",
".",
"_call_queue",
"[",
"-",
"1",
"]",
"except",
"IndexError",
":",
"pass",
"return",
"group"
] | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/mox.py#L645-L662 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/platform.py | python | _syscmd_ver | (system='', release='', version='',
supported_platforms=('win32','win16','dos','os2')) | return system,release,version | Tries to figure out the OS version used and returns
a tuple (system,release,version).
It uses the "ver" shell command for this which is known
to exists on Windows, DOS and OS/2. XXX Others too ?
In case this fails, the given parameters are used as
defaults. | Tries to figure out the OS version used and returns
a tuple (system,release,version). | [
"Tries",
"to",
"figure",
"out",
"the",
"OS",
"version",
"used",
"and",
"returns",
"a",
"tuple",
"(",
"system",
"release",
"version",
")",
"."
] | def _syscmd_ver(system='', release='', version='',
supported_platforms=('win32','win16','dos','os2')):
""" Tries to figure out the OS version used and returns
a tuple (system,release,version).
It uses the "ver" shell command for this which is known
to exists on Windows, DOS and OS/2. XXX Others too ?
In case this fails, the given parameters are used as
defaults.
"""
if sys.platform not in supported_platforms:
return system,release,version
# Try some common cmd strings
for cmd in ('ver','command /c ver','cmd /c ver'):
try:
pipe = popen(cmd)
info = pipe.read()
if pipe.close():
raise os.error,'command failed'
# XXX How can I suppress shell errors from being written
# to stderr ?
except os.error,why:
#print 'Command %s failed: %s' % (cmd,why)
continue
except IOError,why:
#print 'Command %s failed: %s' % (cmd,why)
continue
else:
break
else:
return system,release,version
# Parse the output
info = string.strip(info)
m = _ver_output.match(info)
if m is not None:
system,release,version = m.groups()
# Strip trailing dots from version and release
if release[-1] == '.':
release = release[:-1]
if version[-1] == '.':
version = version[:-1]
# Normalize the version and build strings (eliminating additional
# zeros)
version = _norm_version(version)
return system,release,version | [
"def",
"_syscmd_ver",
"(",
"system",
"=",
"''",
",",
"release",
"=",
"''",
",",
"version",
"=",
"''",
",",
"supported_platforms",
"=",
"(",
"'win32'",
",",
"'win16'",
",",
"'dos'",
",",
"'os2'",
")",
")",
":",
"if",
"sys",
".",
"platform",
"not",
"in",
"supported_platforms",
":",
"return",
"system",
",",
"release",
",",
"version",
"# Try some common cmd strings",
"for",
"cmd",
"in",
"(",
"'ver'",
",",
"'command /c ver'",
",",
"'cmd /c ver'",
")",
":",
"try",
":",
"pipe",
"=",
"popen",
"(",
"cmd",
")",
"info",
"=",
"pipe",
".",
"read",
"(",
")",
"if",
"pipe",
".",
"close",
"(",
")",
":",
"raise",
"os",
".",
"error",
",",
"'command failed'",
"# XXX How can I suppress shell errors from being written",
"# to stderr ?",
"except",
"os",
".",
"error",
",",
"why",
":",
"#print 'Command %s failed: %s' % (cmd,why)",
"continue",
"except",
"IOError",
",",
"why",
":",
"#print 'Command %s failed: %s' % (cmd,why)",
"continue",
"else",
":",
"break",
"else",
":",
"return",
"system",
",",
"release",
",",
"version",
"# Parse the output",
"info",
"=",
"string",
".",
"strip",
"(",
"info",
")",
"m",
"=",
"_ver_output",
".",
"match",
"(",
"info",
")",
"if",
"m",
"is",
"not",
"None",
":",
"system",
",",
"release",
",",
"version",
"=",
"m",
".",
"groups",
"(",
")",
"# Strip trailing dots from version and release",
"if",
"release",
"[",
"-",
"1",
"]",
"==",
"'.'",
":",
"release",
"=",
"release",
"[",
":",
"-",
"1",
"]",
"if",
"version",
"[",
"-",
"1",
"]",
"==",
"'.'",
":",
"version",
"=",
"version",
"[",
":",
"-",
"1",
"]",
"# Normalize the version and build strings (eliminating additional",
"# zeros)",
"version",
"=",
"_norm_version",
"(",
"version",
")",
"return",
"system",
",",
"release",
",",
"version"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/platform.py#L540-L590 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | SimBody.getObjectTransform | (self) | return _robotsim.SimBody_getObjectTransform(self) | r"""
getObjectTransform(SimBody self)
Gets the body's transformation at the current simulation time step (in object-
native coordinates). | r"""
getObjectTransform(SimBody self) | [
"r",
"getObjectTransform",
"(",
"SimBody",
"self",
")"
] | def getObjectTransform(self) -> "void":
r"""
getObjectTransform(SimBody self)
Gets the body's transformation at the current simulation time step (in object-
native coordinates).
"""
return _robotsim.SimBody_getObjectTransform(self) | [
"def",
"getObjectTransform",
"(",
"self",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"SimBody_getObjectTransform",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L7923-L7932 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewModelNotifier.ValueChanged | (*args, **kwargs) | return _dataview.DataViewModelNotifier_ValueChanged(*args, **kwargs) | ValueChanged(self, DataViewItem item, unsigned int col) -> bool
Override this to be informed that a value has changed in the model.
This differs from `ItemChanged` in that this method is sensitive to
changes in sub-elements of an item, not just the whole item (row). | ValueChanged(self, DataViewItem item, unsigned int col) -> bool | [
"ValueChanged",
"(",
"self",
"DataViewItem",
"item",
"unsigned",
"int",
"col",
")",
"-",
">",
"bool"
] | def ValueChanged(*args, **kwargs):
"""
ValueChanged(self, DataViewItem item, unsigned int col) -> bool
Override this to be informed that a value has changed in the model.
This differs from `ItemChanged` in that this method is sensitive to
changes in sub-elements of an item, not just the whole item (row).
"""
return _dataview.DataViewModelNotifier_ValueChanged(*args, **kwargs) | [
"def",
"ValueChanged",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModelNotifier_ValueChanged",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L240-L248 | |
nvdla/sw | 79538ba1b52b040a4a4645f630e457fa01839e90 | umd/external/protobuf-2.6/python/google/protobuf/text_format.py | python | ParseBool | (text) | Parse a boolean value.
Args:
text: Text to parse.
Returns:
Boolean values parsed
Raises:
ValueError: If text is not a valid boolean. | Parse a boolean value. | [
"Parse",
"a",
"boolean",
"value",
"."
] | def ParseBool(text):
"""Parse a boolean value.
Args:
text: Text to parse.
Returns:
Boolean values parsed
Raises:
ValueError: If text is not a valid boolean.
"""
if text in ('true', 't', '1'):
return True
elif text in ('false', 'f', '0'):
return False
else:
raise ValueError('Expected "true" or "false".') | [
"def",
"ParseBool",
"(",
"text",
")",
":",
"if",
"text",
"in",
"(",
"'true'",
",",
"'t'",
",",
"'1'",
")",
":",
"return",
"True",
"elif",
"text",
"in",
"(",
"'false'",
",",
"'f'",
",",
"'0'",
")",
":",
"return",
"False",
"else",
":",
"raise",
"ValueError",
"(",
"'Expected \"true\" or \"false\".'",
")"
] | https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/text_format.py#L820-L837 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/io/pytables.py | python | HDFStore.append_to_multiple | (self, d, value, selector, data_columns=None,
axes=None, dropna=False, **kwargs) | Append to multiple tables
Parameters
----------
d : a dict of table_name to table_columns, None is acceptable as the
values of one node (this will get all the remaining columns)
value : a pandas object
selector : a string that designates the indexable table; all of its
columns will be designed as data_columns, unless data_columns is
passed, in which case these are used
data_columns : list of columns to create as data columns, or True to
use all columns
dropna : if evaluates to True, drop rows from all tables if any single
row in each table has all NaN. Default False.
Notes
-----
axes parameter is currently not accepted | Append to multiple tables | [
"Append",
"to",
"multiple",
"tables"
] | def append_to_multiple(self, d, value, selector, data_columns=None,
axes=None, dropna=False, **kwargs):
"""
Append to multiple tables
Parameters
----------
d : a dict of table_name to table_columns, None is acceptable as the
values of one node (this will get all the remaining columns)
value : a pandas object
selector : a string that designates the indexable table; all of its
columns will be designed as data_columns, unless data_columns is
passed, in which case these are used
data_columns : list of columns to create as data columns, or True to
use all columns
dropna : if evaluates to True, drop rows from all tables if any single
row in each table has all NaN. Default False.
Notes
-----
axes parameter is currently not accepted
"""
if axes is not None:
raise TypeError("axes is currently not accepted as a parameter to"
" append_to_multiple; you can create the "
"tables independently instead")
if not isinstance(d, dict):
raise ValueError(
"append_to_multiple must have a dictionary specified as the "
"way to split the value"
)
if selector not in d:
raise ValueError(
"append_to_multiple requires a selector that is in passed dict"
)
# figure out the splitting axis (the non_index_axis)
axis = list(set(range(value.ndim)) - set(_AXES_MAP[type(value)]))[0]
# figure out how to split the value
remain_key = None
remain_values = []
for k, v in d.items():
if v is None:
if remain_key is not None:
raise ValueError(
"append_to_multiple can only have one value in d that "
"is None"
)
remain_key = k
else:
remain_values.extend(v)
if remain_key is not None:
ordered = value.axes[axis]
ordd = ordered.difference(Index(remain_values))
ordd = sorted(ordered.get_indexer(ordd))
d[remain_key] = ordered.take(ordd)
# data_columns
if data_columns is None:
data_columns = d[selector]
# ensure rows are synchronized across the tables
if dropna:
idxs = (value[cols].dropna(how='all').index for cols in d.values())
valid_index = next(idxs)
for index in idxs:
valid_index = valid_index.intersection(index)
value = value.loc[valid_index]
# append
for k, v in d.items():
dc = data_columns if k == selector else None
# compute the val
val = value.reindex(v, axis=axis)
self.append(k, val, data_columns=dc, **kwargs) | [
"def",
"append_to_multiple",
"(",
"self",
",",
"d",
",",
"value",
",",
"selector",
",",
"data_columns",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"dropna",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"axes",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"axes is currently not accepted as a parameter to\"",
"\" append_to_multiple; you can create the \"",
"\"tables independently instead\"",
")",
"if",
"not",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"append_to_multiple must have a dictionary specified as the \"",
"\"way to split the value\"",
")",
"if",
"selector",
"not",
"in",
"d",
":",
"raise",
"ValueError",
"(",
"\"append_to_multiple requires a selector that is in passed dict\"",
")",
"# figure out the splitting axis (the non_index_axis)",
"axis",
"=",
"list",
"(",
"set",
"(",
"range",
"(",
"value",
".",
"ndim",
")",
")",
"-",
"set",
"(",
"_AXES_MAP",
"[",
"type",
"(",
"value",
")",
"]",
")",
")",
"[",
"0",
"]",
"# figure out how to split the value",
"remain_key",
"=",
"None",
"remain_values",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"if",
"remain_key",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"append_to_multiple can only have one value in d that \"",
"\"is None\"",
")",
"remain_key",
"=",
"k",
"else",
":",
"remain_values",
".",
"extend",
"(",
"v",
")",
"if",
"remain_key",
"is",
"not",
"None",
":",
"ordered",
"=",
"value",
".",
"axes",
"[",
"axis",
"]",
"ordd",
"=",
"ordered",
".",
"difference",
"(",
"Index",
"(",
"remain_values",
")",
")",
"ordd",
"=",
"sorted",
"(",
"ordered",
".",
"get_indexer",
"(",
"ordd",
")",
")",
"d",
"[",
"remain_key",
"]",
"=",
"ordered",
".",
"take",
"(",
"ordd",
")",
"# data_columns",
"if",
"data_columns",
"is",
"None",
":",
"data_columns",
"=",
"d",
"[",
"selector",
"]",
"# ensure rows are synchronized across the tables",
"if",
"dropna",
":",
"idxs",
"=",
"(",
"value",
"[",
"cols",
"]",
".",
"dropna",
"(",
"how",
"=",
"'all'",
")",
".",
"index",
"for",
"cols",
"in",
"d",
".",
"values",
"(",
")",
")",
"valid_index",
"=",
"next",
"(",
"idxs",
")",
"for",
"index",
"in",
"idxs",
":",
"valid_index",
"=",
"valid_index",
".",
"intersection",
"(",
"index",
")",
"value",
"=",
"value",
".",
"loc",
"[",
"valid_index",
"]",
"# append",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"dc",
"=",
"data_columns",
"if",
"k",
"==",
"selector",
"else",
"None",
"# compute the val",
"val",
"=",
"value",
".",
"reindex",
"(",
"v",
",",
"axis",
"=",
"axis",
")",
"self",
".",
"append",
"(",
"k",
",",
"val",
",",
"data_columns",
"=",
"dc",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L988-L1068 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/io/formats/style.py | python | Styler.set_caption | (self, caption) | return self | Set the caption on a Styler
Parameters
----------
caption : str
Returns
-------
self : Styler | Set the caption on a Styler | [
"Set",
"the",
"caption",
"on",
"a",
"Styler"
] | def set_caption(self, caption):
"""
Set the caption on a Styler
Parameters
----------
caption : str
Returns
-------
self : Styler
"""
self.caption = caption
return self | [
"def",
"set_caption",
"(",
"self",
",",
"caption",
")",
":",
"self",
".",
"caption",
"=",
"caption",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/formats/style.py#L778-L791 | |
manutdzou/KITTI_SSD | 5b620c2f291d36a0fe14489214f22a992f173f44 | examples/pycaffe/tools.py | python | SimpleTransformer.preprocess | (self, im) | return im | preprocess() emulate the pre-processing occuring in the vgg16 caffe
prototxt. | preprocess() emulate the pre-processing occuring in the vgg16 caffe
prototxt. | [
"preprocess",
"()",
"emulate",
"the",
"pre",
"-",
"processing",
"occuring",
"in",
"the",
"vgg16",
"caffe",
"prototxt",
"."
] | def preprocess(self, im):
"""
preprocess() emulate the pre-processing occuring in the vgg16 caffe
prototxt.
"""
im = np.float32(im)
im = im[:, :, ::-1] # change to BGR
im -= self.mean
im *= self.scale
im = im.transpose((2, 0, 1))
return im | [
"def",
"preprocess",
"(",
"self",
",",
"im",
")",
":",
"im",
"=",
"np",
".",
"float32",
"(",
"im",
")",
"im",
"=",
"im",
"[",
":",
",",
":",
",",
":",
":",
"-",
"1",
"]",
"# change to BGR",
"im",
"-=",
"self",
".",
"mean",
"im",
"*=",
"self",
".",
"scale",
"im",
"=",
"im",
".",
"transpose",
"(",
"(",
"2",
",",
"0",
",",
"1",
")",
")",
"return",
"im"
] | https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/examples/pycaffe/tools.py#L27-L39 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/numpy/_op.py | python | broadcast_to | (array, shape) | return _api_internal.broadcast_to(array, shape) | Broadcast an array to a new shape.
Parameters
----------
array : ndarray or scalar
The array to broadcast.
shape : tuple
The shape of the desired array.
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
MXNetError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules. | Broadcast an array to a new shape. | [
"Broadcast",
"an",
"array",
"to",
"a",
"new",
"shape",
"."
] | def broadcast_to(array, shape):
"""
Broadcast an array to a new shape.
Parameters
----------
array : ndarray or scalar
The array to broadcast.
shape : tuple
The shape of the desired array.
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
MXNetError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
"""
if _np.isscalar(array):
return full(shape, array)
return _api_internal.broadcast_to(array, shape) | [
"def",
"broadcast_to",
"(",
"array",
",",
"shape",
")",
":",
"if",
"_np",
".",
"isscalar",
"(",
"array",
")",
":",
"return",
"full",
"(",
"shape",
",",
"array",
")",
"return",
"_api_internal",
".",
"broadcast_to",
"(",
"array",
",",
"shape",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/_op.py#L292-L318 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/core/function/polymorphism/type_dispatch.py | python | TypeDispatchTable.clear | (self) | Deletes all targets in the table. | Deletes all targets in the table. | [
"Deletes",
"all",
"targets",
"in",
"the",
"table",
"."
] | def clear(self) -> None:
"""Deletes all targets in the table."""
self._targets.clear()
self._dispatch_cache.clear() | [
"def",
"clear",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_targets",
".",
"clear",
"(",
")",
"self",
".",
"_dispatch_cache",
".",
"clear",
"(",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/core/function/polymorphism/type_dispatch.py#L66-L69 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/diagnostic_updater/_diagnostic_updater.py | python | Updater.update | (self) | Causes the diagnostics to update if the inter-update interval
has been exceeded. | Causes the diagnostics to update if the inter-update interval
has been exceeded. | [
"Causes",
"the",
"diagnostics",
"to",
"update",
"if",
"the",
"inter",
"-",
"update",
"interval",
"has",
"been",
"exceeded",
"."
] | def update(self):
"""Causes the diagnostics to update if the inter-update interval
has been exceeded.
"""
self._check_diagnostic_period()
if rospy.Time.now() >= self.last_time + rospy.Duration(self.period):
self.force_update() | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_check_diagnostic_period",
"(",
")",
"if",
"rospy",
".",
"Time",
".",
"now",
"(",
")",
">=",
"self",
".",
"last_time",
"+",
"rospy",
".",
"Duration",
"(",
"self",
".",
"period",
")",
":",
"self",
".",
"force_update",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/diagnostic_updater/_diagnostic_updater.py#L241-L247 | ||
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | hasher-matcher-actioner/hmalib/common/s3_adapters.py | python | ThreatUpdateS3Store._get_datafile_object_keys | (self) | return [
item["Key"]
for item in self.s3_client.list_objects_v2(
Bucket=self.s3_bucket_name, Prefix=self.get_privacy_group_prefix()
)["Contents"]
if not item["Key"].endswith(self.CHECKPOINT_SUFFIX)
] | Returns all non-checkpoint datafile objects for the current privacy group. | Returns all non-checkpoint datafile objects for the current privacy group. | [
"Returns",
"all",
"non",
"-",
"checkpoint",
"datafile",
"objects",
"for",
"the",
"current",
"privacy",
"group",
"."
] | def _get_datafile_object_keys(self) -> t.Iterable[str]:
"""
Returns all non-checkpoint datafile objects for the current privacy group.
"""
return [
item["Key"]
for item in self.s3_client.list_objects_v2(
Bucket=self.s3_bucket_name, Prefix=self.get_privacy_group_prefix()
)["Contents"]
if not item["Key"].endswith(self.CHECKPOINT_SUFFIX)
] | [
"def",
"_get_datafile_object_keys",
"(",
"self",
")",
"->",
"t",
".",
"Iterable",
"[",
"str",
"]",
":",
"return",
"[",
"item",
"[",
"\"Key\"",
"]",
"for",
"item",
"in",
"self",
".",
"s3_client",
".",
"list_objects_v2",
"(",
"Bucket",
"=",
"self",
".",
"s3_bucket_name",
",",
"Prefix",
"=",
"self",
".",
"get_privacy_group_prefix",
"(",
")",
")",
"[",
"\"Contents\"",
"]",
"if",
"not",
"item",
"[",
"\"Key\"",
"]",
".",
"endswith",
"(",
"self",
".",
"CHECKPOINT_SUFFIX",
")",
"]"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/hasher-matcher-actioner/hmalib/common/s3_adapters.py#L396-L406 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/count-square-submatrices-with-all-ones.py | python | Solution.countSquares | (self, matrix) | return sum(x for row in matrix for x in row) | :type matrix: List[List[int]]
:rtype: int | :type matrix: List[List[int]]
:rtype: int | [
":",
"type",
"matrix",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"int"
] | def countSquares(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
for i in xrange(1, len(matrix)):
for j in xrange(1, len(matrix[0])):
if not matrix[i][j]:
continue
l = min(matrix[i-1][j], matrix[i][j-1])
matrix[i][j] = l+1 if matrix[i-l][j-l] else l
return sum(x for row in matrix for x in row) | [
"def",
"countSquares",
"(",
"self",
",",
"matrix",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"len",
"(",
"matrix",
")",
")",
":",
"for",
"j",
"in",
"xrange",
"(",
"1",
",",
"len",
"(",
"matrix",
"[",
"0",
"]",
")",
")",
":",
"if",
"not",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
":",
"continue",
"l",
"=",
"min",
"(",
"matrix",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"]",
",",
"matrix",
"[",
"i",
"]",
"[",
"j",
"-",
"1",
"]",
")",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"l",
"+",
"1",
"if",
"matrix",
"[",
"i",
"-",
"l",
"]",
"[",
"j",
"-",
"l",
"]",
"else",
"l",
"return",
"sum",
"(",
"x",
"for",
"row",
"in",
"matrix",
"for",
"x",
"in",
"row",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/count-square-submatrices-with-all-ones.py#L5-L16 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/cubecolourdialog.py | python | CustomPanel.PaintCustomColours | (self, dc) | Draws all the 16 subpanels with their custom colours.
:param `dc`: an instance of :class:`DC`. | Draws all the 16 subpanels with their custom colours. | [
"Draws",
"all",
"the",
"16",
"subpanels",
"with",
"their",
"custom",
"colours",
"."
] | def PaintCustomColours(self, dc):
"""
Draws all the 16 subpanels with their custom colours.
:param `dc`: an instance of :class:`DC`.
"""
for i in xrange(2):
for j in xrange(8):
ptr = i*8 + j
x = (j*(self._smallRectangleSize.x+self._gridSpacing)) + self._customColourRect.x
y = (i*(self._smallRectangleSize.y+self._gridSpacing)) + self._customColourRect.y
dc.SetPen(wx.BLACK_PEN)
brush = wx.Brush(self._customColours[ptr])
dc.SetBrush(brush)
dc.DrawRectangle(x, y, self._smallRectangleSize.x, self._smallRectangleSize.y) | [
"def",
"PaintCustomColours",
"(",
"self",
",",
"dc",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"2",
")",
":",
"for",
"j",
"in",
"xrange",
"(",
"8",
")",
":",
"ptr",
"=",
"i",
"*",
"8",
"+",
"j",
"x",
"=",
"(",
"j",
"*",
"(",
"self",
".",
"_smallRectangleSize",
".",
"x",
"+",
"self",
".",
"_gridSpacing",
")",
")",
"+",
"self",
".",
"_customColourRect",
".",
"x",
"y",
"=",
"(",
"i",
"*",
"(",
"self",
".",
"_smallRectangleSize",
".",
"y",
"+",
"self",
".",
"_gridSpacing",
")",
")",
"+",
"self",
".",
"_customColourRect",
".",
"y",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"BLACK_PEN",
")",
"brush",
"=",
"wx",
".",
"Brush",
"(",
"self",
".",
"_customColours",
"[",
"ptr",
"]",
")",
"dc",
".",
"SetBrush",
"(",
"brush",
")",
"dc",
".",
"DrawRectangle",
"(",
"x",
",",
"y",
",",
"self",
".",
"_smallRectangleSize",
".",
"x",
",",
"self",
".",
"_smallRectangleSize",
".",
"y",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/cubecolourdialog.py#L2749-L2768 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/cygprofile/patch_orderfile.py | python | _SectionsWithSuffixes | (symbol_to_sections_map) | return sections_with_suffixes | Finds sections which have suffixes applied.
Args:
symbol_to_sections_map: a map where the values are lists of section names.
Returns:
A set containing all section names which were seen with suffixes applied. | Finds sections which have suffixes applied. | [
"Finds",
"sections",
"which",
"have",
"suffixes",
"applied",
"."
] | def _SectionsWithSuffixes(symbol_to_sections_map):
"""Finds sections which have suffixes applied.
Args:
symbol_to_sections_map: a map where the values are lists of section names.
Returns:
A set containing all section names which were seen with suffixes applied.
"""
sections_with_suffixes = set()
for suffixed_sections in symbol_to_sections_map.itervalues():
for suffixed_section in suffixed_sections:
section = RemoveSuffixes(suffixed_section)
if section != suffixed_section:
sections_with_suffixes.add(section)
return sections_with_suffixes | [
"def",
"_SectionsWithSuffixes",
"(",
"symbol_to_sections_map",
")",
":",
"sections_with_suffixes",
"=",
"set",
"(",
")",
"for",
"suffixed_sections",
"in",
"symbol_to_sections_map",
".",
"itervalues",
"(",
")",
":",
"for",
"suffixed_section",
"in",
"suffixed_sections",
":",
"section",
"=",
"RemoveSuffixes",
"(",
"suffixed_section",
")",
"if",
"section",
"!=",
"suffixed_section",
":",
"sections_with_suffixes",
".",
"add",
"(",
"section",
")",
"return",
"sections_with_suffixes"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cygprofile/patch_orderfile.py#L344-L359 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/config_key.py | python | GetKeysDialog.set_modifiers_for_platform | (self) | Determine list of names of key modifiers for this platform.
The names are used to build Tk bindings -- it doesn't matter if the
keyboard has these keys; it matters if Tk understands them. The
order is also important: key binding equality depends on it, so
config-keys.def must use the same ordering. | Determine list of names of key modifiers for this platform. | [
"Determine",
"list",
"of",
"names",
"of",
"key",
"modifiers",
"for",
"this",
"platform",
"."
] | def set_modifiers_for_platform(self):
"""Determine list of names of key modifiers for this platform.
The names are used to build Tk bindings -- it doesn't matter if the
keyboard has these keys; it matters if Tk understands them. The
order is also important: key binding equality depends on it, so
config-keys.def must use the same ordering.
"""
if sys.platform == "darwin":
self.modifiers = ['Shift', 'Control', 'Option', 'Command']
else:
self.modifiers = ['Control', 'Alt', 'Shift']
self.modifier_label = {'Control': 'Ctrl'} | [
"def",
"set_modifiers_for_platform",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"self",
".",
"modifiers",
"=",
"[",
"'Shift'",
",",
"'Control'",
",",
"'Option'",
",",
"'Command'",
"]",
"else",
":",
"self",
".",
"modifiers",
"=",
"[",
"'Control'",
",",
"'Alt'",
",",
"'Shift'",
"]",
"self",
".",
"modifier_label",
"=",
"{",
"'Control'",
":",
"'Ctrl'",
"}"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/config_key.py#L202-L214 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/project.py | python | ProjectRegistry.load_jamfile | (self, dir, jamfile_module) | Load a Jamfile at the given directory. Returns nothing.
Will attempt to load the file as indicated by the JAMFILE patterns.
Effect of calling this rule twice with the same 'dir' is underfined. | Load a Jamfile at the given directory. Returns nothing.
Will attempt to load the file as indicated by the JAMFILE patterns.
Effect of calling this rule twice with the same 'dir' is underfined. | [
"Load",
"a",
"Jamfile",
"at",
"the",
"given",
"directory",
".",
"Returns",
"nothing",
".",
"Will",
"attempt",
"to",
"load",
"the",
"file",
"as",
"indicated",
"by",
"the",
"JAMFILE",
"patterns",
".",
"Effect",
"of",
"calling",
"this",
"rule",
"twice",
"with",
"the",
"same",
"dir",
"is",
"underfined",
"."
] | def load_jamfile(self, dir, jamfile_module):
"""Load a Jamfile at the given directory. Returns nothing.
Will attempt to load the file as indicated by the JAMFILE patterns.
Effect of calling this rule twice with the same 'dir' is underfined."""
assert isinstance(dir, basestring)
assert isinstance(jamfile_module, basestring)
# See if the Jamfile is where it should be.
is_jamroot = False
jamfile_to_load = b2.util.path.glob([dir], self.JAMROOT)
if jamfile_to_load:
if len(jamfile_to_load) > 1:
get_manager().errors()(
"Multiple Jamfiles found at '{}'\n"
"Filenames are: {}"
.format(dir, ' '.join(os.path.basename(j) for j in jamfile_to_load))
)
is_jamroot = True
jamfile_to_load = jamfile_to_load[0]
else:
jamfile_to_load = self.find_jamfile(dir)
dir = os.path.dirname(jamfile_to_load)
if not dir:
dir = "."
self.used_projects[jamfile_module] = []
# Now load the Jamfile in it's own context.
# The call to 'initialize' may load parent Jamfile, which might have
# 'use-project' statement that causes a second attempt to load the
# same project we're loading now. Checking inside .jamfile-modules
# prevents that second attempt from messing up.
if not jamfile_module in self.jamfile_modules:
previous_project = self.current_project
# Initialize the jamfile module before loading.
self.initialize(jamfile_module, dir, os.path.basename(jamfile_to_load))
if not jamfile_module in self.jamfile_modules:
saved_project = self.current_project
self.jamfile_modules[jamfile_module] = True
bjam.call("load", jamfile_module, jamfile_to_load)
if is_jamroot:
jamfile = self.find_jamfile(dir, no_errors=True)
if jamfile:
bjam.call("load", jamfile_module, jamfile)
# Now do some checks
if self.current_project != saved_project:
from textwrap import dedent
self.manager.errors()(dedent(
"""
The value of the .current-project variable has magically changed
after loading a Jamfile. This means some of the targets might be
defined a the wrong project.
after loading %s
expected value %s
actual value %s
"""
% (jamfile_module, saved_project, self.current_project)
))
self.end_load(previous_project)
if self.global_build_dir:
id = self.attributeDefault(jamfile_module, "id", None)
project_root = self.attribute(jamfile_module, "project-root")
location = self.attribute(jamfile_module, "location")
if location and project_root == dir:
# This is Jamroot
if not id:
# FIXME: go via errors module, so that contexts are
# shown?
print "warning: the --build-dir option was specified"
print "warning: but Jamroot at '%s'" % dir
print "warning: specified no project id"
print "warning: the --build-dir option will be ignored" | [
"def",
"load_jamfile",
"(",
"self",
",",
"dir",
",",
"jamfile_module",
")",
":",
"assert",
"isinstance",
"(",
"dir",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"jamfile_module",
",",
"basestring",
")",
"# See if the Jamfile is where it should be.",
"is_jamroot",
"=",
"False",
"jamfile_to_load",
"=",
"b2",
".",
"util",
".",
"path",
".",
"glob",
"(",
"[",
"dir",
"]",
",",
"self",
".",
"JAMROOT",
")",
"if",
"jamfile_to_load",
":",
"if",
"len",
"(",
"jamfile_to_load",
")",
">",
"1",
":",
"get_manager",
"(",
")",
".",
"errors",
"(",
")",
"(",
"\"Multiple Jamfiles found at '{}'\\n\"",
"\"Filenames are: {}\"",
".",
"format",
"(",
"dir",
",",
"' '",
".",
"join",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"j",
")",
"for",
"j",
"in",
"jamfile_to_load",
")",
")",
")",
"is_jamroot",
"=",
"True",
"jamfile_to_load",
"=",
"jamfile_to_load",
"[",
"0",
"]",
"else",
":",
"jamfile_to_load",
"=",
"self",
".",
"find_jamfile",
"(",
"dir",
")",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"jamfile_to_load",
")",
"if",
"not",
"dir",
":",
"dir",
"=",
"\".\"",
"self",
".",
"used_projects",
"[",
"jamfile_module",
"]",
"=",
"[",
"]",
"# Now load the Jamfile in it's own context.",
"# The call to 'initialize' may load parent Jamfile, which might have",
"# 'use-project' statement that causes a second attempt to load the",
"# same project we're loading now. Checking inside .jamfile-modules",
"# prevents that second attempt from messing up.",
"if",
"not",
"jamfile_module",
"in",
"self",
".",
"jamfile_modules",
":",
"previous_project",
"=",
"self",
".",
"current_project",
"# Initialize the jamfile module before loading.",
"self",
".",
"initialize",
"(",
"jamfile_module",
",",
"dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"jamfile_to_load",
")",
")",
"if",
"not",
"jamfile_module",
"in",
"self",
".",
"jamfile_modules",
":",
"saved_project",
"=",
"self",
".",
"current_project",
"self",
".",
"jamfile_modules",
"[",
"jamfile_module",
"]",
"=",
"True",
"bjam",
".",
"call",
"(",
"\"load\"",
",",
"jamfile_module",
",",
"jamfile_to_load",
")",
"if",
"is_jamroot",
":",
"jamfile",
"=",
"self",
".",
"find_jamfile",
"(",
"dir",
",",
"no_errors",
"=",
"True",
")",
"if",
"jamfile",
":",
"bjam",
".",
"call",
"(",
"\"load\"",
",",
"jamfile_module",
",",
"jamfile",
")",
"# Now do some checks",
"if",
"self",
".",
"current_project",
"!=",
"saved_project",
":",
"from",
"textwrap",
"import",
"dedent",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"dedent",
"(",
"\"\"\"\n The value of the .current-project variable has magically changed\n after loading a Jamfile. This means some of the targets might be\n defined a the wrong project.\n after loading %s\n expected value %s\n actual value %s\n \"\"\"",
"%",
"(",
"jamfile_module",
",",
"saved_project",
",",
"self",
".",
"current_project",
")",
")",
")",
"self",
".",
"end_load",
"(",
"previous_project",
")",
"if",
"self",
".",
"global_build_dir",
":",
"id",
"=",
"self",
".",
"attributeDefault",
"(",
"jamfile_module",
",",
"\"id\"",
",",
"None",
")",
"project_root",
"=",
"self",
".",
"attribute",
"(",
"jamfile_module",
",",
"\"project-root\"",
")",
"location",
"=",
"self",
".",
"attribute",
"(",
"jamfile_module",
",",
"\"location\"",
")",
"if",
"location",
"and",
"project_root",
"==",
"dir",
":",
"# This is Jamroot",
"if",
"not",
"id",
":",
"# FIXME: go via errors module, so that contexts are",
"# shown?",
"print",
"\"warning: the --build-dir option was specified\"",
"print",
"\"warning: but Jamroot at '%s'\"",
"%",
"dir",
"print",
"\"warning: specified no project id\"",
"print",
"\"warning: the --build-dir option will be ignored\""
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/project.py#L291-L370 | ||
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_endpoints.py | python | Connection.remote_container | (self) | return pn_connection_remote_container(self._impl) | The container identifier specified by the remote peer for this connection.
This will return ``None`` until the :const:'REMOTE_ACTIVE` state is
reached. See :class:`Endpoint` for more details on endpoint state.
Any (non ``None``) name returned by this operation will be valid until
the connection object is unbound from a transport or freed,
whichever happens sooner. | The container identifier specified by the remote peer for this connection. | [
"The",
"container",
"identifier",
"specified",
"by",
"the",
"remote",
"peer",
"for",
"this",
"connection",
"."
] | def remote_container(self) -> Optional[str]:
"""
The container identifier specified by the remote peer for this connection.
This will return ``None`` until the :const:'REMOTE_ACTIVE` state is
reached. See :class:`Endpoint` for more details on endpoint state.
Any (non ``None``) name returned by this operation will be valid until
the connection object is unbound from a transport or freed,
whichever happens sooner.
"""
return pn_connection_remote_container(self._impl) | [
"def",
"remote_container",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"pn_connection_remote_container",
"(",
"self",
".",
"_impl",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_endpoints.py#L294-L305 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/console/console_output.py | python | writeOut.__init__ | (self, shellOut, out=None, style=None) | This class allows writing to stdout and stderr | This class allows writing to stdout and stderr | [
"This",
"class",
"allows",
"writing",
"to",
"stdout",
"and",
"stderr"
] | def __init__(self, shellOut, out=None, style=None):
"""
This class allows writing to stdout and stderr
"""
super().__init__()
self.sO = shellOut
self.out = None
self.style = style
self.fire_keyboard_interrupt = False | [
"def",
"__init__",
"(",
"self",
",",
"shellOut",
",",
"out",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"sO",
"=",
"shellOut",
"self",
".",
"out",
"=",
"None",
"self",
".",
"style",
"=",
"style",
"self",
".",
"fire_keyboard_interrupt",
"=",
"False"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/console/console_output.py#L34-L42 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/sslproto.py | python | _SSLProtocolTransport.can_write_eof | (self) | return False | Return True if this transport supports write_eof(), False if not. | Return True if this transport supports write_eof(), False if not. | [
"Return",
"True",
"if",
"this",
"transport",
"supports",
"write_eof",
"()",
"False",
"if",
"not",
"."
] | def can_write_eof(self):
"""Return True if this transport supports write_eof(), False if not."""
return False | [
"def",
"can_write_eof",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/sslproto.py#L390-L392 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/sqs/message.py | python | RawMessage.get_body_encoded | (self) | return self.encode(self.get_body()) | This method is really a semi-private method used by the Queue.write
method when writing the contents of the message to SQS.
You probably shouldn't need to call this method in the normal course of events. | This method is really a semi-private method used by the Queue.write
method when writing the contents of the message to SQS.
You probably shouldn't need to call this method in the normal course of events. | [
"This",
"method",
"is",
"really",
"a",
"semi",
"-",
"private",
"method",
"used",
"by",
"the",
"Queue",
".",
"write",
"method",
"when",
"writing",
"the",
"contents",
"of",
"the",
"message",
"to",
"SQS",
".",
"You",
"probably",
"shouldn",
"t",
"need",
"to",
"call",
"this",
"method",
"in",
"the",
"normal",
"course",
"of",
"events",
"."
] | def get_body_encoded(self):
"""
This method is really a semi-private method used by the Queue.write
method when writing the contents of the message to SQS.
You probably shouldn't need to call this method in the normal course of events.
"""
return self.encode(self.get_body()) | [
"def",
"get_body_encoded",
"(",
"self",
")",
":",
"return",
"self",
".",
"encode",
"(",
"self",
".",
"get_body",
"(",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/sqs/message.py#L136-L142 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | external/tools/build/v2/build/project.py | python | ProjectRules.path_constant | (self, name, value) | Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root. | Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root. | [
"Declare",
"and",
"set",
"a",
"project",
"global",
"constant",
"whose",
"value",
"is",
"a",
"path",
".",
"The",
"path",
"is",
"adjusted",
"to",
"be",
"relative",
"to",
"the",
"invocation",
"directory",
".",
"The",
"given",
"value",
"path",
"is",
"taken",
"to",
"be",
"either",
"absolute",
"or",
"relative",
"to",
"this",
"project",
"root",
"."
] | def path_constant(self, name, value):
"""Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root."""
if len(value) > 1:
self.registry.manager.error()("path constant should have one element")
self.registry.current().add_constant(name[0], value[0], path=1) | [
"def",
"path_constant",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
">",
"1",
":",
"self",
".",
"registry",
".",
"manager",
".",
"error",
"(",
")",
"(",
"\"path constant should have one element\"",
")",
"self",
".",
"registry",
".",
"current",
"(",
")",
".",
"add_constant",
"(",
"name",
"[",
"0",
"]",
",",
"value",
"[",
"0",
"]",
",",
"path",
"=",
"1",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/build/project.py#L995-L1002 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetSelections | (*args, **kwargs) | return _stc.StyledTextCtrl_GetSelections(*args, **kwargs) | GetSelections(self) -> int
How many selections are there? | GetSelections(self) -> int | [
"GetSelections",
"(",
"self",
")",
"-",
">",
"int"
] | def GetSelections(*args, **kwargs):
"""
GetSelections(self) -> int
How many selections are there?
"""
return _stc.StyledTextCtrl_GetSelections(*args, **kwargs) | [
"def",
"GetSelections",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetSelections",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L6104-L6110 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/multi.py | python | MultiIndex.reorder_levels | (self, order) | return MultiIndex(
levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False
) | Rearrange levels using input order. May not drop or duplicate levels.
Parameters
----------
Returns
-------
MultiIndex | Rearrange levels using input order. May not drop or duplicate levels. | [
"Rearrange",
"levels",
"using",
"input",
"order",
".",
"May",
"not",
"drop",
"or",
"duplicate",
"levels",
"."
] | def reorder_levels(self, order):
"""
Rearrange levels using input order. May not drop or duplicate levels.
Parameters
----------
Returns
-------
MultiIndex
"""
order = [self._get_level_number(i) for i in order]
if len(order) != self.nlevels:
raise AssertionError(
f"Length of order must be same as number of levels ({self.nlevels}),"
f" got {len(order)}"
)
new_levels = [self.levels[i] for i in order]
new_codes = [self.codes[i] for i in order]
new_names = [self.names[i] for i in order]
return MultiIndex(
levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False
) | [
"def",
"reorder_levels",
"(",
"self",
",",
"order",
")",
":",
"order",
"=",
"[",
"self",
".",
"_get_level_number",
"(",
"i",
")",
"for",
"i",
"in",
"order",
"]",
"if",
"len",
"(",
"order",
")",
"!=",
"self",
".",
"nlevels",
":",
"raise",
"AssertionError",
"(",
"f\"Length of order must be same as number of levels ({self.nlevels}),\"",
"f\" got {len(order)}\"",
")",
"new_levels",
"=",
"[",
"self",
".",
"levels",
"[",
"i",
"]",
"for",
"i",
"in",
"order",
"]",
"new_codes",
"=",
"[",
"self",
".",
"codes",
"[",
"i",
"]",
"for",
"i",
"in",
"order",
"]",
"new_names",
"=",
"[",
"self",
".",
"names",
"[",
"i",
"]",
"for",
"i",
"in",
"order",
"]",
"return",
"MultiIndex",
"(",
"levels",
"=",
"new_levels",
",",
"codes",
"=",
"new_codes",
",",
"names",
"=",
"new_names",
",",
"verify_integrity",
"=",
"False",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/multi.py#L2178-L2201 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/decimal.py | python | Context.scaleb | (self, a, b) | return a.scaleb(b, context=self) | Returns the first operand after adding the second value its exp.
>>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Decimal('0.0750')
>>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Decimal('7.50')
>>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Decimal('7.50E+3')
>>> ExtendedContext.scaleb(1, 4)
Decimal('1E+4')
>>> ExtendedContext.scaleb(Decimal(1), 4)
Decimal('1E+4')
>>> ExtendedContext.scaleb(1, Decimal(4))
Decimal('1E+4') | Returns the first operand after adding the second value its exp. | [
"Returns",
"the",
"first",
"operand",
"after",
"adding",
"the",
"second",
"value",
"its",
"exp",
"."
] | def scaleb (self, a, b):
"""Returns the first operand after adding the second value its exp.
>>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Decimal('0.0750')
>>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Decimal('7.50')
>>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Decimal('7.50E+3')
>>> ExtendedContext.scaleb(1, 4)
Decimal('1E+4')
>>> ExtendedContext.scaleb(Decimal(1), 4)
Decimal('1E+4')
>>> ExtendedContext.scaleb(1, Decimal(4))
Decimal('1E+4')
"""
a = _convert_other(a, raiseit=True)
return a.scaleb(b, context=self) | [
"def",
"scaleb",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"scaleb",
"(",
"b",
",",
"context",
"=",
"self",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L5236-L5253 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | GraphicsGradientStops.__init__ | (self, *args, **kwargs) | __init__(self, Colour startCol=wxTransparentColour, Colour endCol=wxTransparentColour) -> GraphicsGradientStops | __init__(self, Colour startCol=wxTransparentColour, Colour endCol=wxTransparentColour) -> GraphicsGradientStops | [
"__init__",
"(",
"self",
"Colour",
"startCol",
"=",
"wxTransparentColour",
"Colour",
"endCol",
"=",
"wxTransparentColour",
")",
"-",
">",
"GraphicsGradientStops"
] | def __init__(self, *args, **kwargs):
"""__init__(self, Colour startCol=wxTransparentColour, Colour endCol=wxTransparentColour) -> GraphicsGradientStops"""
_gdi_.GraphicsGradientStops_swiginit(self,_gdi_.new_GraphicsGradientStops(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gdi_",
".",
"GraphicsGradientStops_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_GraphicsGradientStops",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L6078-L6080 | ||
ideawu/ssdb | f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4 | deps/cpy/antlr3/streams.py | python | IntStream.seek | (self, index) | Set the input cursor to the position indicated by index. This is
normally used to seek ahead in the input stream. No buffering is
required to do this unless you know your stream will use seek to
move backwards such as when backtracking.
This is different from rewind in its multi-directional
requirement and in that its argument is strictly an input cursor
(index).
For char streams, seeking forward must update the stream state such
as line number. For seeking backwards, you will be presumably
backtracking using the mark/rewind mechanism that restores state and
so this method does not need to update state when seeking backwards.
Currently, this method is only used for efficient backtracking using
memoization, but in the future it may be used for incremental parsing.
The index is 0..n-1. A seek to position i means that LA(1) will
return the ith symbol. So, seeking to 0 means LA(1) will return the
first element in the stream. | Set the input cursor to the position indicated by index. This is
normally used to seek ahead in the input stream. No buffering is
required to do this unless you know your stream will use seek to
move backwards such as when backtracking. | [
"Set",
"the",
"input",
"cursor",
"to",
"the",
"position",
"indicated",
"by",
"index",
".",
"This",
"is",
"normally",
"used",
"to",
"seek",
"ahead",
"in",
"the",
"input",
"stream",
".",
"No",
"buffering",
"is",
"required",
"to",
"do",
"this",
"unless",
"you",
"know",
"your",
"stream",
"will",
"use",
"seek",
"to",
"move",
"backwards",
"such",
"as",
"when",
"backtracking",
"."
] | def seek(self, index):
"""
Set the input cursor to the position indicated by index. This is
normally used to seek ahead in the input stream. No buffering is
required to do this unless you know your stream will use seek to
move backwards such as when backtracking.
This is different from rewind in its multi-directional
requirement and in that its argument is strictly an input cursor
(index).
For char streams, seeking forward must update the stream state such
as line number. For seeking backwards, you will be presumably
backtracking using the mark/rewind mechanism that restores state and
so this method does not need to update state when seeking backwards.
Currently, this method is only used for efficient backtracking using
memoization, but in the future it may be used for incremental parsing.
The index is 0..n-1. A seek to position i means that LA(1) will
return the ith symbol. So, seeking to 0 means LA(1) will return the
first element in the stream.
"""
raise NotImplementedError | [
"def",
"seek",
"(",
"self",
",",
"index",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/streams.py#L135-L159 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/textwrap.py | python | TextWrapper.wrap | (self, text) | return self._wrap_chunks(chunks) | wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characters (including newline) are
converted to space. | wrap(text : string) -> [string] | [
"wrap",
"(",
"text",
":",
"string",
")",
"-",
">",
"[",
"string",
"]"
] | def wrap(self, text):
"""wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characters (including newline) are
converted to space.
"""
text = self._munge_whitespace(text)
chunks = self._split(text)
if self.fix_sentence_endings:
self._fix_sentence_endings(chunks)
return self._wrap_chunks(chunks) | [
"def",
"wrap",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"self",
".",
"_munge_whitespace",
"(",
"text",
")",
"chunks",
"=",
"self",
".",
"_split",
"(",
"text",
")",
"if",
"self",
".",
"fix_sentence_endings",
":",
"self",
".",
"_fix_sentence_endings",
"(",
"chunks",
")",
"return",
"self",
".",
"_wrap_chunks",
"(",
"chunks",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/textwrap.py#L316-L329 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_grid.py | python | ToggleGrid.Activated | (self) | Execute when the command is called. | Execute when the command is called. | [
"Execute",
"when",
"the",
"command",
"is",
"called",
"."
] | def Activated(self):
"""Execute when the command is called."""
super(ToggleGrid, self).Activated()
if hasattr(Gui, "Snapper"):
Gui.Snapper.setTrackers()
if Gui.Snapper.grid:
if Gui.Snapper.grid.Visible:
Gui.Snapper.grid.off()
Gui.Snapper.forceGridOff = True
else:
Gui.Snapper.grid.on()
Gui.Snapper.forceGridOff = False | [
"def",
"Activated",
"(",
"self",
")",
":",
"super",
"(",
"ToggleGrid",
",",
"self",
")",
".",
"Activated",
"(",
")",
"if",
"hasattr",
"(",
"Gui",
",",
"\"Snapper\"",
")",
":",
"Gui",
".",
"Snapper",
".",
"setTrackers",
"(",
")",
"if",
"Gui",
".",
"Snapper",
".",
"grid",
":",
"if",
"Gui",
".",
"Snapper",
".",
"grid",
".",
"Visible",
":",
"Gui",
".",
"Snapper",
".",
"grid",
".",
"off",
"(",
")",
"Gui",
".",
"Snapper",
".",
"forceGridOff",
"=",
"True",
"else",
":",
"Gui",
".",
"Snapper",
".",
"grid",
".",
"on",
"(",
")",
"Gui",
".",
"Snapper",
".",
"forceGridOff",
"=",
"False"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_grid.py#L64-L76 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | clang/utils/analyzer/CmpRuns.py | python | compare_results | (results_old: AnalysisRun, results_new: AnalysisRun,
histogram: Optional[HistogramType] = None
) | return res | compare_results - Generate a relation from diagnostics in run A to
diagnostics in run B.
The result is the relation as a list of triples (a, b) where
each element {a,b} is None or a matching element from the respective run | compare_results - Generate a relation from diagnostics in run A to
diagnostics in run B. | [
"compare_results",
"-",
"Generate",
"a",
"relation",
"from",
"diagnostics",
"in",
"run",
"A",
"to",
"diagnostics",
"in",
"run",
"B",
"."
] | def compare_results(results_old: AnalysisRun, results_new: AnalysisRun,
histogram: Optional[HistogramType] = None
) -> ComparisonResult:
"""
compare_results - Generate a relation from diagnostics in run A to
diagnostics in run B.
The result is the relation as a list of triples (a, b) where
each element {a,b} is None or a matching element from the respective run
"""
res = ComparisonResult()
# Map size_before -> size_after
path_difference_data: List[float] = []
diags_old = get_grouped_diagnostics(results_old.diagnostics)
diags_new = get_grouped_diagnostics(results_new.diagnostics)
locations_old = set(diags_old.keys())
locations_new = set(diags_new.keys())
common_locations = locations_old & locations_new
for location in common_locations:
old = diags_old[location]
new = diags_new[location]
# Quadratic algorithms in this part are fine because 'old' and 'new'
# are most commonly of size 1.
common: Set[AnalysisDiagnostic] = set()
for a in old:
for b in new:
if a.get_issue_identifier() == b.get_issue_identifier():
a_path_len = a.get_path_length()
b_path_len = b.get_path_length()
if a_path_len != b_path_len:
if histogram == HistogramType.RELATIVE:
path_difference_data.append(
float(a_path_len) / b_path_len)
elif histogram == HistogramType.LOG_RELATIVE:
path_difference_data.append(
log(float(a_path_len) / b_path_len))
elif histogram == HistogramType.ABSOLUTE:
path_difference_data.append(
a_path_len - b_path_len)
res.add_common(b)
common.add(a)
old = filter_issues(old, common)
new = filter_issues(new, common)
common = set()
for a in old:
for b in new:
if a.is_similar_to(b):
res.add_changed(a, b)
common.add(a)
common.add(b)
old = filter_issues(old, common)
new = filter_issues(new, common)
# Whatever is left in 'old' doesn't have a corresponding diagnostic
# in 'new', so we need to mark it as 'removed'.
for a in old:
res.add_removed(a)
# Whatever is left in 'new' doesn't have a corresponding diagnostic
# in 'old', so we need to mark it as 'added'.
for b in new:
res.add_added(b)
only_old_locations = locations_old - common_locations
for location in only_old_locations:
for a in diags_old[location]:
# These locations have been found only in the old build, so we
# need to mark all of therm as 'removed'
res.add_removed(a)
only_new_locations = locations_new - common_locations
for location in only_new_locations:
for b in diags_new[location]:
# These locations have been found only in the new build, so we
# need to mark all of therm as 'added'
res.add_added(b)
# FIXME: Add fuzzy matching. One simple and possible effective idea would
# be to bin the diagnostics, print them in a normalized form (based solely
# on the structure of the diagnostic), compute the diff, then use that as
# the basis for matching. This has the nice property that we don't depend
# in any way on the diagnostic format.
if histogram:
from matplotlib import pyplot
pyplot.hist(path_difference_data, bins=100)
pyplot.show()
return res | [
"def",
"compare_results",
"(",
"results_old",
":",
"AnalysisRun",
",",
"results_new",
":",
"AnalysisRun",
",",
"histogram",
":",
"Optional",
"[",
"HistogramType",
"]",
"=",
"None",
")",
"->",
"ComparisonResult",
":",
"res",
"=",
"ComparisonResult",
"(",
")",
"# Map size_before -> size_after",
"path_difference_data",
":",
"List",
"[",
"float",
"]",
"=",
"[",
"]",
"diags_old",
"=",
"get_grouped_diagnostics",
"(",
"results_old",
".",
"diagnostics",
")",
"diags_new",
"=",
"get_grouped_diagnostics",
"(",
"results_new",
".",
"diagnostics",
")",
"locations_old",
"=",
"set",
"(",
"diags_old",
".",
"keys",
"(",
")",
")",
"locations_new",
"=",
"set",
"(",
"diags_new",
".",
"keys",
"(",
")",
")",
"common_locations",
"=",
"locations_old",
"&",
"locations_new",
"for",
"location",
"in",
"common_locations",
":",
"old",
"=",
"diags_old",
"[",
"location",
"]",
"new",
"=",
"diags_new",
"[",
"location",
"]",
"# Quadratic algorithms in this part are fine because 'old' and 'new'",
"# are most commonly of size 1.",
"common",
":",
"Set",
"[",
"AnalysisDiagnostic",
"]",
"=",
"set",
"(",
")",
"for",
"a",
"in",
"old",
":",
"for",
"b",
"in",
"new",
":",
"if",
"a",
".",
"get_issue_identifier",
"(",
")",
"==",
"b",
".",
"get_issue_identifier",
"(",
")",
":",
"a_path_len",
"=",
"a",
".",
"get_path_length",
"(",
")",
"b_path_len",
"=",
"b",
".",
"get_path_length",
"(",
")",
"if",
"a_path_len",
"!=",
"b_path_len",
":",
"if",
"histogram",
"==",
"HistogramType",
".",
"RELATIVE",
":",
"path_difference_data",
".",
"append",
"(",
"float",
"(",
"a_path_len",
")",
"/",
"b_path_len",
")",
"elif",
"histogram",
"==",
"HistogramType",
".",
"LOG_RELATIVE",
":",
"path_difference_data",
".",
"append",
"(",
"log",
"(",
"float",
"(",
"a_path_len",
")",
"/",
"b_path_len",
")",
")",
"elif",
"histogram",
"==",
"HistogramType",
".",
"ABSOLUTE",
":",
"path_difference_data",
".",
"append",
"(",
"a_path_len",
"-",
"b_path_len",
")",
"res",
".",
"add_common",
"(",
"b",
")",
"common",
".",
"add",
"(",
"a",
")",
"old",
"=",
"filter_issues",
"(",
"old",
",",
"common",
")",
"new",
"=",
"filter_issues",
"(",
"new",
",",
"common",
")",
"common",
"=",
"set",
"(",
")",
"for",
"a",
"in",
"old",
":",
"for",
"b",
"in",
"new",
":",
"if",
"a",
".",
"is_similar_to",
"(",
"b",
")",
":",
"res",
".",
"add_changed",
"(",
"a",
",",
"b",
")",
"common",
".",
"add",
"(",
"a",
")",
"common",
".",
"add",
"(",
"b",
")",
"old",
"=",
"filter_issues",
"(",
"old",
",",
"common",
")",
"new",
"=",
"filter_issues",
"(",
"new",
",",
"common",
")",
"# Whatever is left in 'old' doesn't have a corresponding diagnostic",
"# in 'new', so we need to mark it as 'removed'.",
"for",
"a",
"in",
"old",
":",
"res",
".",
"add_removed",
"(",
"a",
")",
"# Whatever is left in 'new' doesn't have a corresponding diagnostic",
"# in 'old', so we need to mark it as 'added'.",
"for",
"b",
"in",
"new",
":",
"res",
".",
"add_added",
"(",
"b",
")",
"only_old_locations",
"=",
"locations_old",
"-",
"common_locations",
"for",
"location",
"in",
"only_old_locations",
":",
"for",
"a",
"in",
"diags_old",
"[",
"location",
"]",
":",
"# These locations have been found only in the old build, so we",
"# need to mark all of therm as 'removed'",
"res",
".",
"add_removed",
"(",
"a",
")",
"only_new_locations",
"=",
"locations_new",
"-",
"common_locations",
"for",
"location",
"in",
"only_new_locations",
":",
"for",
"b",
"in",
"diags_new",
"[",
"location",
"]",
":",
"# These locations have been found only in the new build, so we",
"# need to mark all of therm as 'added'",
"res",
".",
"add_added",
"(",
"b",
")",
"# FIXME: Add fuzzy matching. One simple and possible effective idea would",
"# be to bin the diagnostics, print them in a normalized form (based solely",
"# on the structure of the diagnostic), compute the diff, then use that as",
"# the basis for matching. This has the nice property that we don't depend",
"# in any way on the diagnostic format.",
"if",
"histogram",
":",
"from",
"matplotlib",
"import",
"pyplot",
"pyplot",
".",
"hist",
"(",
"path_difference_data",
",",
"bins",
"=",
"100",
")",
"pyplot",
".",
"show",
"(",
")",
"return",
"res"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/utils/analyzer/CmpRuns.py#L347-L450 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/ContactStructuralMechanicsApplication/python_scripts/explicit_penalty_contact_process.py | python | ExplicitPenaltyContactProcess.ExecuteBeforeOutputStep | (self) | This method is executed right before the ouput process computation
Keyword arguments:
self -- It signifies an instance of a class. | This method is executed right before the ouput process computation | [
"This",
"method",
"is",
"executed",
"right",
"before",
"the",
"ouput",
"process",
"computation"
] | def ExecuteBeforeOutputStep(self):
""" This method is executed right before the ouput process computation
Keyword arguments:
self -- It signifies an instance of a class.
"""
# We call to the base process
super().ExecuteBeforeOutputStep() | [
"def",
"ExecuteBeforeOutputStep",
"(",
"self",
")",
":",
"# We call to the base process",
"super",
"(",
")",
".",
"ExecuteBeforeOutputStep",
"(",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ContactStructuralMechanicsApplication/python_scripts/explicit_penalty_contact_process.py#L199-L207 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/pycparser/c_generator.py | python | CGenerator._is_simple_node | (self, n) | return isinstance(n, (c_ast.Constant, c_ast.ID, c_ast.ArrayRef,
c_ast.StructRef, c_ast.FuncCall)) | Returns True for nodes that are "simple" - i.e. nodes that always
have higher precedence than operators. | Returns True for nodes that are "simple" - i.e. nodes that always
have higher precedence than operators. | [
"Returns",
"True",
"for",
"nodes",
"that",
"are",
"simple",
"-",
"i",
".",
"e",
".",
"nodes",
"that",
"always",
"have",
"higher",
"precedence",
"than",
"operators",
"."
] | def _is_simple_node(self, n):
""" Returns True for nodes that are "simple" - i.e. nodes that always
have higher precedence than operators.
"""
return isinstance(n, (c_ast.Constant, c_ast.ID, c_ast.ArrayRef,
c_ast.StructRef, c_ast.FuncCall)) | [
"def",
"_is_simple_node",
"(",
"self",
",",
"n",
")",
":",
"return",
"isinstance",
"(",
"n",
",",
"(",
"c_ast",
".",
"Constant",
",",
"c_ast",
".",
"ID",
",",
"c_ast",
".",
"ArrayRef",
",",
"c_ast",
".",
"StructRef",
",",
"c_ast",
".",
"FuncCall",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/pycparser/c_generator.py#L439-L444 | |
may0324/DeepCompression-caffe | 0aff6c1287bda4cfc7f378ed8a16524e1afabd8c | scripts/cpp_lint.py | python | _CppLintState.IncrementErrorCount | (self, category) | Bumps the module's error statistic. | Bumps the module's error statistic. | [
"Bumps",
"the",
"module",
"s",
"error",
"statistic",
"."
] | def IncrementErrorCount(self, category):
"""Bumps the module's error statistic."""
self.error_count += 1
if self.counting in ('toplevel', 'detailed'):
if self.counting != 'detailed':
category = category.split('/')[0]
if category not in self.errors_by_category:
self.errors_by_category[category] = 0
self.errors_by_category[category] += 1 | [
"def",
"IncrementErrorCount",
"(",
"self",
",",
"category",
")",
":",
"self",
".",
"error_count",
"+=",
"1",
"if",
"self",
".",
"counting",
"in",
"(",
"'toplevel'",
",",
"'detailed'",
")",
":",
"if",
"self",
".",
"counting",
"!=",
"'detailed'",
":",
"category",
"=",
"category",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"if",
"category",
"not",
"in",
"self",
".",
"errors_by_category",
":",
"self",
".",
"errors_by_category",
"[",
"category",
"]",
"=",
"0",
"self",
".",
"errors_by_category",
"[",
"category",
"]",
"+=",
"1"
] | https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/scripts/cpp_lint.py#L747-L755 | ||
ucbrise/confluo | 578883a4f7fbbb4aea78c342d366f5122ef598f7 | pyclient/confluo/rpc/rpc_service.py | python | Client.append_batch | (self, mid, batch) | return self.recv_append_batch() | Parameters:
- mid
- batch | Parameters:
- mid
- batch | [
"Parameters",
":",
"-",
"mid",
"-",
"batch"
] | def append_batch(self, mid, batch):
"""
Parameters:
- mid
- batch
"""
self.send_append_batch(mid, batch)
return self.recv_append_batch() | [
"def",
"append_batch",
"(",
"self",
",",
"mid",
",",
"batch",
")",
":",
"self",
".",
"send_append_batch",
"(",
"mid",
",",
"batch",
")",
"return",
"self",
".",
"recv_append_batch",
"(",
")"
] | https://github.com/ucbrise/confluo/blob/578883a4f7fbbb4aea78c342d366f5122ef598f7/pyclient/confluo/rpc/rpc_service.py#L827-L835 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/inputs/outputs.py | python | InputTrajectory.__init__ | (self, help=None, default=None, dtype=None, dimension=None) | Initializes InputTrajectory.
Just calls the parent initialization function with appropriate arguments. | Initializes InputTrajectory. | [
"Initializes",
"InputTrajectory",
"."
] | def __init__(self, help=None, default=None, dtype=None, dimension=None):
"""Initializes InputTrajectory.
Just calls the parent initialization function with appropriate arguments.
"""
super(InputTrajectory,self).__init__(help=help, default=default, dtype=str, dimension=dimension) | [
"def",
"__init__",
"(",
"self",
",",
"help",
"=",
"None",
",",
"default",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"dimension",
"=",
"None",
")",
":",
"super",
"(",
"InputTrajectory",
",",
"self",
")",
".",
"__init__",
"(",
"help",
"=",
"help",
",",
"default",
"=",
"default",
",",
"dtype",
"=",
"str",
",",
"dimension",
"=",
"dimension",
")"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/outputs.py#L127-L133 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TextAttr.SetListStyleName | (*args, **kwargs) | return _controls_.TextAttr_SetListStyleName(*args, **kwargs) | SetListStyleName(self, String name) | SetListStyleName(self, String name) | [
"SetListStyleName",
"(",
"self",
"String",
"name",
")"
] | def SetListStyleName(*args, **kwargs):
"""SetListStyleName(self, String name)"""
return _controls_.TextAttr_SetListStyleName(*args, **kwargs) | [
"def",
"SetListStyleName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_SetListStyleName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1583-L1585 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py | python | Grid.move_column | (self, from_, to, offset) | Moves the range of columns from position FROM through TO by
the distance indicated by OFFSET. For example, move_column(2, 4, 1)
moves the columns 2,3,4 to columns 3,4,5. | Moves the range of columns from position FROM through TO by
the distance indicated by OFFSET. For example, move_column(2, 4, 1)
moves the columns 2,3,4 to columns 3,4,5. | [
"Moves",
"the",
"range",
"of",
"columns",
"from",
"position",
"FROM",
"through",
"TO",
"by",
"the",
"distance",
"indicated",
"by",
"OFFSET",
".",
"For",
"example",
"move_column",
"(",
"2",
"4",
"1",
")",
"moves",
"the",
"columns",
"2",
"3",
"4",
"to",
"columns",
"3",
"4",
"5",
"."
] | def move_column(self, from_, to, offset):
"""Moves the range of columns from position FROM through TO by
the distance indicated by OFFSET. For example, move_column(2, 4, 1)
moves the columns 2,3,4 to columns 3,4,5."""
self.tk.call(self, 'move', 'column', from_, to, offset) | [
"def",
"move_column",
"(",
"self",
",",
"from_",
",",
"to",
",",
"offset",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'move'",
",",
"'column'",
",",
"from_",
",",
"to",
",",
"offset",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py#L1876-L1880 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/_config/localization.py | python | can_set_locale | (lc: str, lc_var: int = locale.LC_ALL) | Check to see if we can set a locale, and subsequently get the locale,
without raising an Exception.
Parameters
----------
lc : str
The locale to attempt to set.
lc_var : int, default `locale.LC_ALL`
The category of the locale being set.
Returns
-------
bool
Whether the passed locale can be set | Check to see if we can set a locale, and subsequently get the locale,
without raising an Exception. | [
"Check",
"to",
"see",
"if",
"we",
"can",
"set",
"a",
"locale",
"and",
"subsequently",
"get",
"the",
"locale",
"without",
"raising",
"an",
"Exception",
"."
] | def can_set_locale(lc: str, lc_var: int = locale.LC_ALL) -> bool:
"""
Check to see if we can set a locale, and subsequently get the locale,
without raising an Exception.
Parameters
----------
lc : str
The locale to attempt to set.
lc_var : int, default `locale.LC_ALL`
The category of the locale being set.
Returns
-------
bool
Whether the passed locale can be set
"""
try:
with set_locale(lc, lc_var=lc_var):
pass
except (ValueError, locale.Error):
# horrible name for a Exception subclass
return False
else:
return True | [
"def",
"can_set_locale",
"(",
"lc",
":",
"str",
",",
"lc_var",
":",
"int",
"=",
"locale",
".",
"LC_ALL",
")",
"->",
"bool",
":",
"try",
":",
"with",
"set_locale",
"(",
"lc",
",",
"lc_var",
"=",
"lc_var",
")",
":",
"pass",
"except",
"(",
"ValueError",
",",
"locale",
".",
"Error",
")",
":",
"# horrible name for a Exception subclass",
"return",
"False",
"else",
":",
"return",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/_config/localization.py#L47-L71 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ListCtrl._setCallbackInfo | (*args, **kwargs) | return _controls_.ListCtrl__setCallbackInfo(*args, **kwargs) | _setCallbackInfo(self, PyObject self, PyObject _class) | _setCallbackInfo(self, PyObject self, PyObject _class) | [
"_setCallbackInfo",
"(",
"self",
"PyObject",
"self",
"PyObject",
"_class",
")"
] | def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _controls_.ListCtrl__setCallbackInfo(*args, **kwargs) | [
"def",
"_setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl__setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4454-L4456 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/core/additions/qgssettingsentry.py | python | PyQgsSettingsEntryEnumFlag.settingsType | (self) | return self.SettingsType.EnumFlag | Get the settings entry type. | Get the settings entry type. | [
"Get",
"the",
"settings",
"entry",
"type",
"."
] | def settingsType(self):
"""
Get the settings entry type.
"""
return self.SettingsType.EnumFlag | [
"def",
"settingsType",
"(",
"self",
")",
":",
"return",
"self",
".",
"SettingsType",
".",
"EnumFlag"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/core/additions/qgssettingsentry.py#L118-L123 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/sysconfig.py | python | get_scheme_names | () | return tuple(sorted(_SCHEMES.sections())) | Return a tuple containing the schemes names. | Return a tuple containing the schemes names. | [
"Return",
"a",
"tuple",
"containing",
"the",
"schemes",
"names",
"."
] | def get_scheme_names():
"""Return a tuple containing the schemes names."""
return tuple(sorted(_SCHEMES.sections())) | [
"def",
"get_scheme_names",
"(",
")",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"_SCHEMES",
".",
"sections",
"(",
")",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/sysconfig.py#L429-L431 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/processpool.py | python | ProcessPoolTransferFuture.__init__ | (self, monitor, meta) | The future associated to a submitted process pool transfer request
:type monitor: TransferMonitor
:param monitor: The monitor associated to the proccess pool downloader
:type meta: ProcessPoolTransferMeta
:param meta: The metadata associated to the request. This object
is visible to the requester. | The future associated to a submitted process pool transfer request | [
"The",
"future",
"associated",
"to",
"a",
"submitted",
"process",
"pool",
"transfer",
"request"
] | def __init__(self, monitor, meta):
"""The future associated to a submitted process pool transfer request
:type monitor: TransferMonitor
:param monitor: The monitor associated to the proccess pool downloader
:type meta: ProcessPoolTransferMeta
:param meta: The metadata associated to the request. This object
is visible to the requester.
"""
self._monitor = monitor
self._meta = meta | [
"def",
"__init__",
"(",
"self",
",",
"monitor",
",",
"meta",
")",
":",
"self",
".",
"_monitor",
"=",
"monitor",
"self",
".",
"_meta",
"=",
"meta"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/processpool.py#L475-L486 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/util.py | python | wrap_data_api_statical_func | (func) | return _wrap_api_creation_func | A convenience decorator for wrapping data apis standardized statical functions to provide
context keyward backward compatibility
Parameters
----------
func : a numpy-compatible array statical function to be wrapped for context keyward change.
Returns
-------
Function
A function wrapped with context keyward changes. | A convenience decorator for wrapping data apis standardized statical functions to provide
context keyward backward compatibility
Parameters
----------
func : a numpy-compatible array statical function to be wrapped for context keyward change.
Returns
-------
Function
A function wrapped with context keyward changes. | [
"A",
"convenience",
"decorator",
"for",
"wrapping",
"data",
"apis",
"standardized",
"statical",
"functions",
"to",
"provide",
"context",
"keyward",
"backward",
"compatibility",
"Parameters",
"----------",
"func",
":",
"a",
"numpy",
"-",
"compatible",
"array",
"statical",
"function",
"to",
"be",
"wrapped",
"for",
"context",
"keyward",
"change",
".",
"Returns",
"-------",
"Function",
"A",
"function",
"wrapped",
"with",
"context",
"keyward",
"changes",
"."
] | def wrap_data_api_statical_func(func):
"""
A convenience decorator for wrapping data apis standardized statical functions to provide
context keyward backward compatibility
Parameters
----------
func : a numpy-compatible array statical function to be wrapped for context keyward change.
Returns
-------
Function
A function wrapped with context keyward changes.
"""
@functools.wraps(func)
def _wrap_api_creation_func(*args, **kwargs):
if len(kwargs) != 0:
correction = kwargs.pop('ddof', None)
if correction is not None:
kwargs['correction'] = correction
return func(*args, **kwargs)
return _wrap_api_creation_func | [
"def",
"wrap_data_api_statical_func",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_wrap_api_creation_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"0",
":",
"correction",
"=",
"kwargs",
".",
"pop",
"(",
"'ddof'",
",",
"None",
")",
"if",
"correction",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'correction'",
"]",
"=",
"correction",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrap_api_creation_func"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/util.py#L653-L674 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/ntpath.py | python | relpath | (path, start=curdir) | return join(*rel_list) | Return a relative version of a path | Return a relative version of a path | [
"Return",
"a",
"relative",
"version",
"of",
"a",
"path"
] | def relpath(path, start=curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_is_unc, start_prefix, start_list = _abspath_split(start)
path_is_unc, path_prefix, path_list = _abspath_split(path)
if path_is_unc ^ start_is_unc:
raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
% (path, start))
if path_prefix.lower() != start_prefix.lower():
if path_is_unc:
raise ValueError("path is on UNC root %s, start on UNC root %s"
% (path_prefix, start_prefix))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_prefix, start_prefix))
# Work out how much of the filepath is shared by start and path.
i = 0
for e1, e2 in zip(start_list, path_list):
if e1.lower() != e2.lower():
break
i += 1
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list) | [
"def",
"relpath",
"(",
"path",
",",
"start",
"=",
"curdir",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"no path specified\"",
")",
"start_is_unc",
",",
"start_prefix",
",",
"start_list",
"=",
"_abspath_split",
"(",
"start",
")",
"path_is_unc",
",",
"path_prefix",
",",
"path_list",
"=",
"_abspath_split",
"(",
"path",
")",
"if",
"path_is_unc",
"^",
"start_is_unc",
":",
"raise",
"ValueError",
"(",
"\"Cannot mix UNC and non-UNC paths (%s and %s)\"",
"%",
"(",
"path",
",",
"start",
")",
")",
"if",
"path_prefix",
".",
"lower",
"(",
")",
"!=",
"start_prefix",
".",
"lower",
"(",
")",
":",
"if",
"path_is_unc",
":",
"raise",
"ValueError",
"(",
"\"path is on UNC root %s, start on UNC root %s\"",
"%",
"(",
"path_prefix",
",",
"start_prefix",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"path is on drive %s, start on drive %s\"",
"%",
"(",
"path_prefix",
",",
"start_prefix",
")",
")",
"# Work out how much of the filepath is shared by start and path.",
"i",
"=",
"0",
"for",
"e1",
",",
"e2",
"in",
"zip",
"(",
"start_list",
",",
"path_list",
")",
":",
"if",
"e1",
".",
"lower",
"(",
")",
"!=",
"e2",
".",
"lower",
"(",
")",
":",
"break",
"i",
"+=",
"1",
"rel_list",
"=",
"[",
"pardir",
"]",
"*",
"(",
"len",
"(",
"start_list",
")",
"-",
"i",
")",
"+",
"path_list",
"[",
"i",
":",
"]",
"if",
"not",
"rel_list",
":",
"return",
"curdir",
"return",
"join",
"(",
"*",
"rel_list",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/ntpath.py#L511-L540 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/transaction.py | python | Transaction.to_str | (self) | return pprint.pformat(self.to_dict()) | Returns the string representation of the model | Returns the string representation of the model | [
"Returns",
"the",
"string",
"representation",
"of",
"the",
"model"
] | def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict()) | [
"def",
"to_str",
"(",
"self",
")",
":",
"return",
"pprint",
".",
"pformat",
"(",
"self",
".",
"to_dict",
"(",
")",
")"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/transaction.py#L385-L387 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/urlparse.py | python | urlunsplit | (data) | return url | Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example, a ? with an
empty query; the RFC states that these are equivalent). | Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example, a ? with an
empty query; the RFC states that these are equivalent). | [
"Combine",
"the",
"elements",
"of",
"a",
"tuple",
"as",
"returned",
"by",
"urlsplit",
"()",
"into",
"a",
"complete",
"URL",
"as",
"a",
"string",
".",
"The",
"data",
"argument",
"can",
"be",
"any",
"five",
"-",
"item",
"iterable",
".",
"This",
"may",
"result",
"in",
"a",
"slightly",
"different",
"but",
"equivalent",
"URL",
"if",
"the",
"URL",
"that",
"was",
"parsed",
"originally",
"had",
"unnecessary",
"delimiters",
"(",
"for",
"example",
"a",
"?",
"with",
"an",
"empty",
"query",
";",
"the",
"RFC",
"states",
"that",
"these",
"are",
"equivalent",
")",
"."
] | def urlunsplit(data):
"""Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example, a ? with an
empty query; the RFC states that these are equivalent)."""
scheme, netloc, url, query, fragment = data
if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
if url and url[:1] != '/': url = '/' + url
url = '//' + (netloc or '') + url
if scheme:
url = scheme + ':' + url
if query:
url = url + '?' + query
if fragment:
url = url + '#' + fragment
return url | [
"def",
"urlunsplit",
"(",
"data",
")",
":",
"scheme",
",",
"netloc",
",",
"url",
",",
"query",
",",
"fragment",
"=",
"data",
"if",
"netloc",
"or",
"(",
"scheme",
"and",
"scheme",
"in",
"uses_netloc",
"and",
"url",
"[",
":",
"2",
"]",
"!=",
"'//'",
")",
":",
"if",
"url",
"and",
"url",
"[",
":",
"1",
"]",
"!=",
"'/'",
":",
"url",
"=",
"'/'",
"+",
"url",
"url",
"=",
"'//'",
"+",
"(",
"netloc",
"or",
"''",
")",
"+",
"url",
"if",
"scheme",
":",
"url",
"=",
"scheme",
"+",
"':'",
"+",
"url",
"if",
"query",
":",
"url",
"=",
"url",
"+",
"'?'",
"+",
"query",
"if",
"fragment",
":",
"url",
"=",
"url",
"+",
"'#'",
"+",
"fragment",
"return",
"url"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/urlparse.py#L232-L248 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py | python | TarInfo.create_ustar_header | (self, info, encoding, errors) | return self._create_header(info, USTAR_FORMAT, encoding, errors) | Return the object as a ustar header block. | Return the object as a ustar header block. | [
"Return",
"the",
"object",
"as",
"a",
"ustar",
"header",
"block",
"."
] | def create_ustar_header(self, info, encoding, errors):
"""Return the object as a ustar header block.
"""
info["magic"] = POSIX_MAGIC
if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
raise ValueError("linkname is too long")
if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
info["prefix"], info["name"] = self._posix_split_name(info["name"], encoding, errors)
return self._create_header(info, USTAR_FORMAT, encoding, errors) | [
"def",
"create_ustar_header",
"(",
"self",
",",
"info",
",",
"encoding",
",",
"errors",
")",
":",
"info",
"[",
"\"magic\"",
"]",
"=",
"POSIX_MAGIC",
"if",
"len",
"(",
"info",
"[",
"\"linkname\"",
"]",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
")",
">",
"LENGTH_LINK",
":",
"raise",
"ValueError",
"(",
"\"linkname is too long\"",
")",
"if",
"len",
"(",
"info",
"[",
"\"name\"",
"]",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
")",
">",
"LENGTH_NAME",
":",
"info",
"[",
"\"prefix\"",
"]",
",",
"info",
"[",
"\"name\"",
"]",
"=",
"self",
".",
"_posix_split_name",
"(",
"info",
"[",
"\"name\"",
"]",
",",
"encoding",
",",
"errors",
")",
"return",
"self",
".",
"_create_header",
"(",
"info",
",",
"USTAR_FORMAT",
",",
"encoding",
",",
"errors",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py#L822-L833 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBWatchpoint_GetWatchpointEventTypeFromEvent | (event) | return _lldb.SBWatchpoint_GetWatchpointEventTypeFromEvent(event) | SBWatchpoint_GetWatchpointEventTypeFromEvent(SBEvent event) -> lldb::WatchpointEventType | SBWatchpoint_GetWatchpointEventTypeFromEvent(SBEvent event) -> lldb::WatchpointEventType | [
"SBWatchpoint_GetWatchpointEventTypeFromEvent",
"(",
"SBEvent",
"event",
")",
"-",
">",
"lldb",
"::",
"WatchpointEventType"
] | def SBWatchpoint_GetWatchpointEventTypeFromEvent(event):
"""SBWatchpoint_GetWatchpointEventTypeFromEvent(SBEvent event) -> lldb::WatchpointEventType"""
return _lldb.SBWatchpoint_GetWatchpointEventTypeFromEvent(event) | [
"def",
"SBWatchpoint_GetWatchpointEventTypeFromEvent",
"(",
"event",
")",
":",
"return",
"_lldb",
".",
"SBWatchpoint_GetWatchpointEventTypeFromEvent",
"(",
"event",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L15280-L15282 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py | python | Manager.getLogger | (self, name) | return rv | Get a logger with the specified name (channel name), creating it
if it doesn't yet exist. This name is a dot-separated hierarchical
name, such as "a", "a.b", "a.b.c" or similar.
If a PlaceHolder existed for the specified name [i.e. the logger
didn't exist but a child of it did], replace it with the created
logger and fix up the parent/child references which pointed to the
placeholder to now point to the logger. | Get a logger with the specified name (channel name), creating it
if it doesn't yet exist. This name is a dot-separated hierarchical
name, such as "a", "a.b", "a.b.c" or similar. | [
"Get",
"a",
"logger",
"with",
"the",
"specified",
"name",
"(",
"channel",
"name",
")",
"creating",
"it",
"if",
"it",
"doesn",
"t",
"yet",
"exist",
".",
"This",
"name",
"is",
"a",
"dot",
"-",
"separated",
"hierarchical",
"name",
"such",
"as",
"a",
"a",
".",
"b",
"a",
".",
"b",
".",
"c",
"or",
"similar",
"."
] | def getLogger(self, name):
"""
Get a logger with the specified name (channel name), creating it
if it doesn't yet exist. This name is a dot-separated hierarchical
name, such as "a", "a.b", "a.b.c" or similar.
If a PlaceHolder existed for the specified name [i.e. the logger
didn't exist but a child of it did], replace it with the created
logger and fix up the parent/child references which pointed to the
placeholder to now point to the logger.
"""
rv = None
if not isinstance(name, str):
raise TypeError('A logger name must be a string')
_acquireLock()
try:
if name in self.loggerDict:
rv = self.loggerDict[name]
if isinstance(rv, PlaceHolder):
ph = rv
rv = (self.loggerClass or _loggerClass)(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupChildren(ph, rv)
self._fixupParents(rv)
else:
rv = (self.loggerClass or _loggerClass)(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupParents(rv)
finally:
_releaseLock()
return rv | [
"def",
"getLogger",
"(",
"self",
",",
"name",
")",
":",
"rv",
"=",
"None",
"if",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'A logger name must be a string'",
")",
"_acquireLock",
"(",
")",
"try",
":",
"if",
"name",
"in",
"self",
".",
"loggerDict",
":",
"rv",
"=",
"self",
".",
"loggerDict",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"rv",
",",
"PlaceHolder",
")",
":",
"ph",
"=",
"rv",
"rv",
"=",
"(",
"self",
".",
"loggerClass",
"or",
"_loggerClass",
")",
"(",
"name",
")",
"rv",
".",
"manager",
"=",
"self",
"self",
".",
"loggerDict",
"[",
"name",
"]",
"=",
"rv",
"self",
".",
"_fixupChildren",
"(",
"ph",
",",
"rv",
")",
"self",
".",
"_fixupParents",
"(",
"rv",
")",
"else",
":",
"rv",
"=",
"(",
"self",
".",
"loggerClass",
"or",
"_loggerClass",
")",
"(",
"name",
")",
"rv",
".",
"manager",
"=",
"self",
"self",
".",
"loggerDict",
"[",
"name",
"]",
"=",
"rv",
"self",
".",
"_fixupParents",
"(",
"rv",
")",
"finally",
":",
"_releaseLock",
"(",
")",
"return",
"rv"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py#L1216-L1248 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/build/util/hg.py | python | mercurial | (repo, dest, branch=None, revision=None, update_dest=True,
shareBase=DefaultShareBase, allowUnsharedLocalClones=False,
clone_by_rev=False, mirrors=None, bundles=None, autoPurge=False) | return clone(repo, dest, branch, revision,
update_dest=update_dest, mirrors=mirrors,
bundles=bundles, clone_by_rev=clone_by_rev) | Makes sure that `dest` is has `revision` or `branch` checked out from
`repo`.
Do what it takes to make that happen, including possibly clobbering
dest.
If allowUnsharedLocalClones is True and we're trying to use the share
extension but fail, then we will be able to clone from the shared repo to
our destination. If this is False, the default, then if we don't have the
share extension we will just clone from the remote repository.
If `clone_by_rev` is True, use 'hg clone -r <rev>' instead of 'hg clone'.
This is slower, but useful when cloning repos with lots of heads.
If `mirrors` is set, will try and use the mirrors before `repo`.
If `bundles` is set, will try and download the bundle first and
unbundle it instead of doing a full clone. If successful, will pull in
new revisions from mirrors or the master repo. If unbundling fails, will
fall back to doing a regular clone from mirrors or the master repo. | Makes sure that `dest` is has `revision` or `branch` checked out from
`repo`. | [
"Makes",
"sure",
"that",
"dest",
"is",
"has",
"revision",
"or",
"branch",
"checked",
"out",
"from",
"repo",
"."
] | def mercurial(repo, dest, branch=None, revision=None, update_dest=True,
shareBase=DefaultShareBase, allowUnsharedLocalClones=False,
clone_by_rev=False, mirrors=None, bundles=None, autoPurge=False):
"""Makes sure that `dest` is has `revision` or `branch` checked out from
`repo`.
Do what it takes to make that happen, including possibly clobbering
dest.
If allowUnsharedLocalClones is True and we're trying to use the share
extension but fail, then we will be able to clone from the shared repo to
our destination. If this is False, the default, then if we don't have the
share extension we will just clone from the remote repository.
If `clone_by_rev` is True, use 'hg clone -r <rev>' instead of 'hg clone'.
This is slower, but useful when cloning repos with lots of heads.
If `mirrors` is set, will try and use the mirrors before `repo`.
If `bundles` is set, will try and download the bundle first and
unbundle it instead of doing a full clone. If successful, will pull in
new revisions from mirrors or the master repo. If unbundling fails, will
fall back to doing a regular clone from mirrors or the master repo.
"""
dest = os.path.abspath(dest)
if shareBase is DefaultShareBase:
shareBase = os.environ.get("HG_SHARE_BASE_DIR", None)
log.info("Reporting hg version in use")
cmd = ['hg', '-q', 'version']
run_cmd(cmd, cwd='.')
if shareBase:
# Check that 'hg share' works
try:
log.info("Checking if share extension works")
output = get_output(['hg', 'help', 'share'], dont_log=True)
if 'no commands defined' in output:
# Share extension is enabled, but not functional
log.info("Disabling sharing since share extension doesn't seem to work (1)")
shareBase = None
elif 'unknown command' in output:
# Share extension is disabled
log.info("Disabling sharing since share extension doesn't seem to work (2)")
shareBase = None
except subprocess.CalledProcessError:
# The command failed, so disable sharing
log.info("Disabling sharing since share extension doesn't seem to work (3)")
shareBase = None
# Check that our default path is correct
if os.path.exists(os.path.join(dest, '.hg')):
hgpath = path(dest, "default")
# Make sure that our default path is correct
if hgpath != _make_absolute(repo):
log.info("hg path isn't correct (%s should be %s); clobbering",
hgpath, _make_absolute(repo))
remove_path(dest)
# If the working directory already exists and isn't using share we update
# the working directory directly from the repo, ignoring the sharing
# settings
if os.path.exists(dest):
if not os.path.exists(os.path.join(dest, ".hg")):
log.warning("%s doesn't appear to be a valid hg directory; clobbering", dest)
remove_path(dest)
elif not os.path.exists(os.path.join(dest, ".hg", "sharedpath")):
try:
if autoPurge:
purge(dest)
return pull(repo, dest, update_dest=update_dest, branch=branch,
revision=revision,
mirrors=mirrors)
except subprocess.CalledProcessError:
log.warning("Error pulling changes into %s from %s; clobbering", dest, repo)
log.debug("Exception:", exc_info=True)
remove_path(dest)
# If that fails for any reason, and sharing is requested, we'll try to
# update the shared repository, and then update the working directory from
# that.
if shareBase:
sharedRepo = os.path.join(shareBase, get_repo_path(repo))
dest_sharedPath = os.path.join(dest, '.hg', 'sharedpath')
if os.path.exists(sharedRepo):
hgpath = path(sharedRepo, "default")
# Make sure that our default path is correct
if hgpath != _make_absolute(repo):
log.info("hg path isn't correct (%s should be %s); clobbering",
hgpath, _make_absolute(repo))
# we need to clobber both the shared checkout and the dest,
# since hgrc needs to be in both places
remove_path(sharedRepo)
remove_path(dest)
if os.path.exists(dest_sharedPath):
# Make sure that the sharedpath points to sharedRepo
dest_sharedPath_data = os.path.normpath(
open(dest_sharedPath).read())
norm_sharedRepo = os.path.normpath(os.path.join(sharedRepo, '.hg'))
if dest_sharedPath_data != norm_sharedRepo:
# Clobber!
log.info("We're currently shared from %s, but are being requested to pull from %s (%s); clobbering",
dest_sharedPath_data, repo, norm_sharedRepo)
remove_path(dest)
try:
log.info("Updating shared repo")
mercurial(repo, sharedRepo, branch=branch, revision=revision,
update_dest=False, shareBase=None, clone_by_rev=clone_by_rev,
mirrors=mirrors, bundles=bundles, autoPurge=False)
if os.path.exists(dest):
if autoPurge:
purge(dest)
return update(dest, branch=branch, revision=revision)
try:
log.info("Trying to share %s to %s", sharedRepo, dest)
return share(sharedRepo, dest, branch=branch, revision=revision)
except subprocess.CalledProcessError:
if not allowUnsharedLocalClones:
# Re-raise the exception so it gets caught below.
# We'll then clobber dest, and clone from original repo
raise
log.warning("Error calling hg share from %s to %s;"
"falling back to normal clone from shared repo",
sharedRepo, dest)
# Do a full local clone first, and then update to the
# revision we want
# This lets us use hardlinks for the local clone if the OS
# supports it
clone(sharedRepo, dest, update_dest=False,
mirrors=mirrors, bundles=bundles)
return update(dest, branch=branch, revision=revision)
except subprocess.CalledProcessError:
log.warning(
"Error updating %s from sharedRepo (%s): ", dest, sharedRepo)
log.debug("Exception:", exc_info=True)
remove_path(dest)
# end if shareBase
if not os.path.exists(os.path.dirname(dest)):
os.makedirs(os.path.dirname(dest))
# Share isn't available or has failed, clone directly from the source
return clone(repo, dest, branch, revision,
update_dest=update_dest, mirrors=mirrors,
bundles=bundles, clone_by_rev=clone_by_rev) | [
"def",
"mercurial",
"(",
"repo",
",",
"dest",
",",
"branch",
"=",
"None",
",",
"revision",
"=",
"None",
",",
"update_dest",
"=",
"True",
",",
"shareBase",
"=",
"DefaultShareBase",
",",
"allowUnsharedLocalClones",
"=",
"False",
",",
"clone_by_rev",
"=",
"False",
",",
"mirrors",
"=",
"None",
",",
"bundles",
"=",
"None",
",",
"autoPurge",
"=",
"False",
")",
":",
"dest",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dest",
")",
"if",
"shareBase",
"is",
"DefaultShareBase",
":",
"shareBase",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"HG_SHARE_BASE_DIR\"",
",",
"None",
")",
"log",
".",
"info",
"(",
"\"Reporting hg version in use\"",
")",
"cmd",
"=",
"[",
"'hg'",
",",
"'-q'",
",",
"'version'",
"]",
"run_cmd",
"(",
"cmd",
",",
"cwd",
"=",
"'.'",
")",
"if",
"shareBase",
":",
"# Check that 'hg share' works",
"try",
":",
"log",
".",
"info",
"(",
"\"Checking if share extension works\"",
")",
"output",
"=",
"get_output",
"(",
"[",
"'hg'",
",",
"'help'",
",",
"'share'",
"]",
",",
"dont_log",
"=",
"True",
")",
"if",
"'no commands defined'",
"in",
"output",
":",
"# Share extension is enabled, but not functional",
"log",
".",
"info",
"(",
"\"Disabling sharing since share extension doesn't seem to work (1)\"",
")",
"shareBase",
"=",
"None",
"elif",
"'unknown command'",
"in",
"output",
":",
"# Share extension is disabled",
"log",
".",
"info",
"(",
"\"Disabling sharing since share extension doesn't seem to work (2)\"",
")",
"shareBase",
"=",
"None",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"# The command failed, so disable sharing",
"log",
".",
"info",
"(",
"\"Disabling sharing since share extension doesn't seem to work (3)\"",
")",
"shareBase",
"=",
"None",
"# Check that our default path is correct",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dest",
",",
"'.hg'",
")",
")",
":",
"hgpath",
"=",
"path",
"(",
"dest",
",",
"\"default\"",
")",
"# Make sure that our default path is correct",
"if",
"hgpath",
"!=",
"_make_absolute",
"(",
"repo",
")",
":",
"log",
".",
"info",
"(",
"\"hg path isn't correct (%s should be %s); clobbering\"",
",",
"hgpath",
",",
"_make_absolute",
"(",
"repo",
")",
")",
"remove_path",
"(",
"dest",
")",
"# If the working directory already exists and isn't using share we update",
"# the working directory directly from the repo, ignoring the sharing",
"# settings",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dest",
",",
"\".hg\"",
")",
")",
":",
"log",
".",
"warning",
"(",
"\"%s doesn't appear to be a valid hg directory; clobbering\"",
",",
"dest",
")",
"remove_path",
"(",
"dest",
")",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dest",
",",
"\".hg\"",
",",
"\"sharedpath\"",
")",
")",
":",
"try",
":",
"if",
"autoPurge",
":",
"purge",
"(",
"dest",
")",
"return",
"pull",
"(",
"repo",
",",
"dest",
",",
"update_dest",
"=",
"update_dest",
",",
"branch",
"=",
"branch",
",",
"revision",
"=",
"revision",
",",
"mirrors",
"=",
"mirrors",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"log",
".",
"warning",
"(",
"\"Error pulling changes into %s from %s; clobbering\"",
",",
"dest",
",",
"repo",
")",
"log",
".",
"debug",
"(",
"\"Exception:\"",
",",
"exc_info",
"=",
"True",
")",
"remove_path",
"(",
"dest",
")",
"# If that fails for any reason, and sharing is requested, we'll try to",
"# update the shared repository, and then update the working directory from",
"# that.",
"if",
"shareBase",
":",
"sharedRepo",
"=",
"os",
".",
"path",
".",
"join",
"(",
"shareBase",
",",
"get_repo_path",
"(",
"repo",
")",
")",
"dest_sharedPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest",
",",
"'.hg'",
",",
"'sharedpath'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"sharedRepo",
")",
":",
"hgpath",
"=",
"path",
"(",
"sharedRepo",
",",
"\"default\"",
")",
"# Make sure that our default path is correct",
"if",
"hgpath",
"!=",
"_make_absolute",
"(",
"repo",
")",
":",
"log",
".",
"info",
"(",
"\"hg path isn't correct (%s should be %s); clobbering\"",
",",
"hgpath",
",",
"_make_absolute",
"(",
"repo",
")",
")",
"# we need to clobber both the shared checkout and the dest,",
"# since hgrc needs to be in both places",
"remove_path",
"(",
"sharedRepo",
")",
"remove_path",
"(",
"dest",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest_sharedPath",
")",
":",
"# Make sure that the sharedpath points to sharedRepo",
"dest_sharedPath_data",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"open",
"(",
"dest_sharedPath",
")",
".",
"read",
"(",
")",
")",
"norm_sharedRepo",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sharedRepo",
",",
"'.hg'",
")",
")",
"if",
"dest_sharedPath_data",
"!=",
"norm_sharedRepo",
":",
"# Clobber!",
"log",
".",
"info",
"(",
"\"We're currently shared from %s, but are being requested to pull from %s (%s); clobbering\"",
",",
"dest_sharedPath_data",
",",
"repo",
",",
"norm_sharedRepo",
")",
"remove_path",
"(",
"dest",
")",
"try",
":",
"log",
".",
"info",
"(",
"\"Updating shared repo\"",
")",
"mercurial",
"(",
"repo",
",",
"sharedRepo",
",",
"branch",
"=",
"branch",
",",
"revision",
"=",
"revision",
",",
"update_dest",
"=",
"False",
",",
"shareBase",
"=",
"None",
",",
"clone_by_rev",
"=",
"clone_by_rev",
",",
"mirrors",
"=",
"mirrors",
",",
"bundles",
"=",
"bundles",
",",
"autoPurge",
"=",
"False",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
":",
"if",
"autoPurge",
":",
"purge",
"(",
"dest",
")",
"return",
"update",
"(",
"dest",
",",
"branch",
"=",
"branch",
",",
"revision",
"=",
"revision",
")",
"try",
":",
"log",
".",
"info",
"(",
"\"Trying to share %s to %s\"",
",",
"sharedRepo",
",",
"dest",
")",
"return",
"share",
"(",
"sharedRepo",
",",
"dest",
",",
"branch",
"=",
"branch",
",",
"revision",
"=",
"revision",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"if",
"not",
"allowUnsharedLocalClones",
":",
"# Re-raise the exception so it gets caught below.",
"# We'll then clobber dest, and clone from original repo",
"raise",
"log",
".",
"warning",
"(",
"\"Error calling hg share from %s to %s;\"",
"\"falling back to normal clone from shared repo\"",
",",
"sharedRepo",
",",
"dest",
")",
"# Do a full local clone first, and then update to the",
"# revision we want",
"# This lets us use hardlinks for the local clone if the OS",
"# supports it",
"clone",
"(",
"sharedRepo",
",",
"dest",
",",
"update_dest",
"=",
"False",
",",
"mirrors",
"=",
"mirrors",
",",
"bundles",
"=",
"bundles",
")",
"return",
"update",
"(",
"dest",
",",
"branch",
"=",
"branch",
",",
"revision",
"=",
"revision",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"log",
".",
"warning",
"(",
"\"Error updating %s from sharedRepo (%s): \"",
",",
"dest",
",",
"sharedRepo",
")",
"log",
".",
"debug",
"(",
"\"Exception:\"",
",",
"exc_info",
"=",
"True",
")",
"remove_path",
"(",
"dest",
")",
"# end if shareBase",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"dest",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"dest",
")",
")",
"# Share isn't available or has failed, clone directly from the source",
"return",
"clone",
"(",
"repo",
",",
"dest",
",",
"branch",
",",
"revision",
",",
"update_dest",
"=",
"update_dest",
",",
"mirrors",
"=",
"mirrors",
",",
"bundles",
"=",
"bundles",
",",
"clone_by_rev",
"=",
"clone_by_rev",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/util/hg.py#L328-L479 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/tools/docs/generate_lib.py | python | _GenerateGuideIndex.process | (self, full_path, base_name) | Index a file, reading from `full_path`, with `base_name` as the link. | Index a file, reading from `full_path`, with `base_name` as the link. | [
"Index",
"a",
"file",
"reading",
"from",
"full_path",
"with",
"base_name",
"as",
"the",
"link",
"."
] | def process(self, full_path, base_name):
"""Index a file, reading from `full_path`, with `base_name` as the link."""
self.full_path = full_path
self.base_name = base_name
self.title = None
self.section_title = None
self.section_tag = None
py_guide_parser.PyGuideParser.process(self, full_path) | [
"def",
"process",
"(",
"self",
",",
"full_path",
",",
"base_name",
")",
":",
"self",
".",
"full_path",
"=",
"full_path",
"self",
".",
"base_name",
"=",
"base_name",
"self",
".",
"title",
"=",
"None",
"self",
".",
"section_title",
"=",
"None",
"self",
".",
"section_tag",
"=",
"None",
"py_guide_parser",
".",
"PyGuideParser",
".",
"process",
"(",
"self",
",",
"full_path",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/tools/docs/generate_lib.py#L323-L330 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py | python | get_recordings_by_echoprint | (echoprint, includes=[], release_status=[],
release_type=[]) | Search for recordings with an `echoprint <http://echoprint.me>`_.
(not available on server) | Search for recordings with an `echoprint <http://echoprint.me>`_.
(not available on server) | [
"Search",
"for",
"recordings",
"with",
"an",
"echoprint",
"<http",
":",
"//",
"echoprint",
".",
"me",
">",
"_",
".",
"(",
"not",
"available",
"on",
"server",
")"
] | def get_recordings_by_echoprint(echoprint, includes=[], release_status=[],
release_type=[]):
"""Search for recordings with an `echoprint <http://echoprint.me>`_.
(not available on server)"""
warn("Echoprints were never introduced\n"
"and will not be found (404)",
Warning, stacklevel=2)
raise ResponseError(cause=compat.HTTPError(
None, 404, "Not Found", None, None)) | [
"def",
"get_recordings_by_echoprint",
"(",
"echoprint",
",",
"includes",
"=",
"[",
"]",
",",
"release_status",
"=",
"[",
"]",
",",
"release_type",
"=",
"[",
"]",
")",
":",
"warn",
"(",
"\"Echoprints were never introduced\\n\"",
"\"and will not be found (404)\"",
",",
"Warning",
",",
"stacklevel",
"=",
"2",
")",
"raise",
"ResponseError",
"(",
"cause",
"=",
"compat",
".",
"HTTPError",
"(",
"None",
",",
"404",
",",
"\"Not Found\"",
",",
"None",
",",
"None",
")",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py#L1014-L1022 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | uCSIsCatMe | (code) | return ret | Check whether the character is part of Me UCS Category | Check whether the character is part of Me UCS Category | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Me",
"UCS",
"Category"
] | def uCSIsCatMe(code):
"""Check whether the character is part of Me UCS Category """
ret = libxml2mod.xmlUCSIsCatMe(code)
return ret | [
"def",
"uCSIsCatMe",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCatMe",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L2261-L2264 | |
genn-team/genn | 75e1eb218cafa228bf36ae4613d1ce26e877b12c | pygenn/genn_groups.py | python | NeuronGroup.pull_current_spike_events_from_device | (self) | Wrapper around GeNNModel.pull_current_spike_events_from_device | Wrapper around GeNNModel.pull_current_spike_events_from_device | [
"Wrapper",
"around",
"GeNNModel",
".",
"pull_current_spike_events_from_device"
] | def pull_current_spike_events_from_device(self):
"""Wrapper around GeNNModel.pull_current_spike_events_from_device"""
self._model.pull_current_spike_events_from_device(self.name) | [
"def",
"pull_current_spike_events_from_device",
"(",
"self",
")",
":",
"self",
".",
"_model",
".",
"pull_current_spike_events_from_device",
"(",
"self",
".",
"name",
")"
] | https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_groups.py#L445-L447 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | Geometry3D.distance_point_ext | (self, pt: "double const [3]", settings: "DistanceQuerySettings") | return _robotsim.Geometry3D_distance_point_ext(self, pt, settings) | r"""
distance_point_ext(Geometry3D self, double const [3] pt, DistanceQuerySettings settings) -> DistanceQueryResult
A customizable version of :meth:`Geometry3D.distance_point`. The settings for
the calculation can be customized with relErr, absErr, and upperBound, e.g., to
break if the closest points are at least upperBound distance from one another. | r"""
distance_point_ext(Geometry3D self, double const [3] pt, DistanceQuerySettings settings) -> DistanceQueryResult | [
"r",
"distance_point_ext",
"(",
"Geometry3D",
"self",
"double",
"const",
"[",
"3",
"]",
"pt",
"DistanceQuerySettings",
"settings",
")",
"-",
">",
"DistanceQueryResult"
] | def distance_point_ext(self, pt: "double const [3]", settings: "DistanceQuerySettings") -> "DistanceQueryResult":
r"""
distance_point_ext(Geometry3D self, double const [3] pt, DistanceQuerySettings settings) -> DistanceQueryResult
A customizable version of :meth:`Geometry3D.distance_point`. The settings for
the calculation can be customized with relErr, absErr, and upperBound, e.g., to
break if the closest points are at least upperBound distance from one another.
"""
return _robotsim.Geometry3D_distance_point_ext(self, pt, settings) | [
"def",
"distance_point_ext",
"(",
"self",
",",
"pt",
":",
"\"double const [3]\"",
",",
"settings",
":",
"\"DistanceQuerySettings\"",
")",
"->",
"\"DistanceQueryResult\"",
":",
"return",
"_robotsim",
".",
"Geometry3D_distance_point_ext",
"(",
"self",
",",
"pt",
",",
"settings",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L2520-L2530 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Pygments/py2/pygments/lexers/sql.py | python | language_callback | (lexer, match) | Parse the content of a $-string using a lexer
The lexer is chosen looking for a nearby LANGUAGE or assumed as
plpgsql if inside a DO statement and no LANGUAGE has been found. | Parse the content of a $-string using a lexer | [
"Parse",
"the",
"content",
"of",
"a",
"$",
"-",
"string",
"using",
"a",
"lexer"
] | def language_callback(lexer, match):
"""Parse the content of a $-string using a lexer
The lexer is chosen looking for a nearby LANGUAGE or assumed as
plpgsql if inside a DO statement and no LANGUAGE has been found.
"""
lx = None
m = language_re.match(lexer.text[match.end():match.end()+100])
if m is not None:
lx = lexer._get_lexer(m.group(1))
else:
m = list(language_re.finditer(
lexer.text[max(0, match.start()-100):match.start()]))
if m:
lx = lexer._get_lexer(m[-1].group(1))
else:
m = list(do_re.finditer(
lexer.text[max(0, match.start()-25):match.start()]))
if m:
lx = lexer._get_lexer('plpgsql')
# 1 = $, 2 = delimiter, 3 = $
yield (match.start(1), String, match.group(1))
yield (match.start(2), String.Delimiter, match.group(2))
yield (match.start(3), String, match.group(3))
# 4 = string contents
if lx:
for x in lx.get_tokens_unprocessed(match.group(4)):
yield x
else:
yield (match.start(4), String, match.group(4))
# 5 = $, 6 = delimiter, 7 = $
yield (match.start(5), String, match.group(5))
yield (match.start(6), String.Delimiter, match.group(6))
yield (match.start(7), String, match.group(7)) | [
"def",
"language_callback",
"(",
"lexer",
",",
"match",
")",
":",
"lx",
"=",
"None",
"m",
"=",
"language_re",
".",
"match",
"(",
"lexer",
".",
"text",
"[",
"match",
".",
"end",
"(",
")",
":",
"match",
".",
"end",
"(",
")",
"+",
"100",
"]",
")",
"if",
"m",
"is",
"not",
"None",
":",
"lx",
"=",
"lexer",
".",
"_get_lexer",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"m",
"=",
"list",
"(",
"language_re",
".",
"finditer",
"(",
"lexer",
".",
"text",
"[",
"max",
"(",
"0",
",",
"match",
".",
"start",
"(",
")",
"-",
"100",
")",
":",
"match",
".",
"start",
"(",
")",
"]",
")",
")",
"if",
"m",
":",
"lx",
"=",
"lexer",
".",
"_get_lexer",
"(",
"m",
"[",
"-",
"1",
"]",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"m",
"=",
"list",
"(",
"do_re",
".",
"finditer",
"(",
"lexer",
".",
"text",
"[",
"max",
"(",
"0",
",",
"match",
".",
"start",
"(",
")",
"-",
"25",
")",
":",
"match",
".",
"start",
"(",
")",
"]",
")",
")",
"if",
"m",
":",
"lx",
"=",
"lexer",
".",
"_get_lexer",
"(",
"'plpgsql'",
")",
"# 1 = $, 2 = delimiter, 3 = $",
"yield",
"(",
"match",
".",
"start",
"(",
"1",
")",
",",
"String",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
"yield",
"(",
"match",
".",
"start",
"(",
"2",
")",
",",
"String",
".",
"Delimiter",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
"yield",
"(",
"match",
".",
"start",
"(",
"3",
")",
",",
"String",
",",
"match",
".",
"group",
"(",
"3",
")",
")",
"# 4 = string contents",
"if",
"lx",
":",
"for",
"x",
"in",
"lx",
".",
"get_tokens_unprocessed",
"(",
"match",
".",
"group",
"(",
"4",
")",
")",
":",
"yield",
"x",
"else",
":",
"yield",
"(",
"match",
".",
"start",
"(",
"4",
")",
",",
"String",
",",
"match",
".",
"group",
"(",
"4",
")",
")",
"# 5 = $, 6 = delimiter, 7 = $",
"yield",
"(",
"match",
".",
"start",
"(",
"5",
")",
",",
"String",
",",
"match",
".",
"group",
"(",
"5",
")",
")",
"yield",
"(",
"match",
".",
"start",
"(",
"6",
")",
",",
"String",
".",
"Delimiter",
",",
"match",
".",
"group",
"(",
"6",
")",
")",
"yield",
"(",
"match",
".",
"start",
"(",
"7",
")",
",",
"String",
",",
"match",
".",
"group",
"(",
"7",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py2/pygments/lexers/sql.py#L72-L106 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | CheckVlogArguments | (filename, clean_lines, linenum, error) | Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks that VLOG() is only used for defining a logging level. | [
"Checks",
"that",
"VLOG",
"()",
"is",
"only",
"used",
"for",
"defining",
"a",
"logging",
"level",
"."
] | def CheckVlogArguments(filename, clean_lines, linenum, error):
"""Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
error(filename, linenum, 'runtime/vlog', 5,
'VLOG() should be used with numeric verbosity level. '
'Use LOG() if you want symbolic severity levels.') | [
"def",
"CheckVlogArguments",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\bVLOG\\((INFO|ERROR|WARNING|DFATAL|FATAL)\\)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/vlog'",
",",
"5",
",",
"'VLOG() should be used with numeric verbosity level. '",
"'Use LOG() if you want symbolic severity levels.'",
")"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L2145-L2161 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.