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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/fileinput.py | python | close | () | Close the sequence. | Close the sequence. | [
"Close",
"the",
"sequence",
"."
] | def close():
"""Close the sequence."""
global _state
state = _state
_state = None
if state:
state.close() | [
"def",
"close",
"(",
")",
":",
"global",
"_state",
"state",
"=",
"_state",
"_state",
"=",
"None",
"if",
"state",
":",
"state",
".",
"close",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/fileinput.py#L106-L112 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | benchmark/opperf/utils/op_registry_utils.py | python | get_all_expanding_operators | () | return expanding_mx_operators | Gets all array expanding operators registered with MXNet.
Returns
-------
{"operator_name": {"has_backward", "nd_op_handle", "params"}} | Gets all array expanding operators registered with MXNet. | [
"Gets",
"all",
"array",
"expanding",
"operators",
"registered",
"with",
"MXNet",
"."
] | def get_all_expanding_operators():
"""Gets all array expanding operators registered with MXNet.
Returns
-------
{"operator_name": {"has_backward", "nd_op_handle", "params"}}
"""
expanding_ops = ['broadcast_axes', 'broadcast_axis', 'broadcast_to', 'broadcast_like',
'repeat', 'tile', 'pad', 'expand_dims']
# Get all mxnet operators
mx_operators = _get_all_mxnet_operators()
# Filter for Array Expanding operators
expanding_mx_operators = {}
for op_name, op_params in mx_operators.items():
if op_name in expanding_ops:
expanding_mx_operators[op_name] = mx_operators[op_name]
return expanding_mx_operators | [
"def",
"get_all_expanding_operators",
"(",
")",
":",
"expanding_ops",
"=",
"[",
"'broadcast_axes'",
",",
"'broadcast_axis'",
",",
"'broadcast_to'",
",",
"'broadcast_like'",
",",
"'repeat'",
",",
"'tile'",
",",
"'pad'",
",",
"'expand_dims'",
"]",
"# Get all mxnet opera... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/benchmark/opperf/utils/op_registry_utils.py#L553-L571 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/p4util/python_helpers.py | python | basname | (name) | return name.lower().replace('+', 'p').replace('*', 's').replace('(', '_').replace(')', '_').replace(',', '_') | Imitates BasisSet.make_filename() without the gbs extension | Imitates BasisSet.make_filename() without the gbs extension | [
"Imitates",
"BasisSet",
".",
"make_filename",
"()",
"without",
"the",
"gbs",
"extension"
] | def basname(name):
"""Imitates BasisSet.make_filename() without the gbs extension"""
return name.lower().replace('+', 'p').replace('*', 's').replace('(', '_').replace(')', '_').replace(',', '_') | [
"def",
"basname",
"(",
"name",
")",
":",
"return",
"name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'+'",
",",
"'p'",
")",
".",
"replace",
"(",
"'*'",
",",
"'s'",
")",
".",
"replace",
"(",
"'('",
",",
"'_'",
")",
".",
"replace",
"(",
"')'"... | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/p4util/python_helpers.py#L513-L515 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/factorization/python/ops/factorization_ops.py | python | WALSModel._prepare_gramian | (self, factors, gramian) | return prep_gramian | Helper function to create ops to prepare/calculate gramian.
Args:
factors: Variable or list of Variable representing (sharded) factors.
Used to compute the updated corresponding gramian value.
gramian: Variable storing the gramian calculated from the factors.
Returns:
A op that updates the gramian with the calcuated value from the factors. | Helper function to create ops to prepare/calculate gramian. | [
"Helper",
"function",
"to",
"create",
"ops",
"to",
"prepare",
"/",
"calculate",
"gramian",
"."
] | def _prepare_gramian(self, factors, gramian):
"""Helper function to create ops to prepare/calculate gramian.
Args:
factors: Variable or list of Variable representing (sharded) factors.
Used to compute the updated corresponding gramian value.
gramian: Variable storing the gramian calculated from the factors.
Returns:
A op that updates the gramian with the calcuated value from the factors.
"""
partial_gramians = []
for f in factors:
with ops.colocate_with(f):
partial_gramians.append(math_ops.matmul(f, f, transpose_a=True))
with ops.colocate_with(gramian):
prep_gramian = state_ops.assign(gramian,
math_ops.add_n(partial_gramians)).op
return prep_gramian | [
"def",
"_prepare_gramian",
"(",
"self",
",",
"factors",
",",
"gramian",
")",
":",
"partial_gramians",
"=",
"[",
"]",
"for",
"f",
"in",
"factors",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"f",
")",
":",
"partial_gramians",
".",
"append",
"(",
"math_... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L429-L449 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_diag.py | python | OperatorPDDiag.__init__ | (self, diag, verify_pd=True, name='OperatorPDDiag') | Initialize an OperatorPDDiag.
Args:
diag: Shape `[N1,...,Nn, k]` positive tensor with `n >= 0`, `k >= 1`.
verify_pd: Whether to check `diag` is positive.
name: A name to prepend to all ops created by this class. | Initialize an OperatorPDDiag. | [
"Initialize",
"an",
"OperatorPDDiag",
"."
] | def __init__(self, diag, verify_pd=True, name='OperatorPDDiag'):
"""Initialize an OperatorPDDiag.
Args:
diag: Shape `[N1,...,Nn, k]` positive tensor with `n >= 0`, `k >= 1`.
verify_pd: Whether to check `diag` is positive.
name: A name to prepend to all ops created by this class.
"""
super(OperatorPDDiag, self).__init__(
diag, verify_pd=verify_pd, name=name) | [
"def",
"__init__",
"(",
"self",
",",
"diag",
",",
"verify_pd",
"=",
"True",
",",
"name",
"=",
"'OperatorPDDiag'",
")",
":",
"super",
"(",
"OperatorPDDiag",
",",
"self",
")",
".",
"__init__",
"(",
"diag",
",",
"verify_pd",
"=",
"verify_pd",
",",
"name",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_diag.py#L161-L170 | ||
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/simple.py | python | UpdateScalarBars | (view=None) | return tfmgr.UpdateScalarBars(view.SMProxy, tfmgr.HIDE_UNUSED_SCALAR_BARS | tfmgr.SHOW_USED_SCALAR_BARS) | Hides all unused scalar bar and shows used scalar bars. A scalar bar is used
if some data is shown in that view that is coloring using the transfer function
shown by the scalar bar. | Hides all unused scalar bar and shows used scalar bars. A scalar bar is used
if some data is shown in that view that is coloring using the transfer function
shown by the scalar bar. | [
"Hides",
"all",
"unused",
"scalar",
"bar",
"and",
"shows",
"used",
"scalar",
"bars",
".",
"A",
"scalar",
"bar",
"is",
"used",
"if",
"some",
"data",
"is",
"shown",
"in",
"that",
"view",
"that",
"is",
"coloring",
"using",
"the",
"transfer",
"function",
"sh... | def UpdateScalarBars(view=None):
"""Hides all unused scalar bar and shows used scalar bars. A scalar bar is used
if some data is shown in that view that is coloring using the transfer function
shown by the scalar bar."""
if not view:
view = active_objects.view
if not view:
raise ValueError ("'view' argument cannot be None with no active is present.")
tfmgr = servermanager.vtkSMTransferFunctionManager()
return tfmgr.UpdateScalarBars(view.SMProxy, tfmgr.HIDE_UNUSED_SCALAR_BARS | tfmgr.SHOW_USED_SCALAR_BARS) | [
"def",
"UpdateScalarBars",
"(",
"view",
"=",
"None",
")",
":",
"if",
"not",
"view",
":",
"view",
"=",
"active_objects",
".",
"view",
"if",
"not",
"view",
":",
"raise",
"ValueError",
"(",
"\"'view' argument cannot be None with no active is present.\"",
")",
"tfmgr"... | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/simple.py#L1779-L1788 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/layers/python/layers/feature_column.py | python | _RealValuedColumn.normalizer_fn | (self) | return self.normalizer | Returns the function used to normalize the column. | Returns the function used to normalize the column. | [
"Returns",
"the",
"function",
"used",
"to",
"normalize",
"the",
"column",
"."
] | def normalizer_fn(self):
"""Returns the function used to normalize the column."""
return self.normalizer | [
"def",
"normalizer_fn",
"(",
"self",
")",
":",
"return",
"self",
".",
"normalizer"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/layers/python/layers/feature_column.py#L1190-L1192 | |
lmb-freiburg/ogn | 974f72ef4bf840d6f6693d22d1843a79223e77ce | python/caffe/pycaffe.py | python | _Net_get_id_name | (func, field) | return get_id_name | Generic property that maps func to the layer names into an OrderedDict.
Used for top_names and bottom_names.
Parameters
----------
func: function id -> [id]
field: implementation field name (cache)
Returns
------
A one-parameter function that can be set as a property. | Generic property that maps func to the layer names into an OrderedDict. | [
"Generic",
"property",
"that",
"maps",
"func",
"to",
"the",
"layer",
"names",
"into",
"an",
"OrderedDict",
"."
] | def _Net_get_id_name(func, field):
"""
Generic property that maps func to the layer names into an OrderedDict.
Used for top_names and bottom_names.
Parameters
----------
func: function id -> [id]
field: implementation field name (cache)
Returns
------
A one-parameter function that can be set as a property.
"""
@property
def get_id_name(self):
if not hasattr(self, field):
id_to_name = list(self.blobs)
res = OrderedDict([(self._layer_names[i],
[id_to_name[j] for j in func(self, i)])
for i in range(len(self.layers))])
setattr(self, field, res)
return getattr(self, field)
return get_id_name | [
"def",
"_Net_get_id_name",
"(",
"func",
",",
"field",
")",
":",
"@",
"property",
"def",
"get_id_name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"field",
")",
":",
"id_to_name",
"=",
"list",
"(",
"self",
".",
"blobs",
")",
"res... | https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/python/caffe/pycaffe.py#L305-L329 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/ftplib.py | python | FTP.quit | (self) | return resp | Quit, and close the connection. | Quit, and close the connection. | [
"Quit",
"and",
"close",
"the",
"connection",
"."
] | def quit(self):
'''Quit, and close the connection.'''
resp = self.voidcmd('QUIT')
self.close()
return resp | [
"def",
"quit",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"voidcmd",
"(",
"'QUIT'",
")",
"self",
".",
"close",
"(",
")",
"return",
"resp"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/ftplib.py#L663-L667 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/fftpack/realtransforms.py | python | idct | (x, type=2, n=None, axis=-1, norm=None, overwrite_x=False) | return _dct(x, _TP[type], n, axis, normalize=norm, overwrite_x=overwrite_x) | Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
Parameters
----------
x : array_like
The input array.
type : {1, 2, 3, 4}, optional
Type of the DCT (see Notes). Default type is 2.
n : int, optional
Length of the transform. If ``n < x.shape[axis]``, `x` is
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
default results in ``n = x.shape[axis]``.
axis : int, optional
Axis along which the idct is computed; the default is over the
last axis (i.e., ``axis=-1``).
norm : {None, 'ortho'}, optional
Normalization mode (see Notes). Default is None.
overwrite_x : bool, optional
If True, the contents of `x` can be destroyed; the default is False.
Returns
-------
idct : ndarray of real
The transformed input array.
See Also
--------
dct : Forward DCT
Notes
-----
For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
MATLAB ``idct(x)``.
'The' IDCT is the IDCT of type 2, which is the same as DCT of type 3.
IDCT of type 1 is the DCT of type 1, IDCT of type 2 is the DCT of type
3, and IDCT of type 3 is the DCT of type 2. IDCT of type 4 is the DCT
of type 4. For the definition of these types, see `dct`.
Examples
--------
The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
inputs. The output is also real and even-symmetrical. Half of the IFFT
input is used to generate half of the IFFT output:
>>> from scipy.fftpack import ifft, idct
>>> ifft(np.array([ 30., -8., 6., -2., 6., -8.])).real
array([ 4., 3., 5., 10., 5., 3.])
>>> idct(np.array([ 30., -8., 6., -2.]), 1) / 6
array([ 4., 3., 5., 10.]) | Return the Inverse Discrete Cosine Transform of an arbitrary type sequence. | [
"Return",
"the",
"Inverse",
"Discrete",
"Cosine",
"Transform",
"of",
"an",
"arbitrary",
"type",
"sequence",
"."
] | def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
"""
Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
Parameters
----------
x : array_like
The input array.
type : {1, 2, 3, 4}, optional
Type of the DCT (see Notes). Default type is 2.
n : int, optional
Length of the transform. If ``n < x.shape[axis]``, `x` is
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
default results in ``n = x.shape[axis]``.
axis : int, optional
Axis along which the idct is computed; the default is over the
last axis (i.e., ``axis=-1``).
norm : {None, 'ortho'}, optional
Normalization mode (see Notes). Default is None.
overwrite_x : bool, optional
If True, the contents of `x` can be destroyed; the default is False.
Returns
-------
idct : ndarray of real
The transformed input array.
See Also
--------
dct : Forward DCT
Notes
-----
For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
MATLAB ``idct(x)``.
'The' IDCT is the IDCT of type 2, which is the same as DCT of type 3.
IDCT of type 1 is the DCT of type 1, IDCT of type 2 is the DCT of type
3, and IDCT of type 3 is the DCT of type 2. IDCT of type 4 is the DCT
of type 4. For the definition of these types, see `dct`.
Examples
--------
The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
inputs. The output is also real and even-symmetrical. Half of the IFFT
input is used to generate half of the IFFT output:
>>> from scipy.fftpack import ifft, idct
>>> ifft(np.array([ 30., -8., 6., -2., 6., -8.])).real
array([ 4., 3., 5., 10., 5., 3.])
>>> idct(np.array([ 30., -8., 6., -2.]), 1) / 6
array([ 4., 3., 5., 10.])
"""
# Inverse/forward type table
_TP = {1:1, 2:3, 3:2, 4:4}
return _dct(x, _TP[type], n, axis, normalize=norm, overwrite_x=overwrite_x) | [
"def",
"idct",
"(",
"x",
",",
"type",
"=",
"2",
",",
"n",
"=",
"None",
",",
"axis",
"=",
"-",
"1",
",",
"norm",
"=",
"None",
",",
"overwrite_x",
"=",
"False",
")",
":",
"# Inverse/forward type table",
"_TP",
"=",
"{",
"1",
":",
"1",
",",
"2",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/fftpack/realtransforms.py#L395-L452 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/utils/llvm-build/llvmbuild/main.py | python | cmake_quote_string | (value) | return value | cmake_quote_string(value) -> str
Return a quoted form of the given value that is suitable for use in CMake
language files. | cmake_quote_string(value) -> str | [
"cmake_quote_string",
"(",
"value",
")",
"-",
">",
"str"
] | def cmake_quote_string(value):
"""
cmake_quote_string(value) -> str
Return a quoted form of the given value that is suitable for use in CMake
language files.
"""
# Currently, we only handle escaping backslashes.
value = value.replace("\\", "\\\\")
return value | [
"def",
"cmake_quote_string",
"(",
"value",
")",
":",
"# Currently, we only handle escaping backslashes.",
"value",
"=",
"value",
".",
"replace",
"(",
"\"\\\\\"",
",",
"\"\\\\\\\\\"",
")",
"return",
"value"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/llvm-build/llvmbuild/main.py#L12-L23 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | CommandLinkButton.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, String mainLabel=wxEmptyString,
String note=wxEmptyString, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0,
Validator validator=DefaultValidator,
String name=wxButtonNameStr) -> CommandLinkButton | __init__(self, Window parent, int id=-1, String mainLabel=wxEmptyString,
String note=wxEmptyString, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0,
Validator validator=DefaultValidator,
String name=wxButtonNameStr) -> CommandLinkButton | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"String",
"mainLabel",
"=",
"wxEmptyString",
"String",
"note",
"=",
"wxEmptyString",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0... | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String mainLabel=wxEmptyString,
String note=wxEmptyString, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0,
Validator validator=DefaultValidator,
String name=wxButtonNameStr) -> CommandLinkButton
"""
_controls_.CommandLinkButton_swiginit(self,_controls_.new_CommandLinkButton(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_controls_",
".",
"CommandLinkButton_swiginit",
"(",
"self",
",",
"_controls_",
".",
"new_CommandLinkButton",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L7863-L7872 | ||
tinyobjloader/tinyobjloader | 8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93 | deps/cpplint.py | python | NestingState.InExternC | (self) | return self.stack and isinstance(self.stack[-1], _ExternCInfo) | Check if we are currently one level inside an 'extern "C"' block.
Returns:
True if top of the stack is an extern block, False otherwise. | Check if we are currently one level inside an 'extern "C"' block. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"an",
"extern",
"C",
"block",
"."
] | def InExternC(self):
"""Check if we are currently one level inside an 'extern "C"' block.
Returns:
True if top of the stack is an extern block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _ExternCInfo) | [
"def",
"InExternC",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_ExternCInfo",
")"
] | https://github.com/tinyobjloader/tinyobjloader/blob/8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93/deps/cpplint.py#L2242-L2248 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | GraphRewriter.eightbitize_conv_node | (self, original_node) | Replaces a Conv2D node with the eight bit equivalent sub-graph. | Replaces a Conv2D node with the eight bit equivalent sub-graph. | [
"Replaces",
"a",
"Conv2D",
"node",
"with",
"the",
"eight",
"bit",
"equivalent",
"sub",
"-",
"graph",
"."
] | def eightbitize_conv_node(self, original_node):
"""Replaces a Conv2D node with the eight bit equivalent sub-graph."""
all_input_names = self.add_eightbit_prologue_nodes(original_node)
quantized_conv_name = original_node.name + "_eightbit_quantized_conv"
quantized_conv_node = create_node("QuantizedConv2D", quantized_conv_name,
all_input_names)
copy_attr(quantized_conv_node, "strides", original_node.attr["strides"])
copy_attr(quantized_conv_node, "padding", original_node.attr["padding"])
set_attr_dtype(quantized_conv_node, "Tinput", tf.quint8)
set_attr_dtype(quantized_conv_node, "Tfilter", tf.quint8)
set_attr_dtype(quantized_conv_node, "out_type", tf.qint32)
self.add_output_graph_node(quantized_conv_node)
quantize_down_name = self.add_quantize_down_node(original_node,
quantized_conv_name)
self.add_dequantize_result_node(quantize_down_name, original_node.name) | [
"def",
"eightbitize_conv_node",
"(",
"self",
",",
"original_node",
")",
":",
"all_input_names",
"=",
"self",
".",
"add_eightbit_prologue_nodes",
"(",
"original_node",
")",
"quantized_conv_name",
"=",
"original_node",
".",
"name",
"+",
"\"_eightbit_quantized_conv\"",
"qu... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L586-L600 | ||
alexgkendall/caffe-posenet | 62aafbd7c45df91acdba14f5d1406d8295c2bc6f | python/caffe/io.py | python | resize_image | (im, new_dims, interp_order=1) | return resized_im.astype(np.float32) | Resize an image array with interpolation.
Parameters
----------
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
interp_order : interpolation order, default is linear.
Returns
-------
im : resized ndarray with shape (new_dims[0], new_dims[1], K) | Resize an image array with interpolation. | [
"Resize",
"an",
"image",
"array",
"with",
"interpolation",
"."
] | def resize_image(im, new_dims, interp_order=1):
"""
Resize an image array with interpolation.
Parameters
----------
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
interp_order : interpolation order, default is linear.
Returns
-------
im : resized ndarray with shape (new_dims[0], new_dims[1], K)
"""
if im.shape[-1] == 1 or im.shape[-1] == 3:
im_min, im_max = im.min(), im.max()
if im_max > im_min:
# skimage is fast but only understands {1,3} channel images
# in [0, 1].
im_std = (im - im_min) / (im_max - im_min)
resized_std = resize(im_std, new_dims, order=interp_order)
resized_im = resized_std * (im_max - im_min) + im_min
else:
# the image is a constant -- avoid divide by 0
ret = np.empty((new_dims[0], new_dims[1], im.shape[-1]),
dtype=np.float32)
ret.fill(im_min)
return ret
else:
# ndimage interpolates anything but more slowly.
scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2]))
resized_im = zoom(im, scale + (1,), order=interp_order)
return resized_im.astype(np.float32) | [
"def",
"resize_image",
"(",
"im",
",",
"new_dims",
",",
"interp_order",
"=",
"1",
")",
":",
"if",
"im",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",
"or",
"im",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"3",
":",
"im_min",
",",
"im_max",
"=",
"... | https://github.com/alexgkendall/caffe-posenet/blob/62aafbd7c45df91acdba14f5d1406d8295c2bc6f/python/caffe/io.py#L305-L337 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/utils/postinversion.py | python | modCovar | (inv) | Formal model covariance matrix (MCM) from inversion.
var, MCMs = modCovar(inv)
Parameters
----------
inv : pygimli inversion object
Returns
-------
var : variances (inverse square roots of MCM matrix)
MCMs : scaled MCM (such that diagonals are 1.0)
Examples
--------
>>> # import pygimli as pg
>>> # import matplotlib.pyplot as plt
>>> # from matplotlib.cm import bwr
>>> # INV = pg.Inversion(data, f)
>>> # par = INV.run()
>>> # var, MCM = modCovar(INV)
>>> # i = plt.imshow(MCM, interpolation='nearest',
>>> # cmap=bwr, vmin=-1, vmax=1)
>>> # plt.colorbar(i) | Formal model covariance matrix (MCM) from inversion. | [
"Formal",
"model",
"covariance",
"matrix",
"(",
"MCM",
")",
"from",
"inversion",
"."
] | def modCovar(inv):
"""Formal model covariance matrix (MCM) from inversion.
var, MCMs = modCovar(inv)
Parameters
----------
inv : pygimli inversion object
Returns
-------
var : variances (inverse square roots of MCM matrix)
MCMs : scaled MCM (such that diagonals are 1.0)
Examples
--------
>>> # import pygimli as pg
>>> # import matplotlib.pyplot as plt
>>> # from matplotlib.cm import bwr
>>> # INV = pg.Inversion(data, f)
>>> # par = INV.run()
>>> # var, MCM = modCovar(INV)
>>> # i = plt.imshow(MCM, interpolation='nearest',
>>> # cmap=bwr, vmin=-1, vmax=1)
>>> # plt.colorbar(i)
"""
td = np.asarray(inv.transData().deriv(inv.response()))
tm = np.asarray(inv.transModel().deriv(inv.model()))
J = td.reshape(len(td), 1) * \
gmat2numpy(inv.forwardOperator().jacobian()) * (1. / tm)
d = 1. / np.asarray(inv.transData().error(inv.response(), inv.error()))
DJ = d.reshape(len(d), 1) * J
JTJ = DJ.T.dot(DJ)
try:
MCM = np.linalg.inv(JTJ) # model covariance matrix
varVG = np.sqrt(np.diag(MCM)) # standard deviations from main diagonal
di = (1.0 / varVG) # variances as column vector
# scaled model covariance (=correlation) matrix
MCMs = di.reshape(len(di), 1) * MCM * di
return varVG, MCMs
except BaseException as e:
print(e)
import traceback
import sys
traceback.print_exc(file=sys.stdout)
return np.zeros(len(inv.model()),), 0 | [
"def",
"modCovar",
"(",
"inv",
")",
":",
"td",
"=",
"np",
".",
"asarray",
"(",
"inv",
".",
"transData",
"(",
")",
".",
"deriv",
"(",
"inv",
".",
"response",
"(",
")",
")",
")",
"tm",
"=",
"np",
".",
"asarray",
"(",
"inv",
".",
"transModel",
"("... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/utils/postinversion.py#L69-L120 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | uCSIsCatMc | (code) | return ret | Check whether the character is part of Mc UCS Category | Check whether the character is part of Mc UCS Category | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Mc",
"UCS",
"Category"
] | def uCSIsCatMc(code):
"""Check whether the character is part of Mc UCS Category """
ret = libxml2mod.xmlUCSIsCatMc(code)
return ret | [
"def",
"uCSIsCatMc",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCatMc",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2306-L2309 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/nyan/nyan_structs.py | python | NyanPatch.set_target | (self, target) | Set the target of the patch. | Set the target of the patch. | [
"Set",
"the",
"target",
"of",
"the",
"patch",
"."
] | def set_target(self, target):
"""
Set the target of the patch.
"""
self._target = target
if not isinstance(self._target, NyanObject):
raise Exception(f"{self.__repr__()}: '_target' must have NyanObject type") | [
"def",
"set_target",
"(",
"self",
",",
"target",
")",
":",
"self",
".",
"_target",
"=",
"target",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_target",
",",
"NyanObject",
")",
":",
"raise",
"Exception",
"(",
"f\"{self.__repr__()}: '_target' must have NyanObjec... | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/nyan/nyan_structs.py#L506-L513 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/WorkingPlane.py | python | Plane.offsetToPoint | (self, p, direction=None) | return direction.dot(self.position.sub(p)) | Return the signed distance from a point to the plane.
Parameters
----------
p : Base::Vector3
The external point to consider.
direction : Base::Vector3, optional
The unit vector that indicates the direction of the distance.
It defaults to `None`, which then uses the `plane.axis` (normal)
value, meaning that the measured distance is perpendicular
to the plane.
Returns
-------
float
The distance from the point to the plane.
Notes
-----
The signed distance `d`, from `p` to the plane, is such that
::
x = p + d*direction,
where `x` is a point that lies on the plane.
The `direction` is a unit vector that specifies the direction
in which the distance is measured.
It defaults to `plane.axis`,
meaning that it is the perpendicular distance.
A picture will help explain the computation
::
p
//|
/ / |
d / / | axis
/ / |
/ / |
-------- plane -----x-----c-----a--------
The points are as follows
* `p` is an arbitrary point outside the plane.
* `c` is a known point on the plane,
for example, `plane.position`.
* `x` is the intercept on the plane from `p` in
the desired `direction`.
* `a` is the perpendicular intercept on the plane,
i.e. along `plane.axis`.
The distance is calculated through the dot product
of the vector `pc` (going from point `p` to point `c`,
both of which are known) with the unit vector `direction`
(which is provided or defaults to `plane.axis`).
::
d = pc . direction
d = (c - p) . direction
**Warning:** this implementation doesn't calculate the entire
distance `|xp|`, only the distance `|pc|` projected onto `|xp|`.
Trigonometric relationships
---------------------------
In 2D the distances can be calculated by trigonometric relationships
::
|ap| = |cp| cos(apc) = |xp| cos(apx)
Then the desired distance is `d = |xp|`
::
|xp| = |cp| cos(apc) / cos(apx)
The cosines can be obtained from the definition of the dot product
::
A . B = |A||B| cos(angleAB)
If one vector is a unit vector
::
A . uB = |A| cos(angleAB)
cp . axis = |cp| cos(apc)
and if both vectors are unit vectors
::
uA . uB = cos(angleAB).
direction . axis = cos(apx)
Then
::
d = (cp . axis) / (direction . axis)
**Note:** for 2D these trigonometric operations
produce the full `|xp|` distance. | Return the signed distance from a point to the plane. | [
"Return",
"the",
"signed",
"distance",
"from",
"a",
"point",
"to",
"the",
"plane",
"."
] | def offsetToPoint(self, p, direction=None):
"""Return the signed distance from a point to the plane.
Parameters
----------
p : Base::Vector3
The external point to consider.
direction : Base::Vector3, optional
The unit vector that indicates the direction of the distance.
It defaults to `None`, which then uses the `plane.axis` (normal)
value, meaning that the measured distance is perpendicular
to the plane.
Returns
-------
float
The distance from the point to the plane.
Notes
-----
The signed distance `d`, from `p` to the plane, is such that
::
x = p + d*direction,
where `x` is a point that lies on the plane.
The `direction` is a unit vector that specifies the direction
in which the distance is measured.
It defaults to `plane.axis`,
meaning that it is the perpendicular distance.
A picture will help explain the computation
::
p
//|
/ / |
d / / | axis
/ / |
/ / |
-------- plane -----x-----c-----a--------
The points are as follows
* `p` is an arbitrary point outside the plane.
* `c` is a known point on the plane,
for example, `plane.position`.
* `x` is the intercept on the plane from `p` in
the desired `direction`.
* `a` is the perpendicular intercept on the plane,
i.e. along `plane.axis`.
The distance is calculated through the dot product
of the vector `pc` (going from point `p` to point `c`,
both of which are known) with the unit vector `direction`
(which is provided or defaults to `plane.axis`).
::
d = pc . direction
d = (c - p) . direction
**Warning:** this implementation doesn't calculate the entire
distance `|xp|`, only the distance `|pc|` projected onto `|xp|`.
Trigonometric relationships
---------------------------
In 2D the distances can be calculated by trigonometric relationships
::
|ap| = |cp| cos(apc) = |xp| cos(apx)
Then the desired distance is `d = |xp|`
::
|xp| = |cp| cos(apc) / cos(apx)
The cosines can be obtained from the definition of the dot product
::
A . B = |A||B| cos(angleAB)
If one vector is a unit vector
::
A . uB = |A| cos(angleAB)
cp . axis = |cp| cos(apc)
and if both vectors are unit vectors
::
uA . uB = cos(angleAB).
direction . axis = cos(apx)
Then
::
d = (cp . axis) / (direction . axis)
**Note:** for 2D these trigonometric operations
produce the full `|xp|` distance.
"""
if direction is None:
direction = self.axis
return direction.dot(self.position.sub(p)) | [
"def",
"offsetToPoint",
"(",
"self",
",",
"p",
",",
"direction",
"=",
"None",
")",
":",
"if",
"direction",
"is",
"None",
":",
"direction",
"=",
"self",
".",
"axis",
"return",
"direction",
".",
"dot",
"(",
"self",
".",
"position",
".",
"sub",
"(",
"p"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/WorkingPlane.py#L131-L228 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/encodings/hex_codec.py | python | hex_encode | (input,errors='strict') | return (output, len(input)) | Encodes the object input and returns a tuple (output
object, length consumed).
errors defines the error handling to apply. It defaults to
'strict' handling which is the only currently supported
error handling for this codec. | Encodes the object input and returns a tuple (output
object, length consumed). | [
"Encodes",
"the",
"object",
"input",
"and",
"returns",
"a",
"tuple",
"(",
"output",
"object",
"length",
"consumed",
")",
"."
] | def hex_encode(input,errors='strict'):
""" Encodes the object input and returns a tuple (output
object, length consumed).
errors defines the error handling to apply. It defaults to
'strict' handling which is the only currently supported
error handling for this codec.
"""
assert errors == 'strict'
output = binascii.b2a_hex(input)
return (output, len(input)) | [
"def",
"hex_encode",
"(",
"input",
",",
"errors",
"=",
"'strict'",
")",
":",
"assert",
"errors",
"==",
"'strict'",
"output",
"=",
"binascii",
".",
"b2a_hex",
"(",
"input",
")",
"return",
"(",
"output",
",",
"len",
"(",
"input",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/encodings/hex_codec.py#L13-L25 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py | python | IMAP4.recent | (self) | return self._untagged_response(typ, dat, name) | Return most recent 'RECENT' responses if any exist,
else prompt server for an update using the 'NOOP' command.
(typ, [data]) = <instance>.recent()
'data' is None if no new messages,
else list of RECENT responses, most recent last. | Return most recent 'RECENT' responses if any exist,
else prompt server for an update using the 'NOOP' command. | [
"Return",
"most",
"recent",
"RECENT",
"responses",
"if",
"any",
"exist",
"else",
"prompt",
"server",
"for",
"an",
"update",
"using",
"the",
"NOOP",
"command",
"."
] | def recent(self):
"""Return most recent 'RECENT' responses if any exist,
else prompt server for an update using the 'NOOP' command.
(typ, [data]) = <instance>.recent()
'data' is None if no new messages,
else list of RECENT responses, most recent last.
"""
name = 'RECENT'
typ, dat = self._untagged_response('OK', [None], name)
if dat[-1]:
return typ, dat
typ, dat = self.noop() # Prod server for response
return self._untagged_response(typ, dat, name) | [
"def",
"recent",
"(",
"self",
")",
":",
"name",
"=",
"'RECENT'",
"typ",
",",
"dat",
"=",
"self",
".",
"_untagged_response",
"(",
"'OK'",
",",
"[",
"None",
"]",
",",
"name",
")",
"if",
"dat",
"[",
"-",
"1",
"]",
":",
"return",
"typ",
",",
"dat",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py#L349-L363 | |
pskun/finance_news_analysis | 6ac13e32deede37a4cf57bba8b2897941ae3d80d | utils/threadpool.py | python | ThreadPool.wait_completion | (self) | 等待数据处理完成 | 等待数据处理完成 | [
"等待数据处理完成"
] | def wait_completion(self):
""" 等待数据处理完成 """
self.__queue.join()
pass | [
"def",
"wait_completion",
"(",
"self",
")",
":",
"self",
".",
"__queue",
".",
"join",
"(",
")",
"pass"
] | https://github.com/pskun/finance_news_analysis/blob/6ac13e32deede37a4cf57bba8b2897941ae3d80d/utils/threadpool.py#L80-L83 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/filters.py | python | do_default | (value, default_value=u'', boolean=False) | return value | If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defined'``. If you want
to use default with variables that evaluate to false you have to
set the second parameter to `true`:
.. sourcecode:: jinja
{{ ''|default('the string was empty', true) }} | If the value is undefined it will return the passed default value,
otherwise the value of the variable: | [
"If",
"the",
"value",
"is",
"undefined",
"it",
"will",
"return",
"the",
"passed",
"default",
"value",
"otherwise",
"the",
"value",
"of",
"the",
"variable",
":"
] | def do_default(value, default_value=u'', boolean=False):
"""If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defined'``. If you want
to use default with variables that evaluate to false you have to
set the second parameter to `true`:
.. sourcecode:: jinja
{{ ''|default('the string was empty', true) }}
"""
if isinstance(value, Undefined) or (boolean and not value):
return default_value
return value | [
"def",
"do_default",
"(",
"value",
",",
"default_value",
"=",
"u''",
",",
"boolean",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Undefined",
")",
"or",
"(",
"boolean",
"and",
"not",
"value",
")",
":",
"return",
"default_value",
"retur... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/filters.py#L268-L287 | |
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/autograd.py | python | Atan.forward | (self, x) | return singa.Atan(x) | Args:
x (CTensor): Input tensor
Returns:
CTensor, the output | Args:
x (CTensor): Input tensor
Returns:
CTensor, the output | [
"Args",
":",
"x",
"(",
"CTensor",
")",
":",
"Input",
"tensor",
"Returns",
":",
"CTensor",
"the",
"output"
] | def forward(self, x):
"""
Args:
x (CTensor): Input tensor
Returns:
CTensor, the output
"""
if training:
self.input = x
return singa.Atan(x) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"if",
"training",
":",
"self",
".",
"input",
"=",
"x",
"return",
"singa",
".",
"Atan",
"(",
"x",
")"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L2373-L2382 | |
networkit/networkit | 695b7a786a894a303fa8587597d5ef916e797729 | networkit/nxadapter.py | python | nk2nx | (nkG) | return nxG | Convert a NetworKit.Graph to a networkx.Graph | Convert a NetworKit.Graph to a networkx.Graph | [
"Convert",
"a",
"NetworKit",
".",
"Graph",
"to",
"a",
"networkx",
".",
"Graph"
] | def nk2nx(nkG):
""" Convert a NetworKit.Graph to a networkx.Graph """
if not have_nx:
raise MissingDependencyError("networkx")
if nkG.isDirected():
nxG = nx.DiGraph()
else:
nxG = nx.Graph()
nxG.add_nodes_from(nkG.iterNodes())
if nkG.isWeighted():
for u, v, w in nkG.iterEdgesWeights():
nxG.add_edge(u, v, weight=w)
else:
nxG.add_edges_from(nkG.iterEdges())
assert (nkG.numberOfNodes() == nxG.number_of_nodes())
assert (nkG.numberOfEdges() == nxG.number_of_edges())
return nxG | [
"def",
"nk2nx",
"(",
"nkG",
")",
":",
"if",
"not",
"have_nx",
":",
"raise",
"MissingDependencyError",
"(",
"\"networkx\"",
")",
"if",
"nkG",
".",
"isDirected",
"(",
")",
":",
"nxG",
"=",
"nx",
".",
"DiGraph",
"(",
")",
"else",
":",
"nxG",
"=",
"nx",
... | https://github.com/networkit/networkit/blob/695b7a786a894a303fa8587597d5ef916e797729/networkit/nxadapter.py#L51-L70 | |
facebookarchive/LogDevice | ce7726050edc49a1e15d9160e81c890736b779e2 | logdevice/ops/ldops/admin_api.py | python | get_maintenances | (
client: AdminAPI, req: Optional[MaintenancesFilter] = None
) | return await client.getMaintenances(req or MaintenancesFilter()) | Wrapper for getMaintenances() Thrift method | Wrapper for getMaintenances() Thrift method | [
"Wrapper",
"for",
"getMaintenances",
"()",
"Thrift",
"method"
] | async def get_maintenances(
client: AdminAPI, req: Optional[MaintenancesFilter] = None
) -> MaintenanceDefinitionResponse:
"""
Wrapper for getMaintenances() Thrift method
"""
return await client.getMaintenances(req or MaintenancesFilter()) | [
"async",
"def",
"get_maintenances",
"(",
"client",
":",
"AdminAPI",
",",
"req",
":",
"Optional",
"[",
"MaintenancesFilter",
"]",
"=",
"None",
")",
"->",
"MaintenanceDefinitionResponse",
":",
"return",
"await",
"client",
".",
"getMaintenances",
"(",
"req",
"or",
... | https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/logdevice/ops/ldops/admin_api.py#L148-L154 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/base.py | python | SelectionMixin._is_cython_func | (self, arg) | return self._cython_table.get(arg) | if we define an internal function for this argument, return it | if we define an internal function for this argument, return it | [
"if",
"we",
"define",
"an",
"internal",
"function",
"for",
"this",
"argument",
"return",
"it"
] | def _is_cython_func(self, arg):
"""
if we define an internal function for this argument, return it
"""
return self._cython_table.get(arg) | [
"def",
"_is_cython_func",
"(",
"self",
",",
"arg",
")",
":",
"return",
"self",
".",
"_cython_table",
".",
"get",
"(",
"arg",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/base.py#L649-L653 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_pyio.py | python | IOBase.seek | (self, pos, whence=0) | Change stream position.
Change the stream position to byte offset pos. Argument pos is
interpreted relative to the position indicated by whence. Values
for whence are:
* 0 -- start of stream (the default); offset should be zero or positive
* 1 -- current stream position; offset may be negative
* 2 -- end of stream; offset is usually negative
Return the new absolute position. | Change stream position. | [
"Change",
"stream",
"position",
"."
] | def seek(self, pos, whence=0):
"""Change stream position.
Change the stream position to byte offset pos. Argument pos is
interpreted relative to the position indicated by whence. Values
for whence are:
* 0 -- start of stream (the default); offset should be zero or positive
* 1 -- current stream position; offset may be negative
* 2 -- end of stream; offset is usually negative
Return the new absolute position.
"""
self._unsupported("seek") | [
"def",
"seek",
"(",
"self",
",",
"pos",
",",
"whence",
"=",
"0",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"seek\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_pyio.py#L298-L311 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/docs/utils.py | python | py_type_name | (type_name) | return {
'blob': 'bytes',
'character': 'string',
'double': 'float',
'long': 'integer',
'map': 'dict',
'structure': 'dict',
'timestamp': 'datetime',
}.get(type_name, type_name) | Get the Python type name for a given model type.
>>> py_type_name('list')
'list'
>>> py_type_name('structure')
'dict'
:rtype: string | Get the Python type name for a given model type. | [
"Get",
"the",
"Python",
"type",
"name",
"for",
"a",
"given",
"model",
"type",
"."
] | def py_type_name(type_name):
"""Get the Python type name for a given model type.
>>> py_type_name('list')
'list'
>>> py_type_name('structure')
'dict'
:rtype: string
"""
return {
'blob': 'bytes',
'character': 'string',
'double': 'float',
'long': 'integer',
'map': 'dict',
'structure': 'dict',
'timestamp': 'datetime',
}.get(type_name, type_name) | [
"def",
"py_type_name",
"(",
"type_name",
")",
":",
"return",
"{",
"'blob'",
":",
"'bytes'",
",",
"'character'",
":",
"'string'",
",",
"'double'",
":",
"'float'",
",",
"'long'",
":",
"'integer'",
",",
"'map'",
":",
"'dict'",
",",
"'structure'",
":",
"'dict'... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/docs/utils.py#L17-L35 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/ipaddress.py | python | IPv4Address.is_multicast | (self) | return self in self._constants._multicast_network | Test if the address is reserved for multicast use.
Returns:
A boolean, True if the address is multicast.
See RFC 3171 for details. | Test if the address is reserved for multicast use. | [
"Test",
"if",
"the",
"address",
"is",
"reserved",
"for",
"multicast",
"use",
"."
] | def is_multicast(self):
"""Test if the address is reserved for multicast use.
Returns:
A boolean, True if the address is multicast.
See RFC 3171 for details.
"""
return self in self._constants._multicast_network | [
"def",
"is_multicast",
"(",
"self",
")",
":",
"return",
"self",
"in",
"self",
".",
"_constants",
".",
"_multicast_network"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/ipaddress.py#L1363-L1371 | |
CGRU/cgru | 1881a4128530e3d31ac6c25314c18314fc50c2c7 | afanasy/python/af.py | python | Job.setPriority | (self, priority) | Missing DocString
:param priority:
:return: | Missing DocString | [
"Missing",
"DocString"
] | def setPriority(self, priority):
"""Missing DocString
:param priority:
:return:
"""
if priority < 0:
return
if priority > 250:
priority = 250
print('Warning: priority clamped to maximum = %d' % priority)
self.data["priority"] = int(priority) | [
"def",
"setPriority",
"(",
"self",
",",
"priority",
")",
":",
"if",
"priority",
"<",
"0",
":",
"return",
"if",
"priority",
">",
"250",
":",
"priority",
"=",
"250",
"print",
"(",
"'Warning: priority clamped to maximum = %d'",
"%",
"priority",
")",
"self",
"."... | https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L603-L616 | ||
JumpingYang001/webrtc | c03d6e965e1f54aeadd670e491eabe5fdb8db968 | rtc_tools/py_event_log_analyzer/misc.py | python | CountReordered | (sequence_numbers) | return sum(1 for (s1, s2) in zip(sequence_numbers, sequence_numbers[1:])
if s1 >= s2) | Returns number of reordered indices.
A reordered index is an index `i` for which sequence_numbers[i] >=
sequence_numbers[i + 1] | Returns number of reordered indices. | [
"Returns",
"number",
"of",
"reordered",
"indices",
"."
] | def CountReordered(sequence_numbers):
"""Returns number of reordered indices.
A reordered index is an index `i` for which sequence_numbers[i] >=
sequence_numbers[i + 1]
"""
return sum(1 for (s1, s2) in zip(sequence_numbers, sequence_numbers[1:])
if s1 >= s2) | [
"def",
"CountReordered",
"(",
"sequence_numbers",
")",
":",
"return",
"sum",
"(",
"1",
"for",
"(",
"s1",
",",
"s2",
")",
"in",
"zip",
"(",
"sequence_numbers",
",",
"sequence_numbers",
"[",
"1",
":",
"]",
")",
"if",
"s1",
">=",
"s2",
")"
] | https://github.com/JumpingYang001/webrtc/blob/c03d6e965e1f54aeadd670e491eabe5fdb8db968/rtc_tools/py_event_log_analyzer/misc.py#L16-L23 | |
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/utils/sort_includes.py | python | sort_includes | (f) | Sort the #include lines of a specific file. | Sort the #include lines of a specific file. | [
"Sort",
"the",
"#include",
"lines",
"of",
"a",
"specific",
"file",
"."
] | def sort_includes(f):
"""Sort the #include lines of a specific file."""
# Skip files which are under INPUTS trees or test trees.
if 'INPUTS/' in f.name or 'test/' in f.name:
return
ext = os.path.splitext(f.name)[1]
if ext not in ['.cpp', '.c', '.h', '.inc', '.def']:
return
lines = f.readlines()
look_for_api_header = ext in ['.cpp', '.c']
found_headers = False
headers_begin = 0
headers_end = 0
api_headers = []
local_headers = []
subproject_headers = []
llvm_headers = []
system_headers = []
for (i, l) in enumerate(lines):
if l.strip() == '':
continue
if l.startswith('#include'):
if not found_headers:
headers_begin = i
found_headers = True
headers_end = i
header = l[len('#include'):].lstrip()
if look_for_api_header and header.startswith('"'):
api_headers.append(header)
look_for_api_header = False
continue
if (header.startswith('<') or header.startswith('"gtest/') or
header.startswith('"isl/') or header.startswith('"json/')):
system_headers.append(header)
continue
if (header.startswith('"clang/') or header.startswith('"clang-c/') or
header.startswith('"polly/')):
subproject_headers.append(header)
continue
if (header.startswith('"llvm/') or header.startswith('"llvm-c/')):
llvm_headers.append(header)
continue
local_headers.append(header)
continue
# Only allow comments and #defines prior to any includes. If either are
# mixed with includes, the order might be sensitive.
if found_headers:
break
if l.startswith('//') or l.startswith('#define') or l.startswith('#ifndef'):
continue
break
if not found_headers:
return
local_headers = sorted(set(local_headers))
subproject_headers = sorted(set(subproject_headers))
llvm_headers = sorted(set(llvm_headers))
system_headers = sorted(set(system_headers))
headers = api_headers + local_headers + subproject_headers + llvm_headers + system_headers
header_lines = ['#include ' + h for h in headers]
lines = lines[:headers_begin] + header_lines + lines[headers_end + 1:]
f.seek(0)
f.truncate()
f.writelines(lines) | [
"def",
"sort_includes",
"(",
"f",
")",
":",
"# Skip files which are under INPUTS trees or test trees.",
"if",
"'INPUTS/'",
"in",
"f",
".",
"name",
"or",
"'test/'",
"in",
"f",
".",
"name",
":",
"return",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"f... | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/utils/sort_includes.py#L14-L82 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/special/_precompute/gammainc_data.py | python | gammaincc | (a, x, dps=50, maxterms=10**8) | Compute gammaincc exactly like mpmath does but allow for more
terms in hypercomb. See
mpmath/functions/expintegrals.py#L187
in the mpmath github repository. | Compute gammaincc exactly like mpmath does but allow for more
terms in hypercomb. See | [
"Compute",
"gammaincc",
"exactly",
"like",
"mpmath",
"does",
"but",
"allow",
"for",
"more",
"terms",
"in",
"hypercomb",
".",
"See"
] | def gammaincc(a, x, dps=50, maxterms=10**8):
"""Compute gammaincc exactly like mpmath does but allow for more
terms in hypercomb. See
mpmath/functions/expintegrals.py#L187
in the mpmath github repository.
"""
with mp.workdps(dps):
z, a = a, x
if mp.isint(z):
try:
# mpmath has a fast integer path
return mpf2float(mp.gammainc(z, a=a, regularized=True))
except mp.libmp.NoConvergence:
pass
nega = mp.fneg(a, exact=True)
G = [z]
# Use 2F0 series when possible; fall back to lower gamma representation
try:
def h(z):
r = z-1
return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)]
return mpf2float(mp.hypercomb(h, [z], force_series=True))
except mp.libmp.NoConvergence:
def h(z):
T1 = [], [1, z-1], [z], G, [], [], 0
T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a
return T1, T2
return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms)) | [
"def",
"gammaincc",
"(",
"a",
",",
"x",
",",
"dps",
"=",
"50",
",",
"maxterms",
"=",
"10",
"**",
"8",
")",
":",
"with",
"mp",
".",
"workdps",
"(",
"dps",
")",
":",
"z",
",",
"a",
"=",
"a",
",",
"x",
"if",
"mp",
".",
"isint",
"(",
"z",
")"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/special/_precompute/gammainc_data.py#L57-L88 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/network/lazy_wheel.py | python | dist_from_wheel_url | (name, url, session) | Return a pkg_resources.Distribution from the given wheel URL.
This uses HTTP range requests to only fetch the potion of the wheel
containing metadata, just enough for the object to be constructed.
If such requests are not supported, HTTPRangeRequestUnsupported
is raised. | Return a pkg_resources.Distribution from the given wheel URL. | [
"Return",
"a",
"pkg_resources",
".",
"Distribution",
"from",
"the",
"given",
"wheel",
"URL",
"."
] | def dist_from_wheel_url(name, url, session):
# type: (str, str, PipSession) -> Distribution
"""Return a pkg_resources.Distribution from the given wheel URL.
This uses HTTP range requests to only fetch the potion of the wheel
containing metadata, just enough for the object to be constructed.
If such requests are not supported, HTTPRangeRequestUnsupported
is raised.
"""
with LazyZipOverHTTP(url, session) as wheel:
# For read-only ZIP files, ZipFile only needs methods read,
# seek, seekable and tell, not the whole IO protocol.
zip_file = ZipFile(wheel) # type: ignore
# After context manager exit, wheel.name
# is an invalid file by intention.
return pkg_resources_distribution_for_wheel(zip_file, name, wheel.name) | [
"def",
"dist_from_wheel_url",
"(",
"name",
",",
"url",
",",
"session",
")",
":",
"# type: (str, str, PipSession) -> Distribution",
"with",
"LazyZipOverHTTP",
"(",
"url",
",",
"session",
")",
"as",
"wheel",
":",
"# For read-only ZIP files, ZipFile only needs methods read,",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/network/lazy_wheel.py#L57-L87 | ||
microsoft/AirSim | 8057725712c0cd46979135396381784075ffc0f3 | PythonClient/airsim/utils.py | python | read_pfm | (file) | return data, scale | Read a pfm file | Read a pfm file | [
"Read",
"a",
"pfm",
"file"
] | def read_pfm(file):
""" Read a pfm file """
file = open(file, 'rb')
color = None
width = None
height = None
scale = None
endian = None
header = file.readline().rstrip()
header = str(bytes.decode(header, encoding='utf-8'))
if header == 'PF':
color = True
elif header == 'Pf':
color = False
else:
raise Exception('Not a PFM file.')
temp_str = str(bytes.decode(file.readline(), encoding='utf-8'))
dim_match = re.match(r'^(\d+)\s(\d+)\s$', temp_str)
if dim_match:
width, height = map(int, dim_match.groups())
else:
raise Exception('Malformed PFM header.')
scale = float(file.readline().rstrip())
if scale < 0: # little-endian
endian = '<'
scale = -scale
else:
endian = '>' # big-endian
data = np.fromfile(file, endian + 'f')
shape = (height, width, 3) if color else (height, width)
data = np.reshape(data, shape)
# DEY: I don't know why this was there.
file.close()
return data, scale | [
"def",
"read_pfm",
"(",
"file",
")",
":",
"file",
"=",
"open",
"(",
"file",
",",
"'rb'",
")",
"color",
"=",
"None",
"width",
"=",
"None",
"height",
"=",
"None",
"scale",
"=",
"None",
"endian",
"=",
"None",
"header",
"=",
"file",
".",
"readline",
"(... | https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/airsim/utils.py#L127-L167 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/PngImagePlugin.py | python | getchunks | (im, **params) | return fp.data | Return a list of PNG chunks representing this image. | Return a list of PNG chunks representing this image. | [
"Return",
"a",
"list",
"of",
"PNG",
"chunks",
"representing",
"this",
"image",
"."
] | def getchunks(im, **params):
"""Return a list of PNG chunks representing this image."""
class collector:
data = []
def write(self, data):
pass
def append(self, chunk):
self.data.append(chunk)
def append(fp, cid, *data):
data = b"".join(data)
crc = o32(_crc32(data, _crc32(cid)))
fp.append((cid, data, crc))
fp = collector()
try:
im.encoderinfo = params
_save(im, fp, None, append)
finally:
del im.encoderinfo
return fp.data | [
"def",
"getchunks",
"(",
"im",
",",
"*",
"*",
"params",
")",
":",
"class",
"collector",
":",
"data",
"=",
"[",
"]",
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"pass",
"def",
"append",
"(",
"self",
",",
"chunk",
")",
":",
"self",
".",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/PngImagePlugin.py#L1312-L1337 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/volume.py | python | Volume.attachment_state | (self) | return state | Get the attachment state. | Get the attachment state. | [
"Get",
"the",
"attachment",
"state",
"."
] | def attachment_state(self):
"""
Get the attachment state.
"""
state = None
if self.attach_data:
state = self.attach_data.status
return state | [
"def",
"attachment_state",
"(",
"self",
")",
":",
"state",
"=",
"None",
"if",
"self",
".",
"attach_data",
":",
"state",
"=",
"self",
".",
"attach_data",
".",
"status",
"return",
"state"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/volume.py#L213-L220 | |
lyxok1/Tiny-DSOD | 94d15450699bea0dd3720e75e2d273e476174fba | python/caffe/coord_map.py | python | coord_map | (fn) | Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords. | Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords. | [
"Define",
"the",
"coordinate",
"mapping",
"by",
"its",
"-",
"axis",
"-",
"scale",
":",
"output",
"coord",
"[",
"i",
"*",
"scale",
"]",
"<",
"-",
"input_coord",
"[",
"i",
"]",
"-",
"shift",
":",
"output",
"coord",
"[",
"i",
"]",
"<",
"-",
"output_co... | def coord_map(fn):
"""
Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords.
"""
if fn.type_name in ['Convolution', 'Pooling', 'Im2col']:
axis, stride, ks, pad = conv_params(fn)
return axis, 1 / stride, (pad - (ks - 1) / 2) / stride
elif fn.type_name == 'Deconvolution':
axis, stride, ks, pad = conv_params(fn)
return axis, stride, (ks - 1) / 2 - pad
elif fn.type_name in PASS_THROUGH_LAYERS:
return None, 1, 0
elif fn.type_name == 'Crop':
axis, offset = crop_params(fn)
axis -= 1 # -1 for last non-coordinate dim.
return axis, 1, - offset
else:
raise UndefinedMapException | [
"def",
"coord_map",
"(",
"fn",
")",
":",
"if",
"fn",
".",
"type_name",
"in",
"[",
"'Convolution'",
",",
"'Pooling'",
",",
"'Im2col'",
"]",
":",
"axis",
",",
"stride",
",",
"ks",
",",
"pad",
"=",
"conv_params",
"(",
"fn",
")",
"return",
"axis",
",",
... | https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/python/caffe/coord_map.py#L57-L79 | ||
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/google/protobuf/descriptor.py | python | Descriptor.__init__ | (self, name, full_name, filename, containing_type, fields,
nested_types, enum_types, extensions, options=None,
is_extendable=True, extension_ranges=None, oneofs=None,
file=None, serialized_start=None, serialized_end=None,
syntax=None) | Arguments to __init__() are as described in the description
of Descriptor fields above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute. | Arguments to __init__() are as described in the description
of Descriptor fields above. | [
"Arguments",
"to",
"__init__",
"()",
"are",
"as",
"described",
"in",
"the",
"description",
"of",
"Descriptor",
"fields",
"above",
"."
] | def __init__(self, name, full_name, filename, containing_type, fields,
nested_types, enum_types, extensions, options=None,
is_extendable=True, extension_ranges=None, oneofs=None,
file=None, serialized_start=None, serialized_end=None,
syntax=None): # pylint:disable=redefined-builtin
"""Arguments to __init__() are as described in the description
of Descriptor fields above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute.
"""
super(Descriptor, self).__init__(
options, 'MessageOptions', name, full_name, file,
containing_type, serialized_start=serialized_start,
serialized_end=serialized_end)
# We have fields in addition to fields_by_name and fields_by_number,
# so that:
# 1. Clients can index fields by "order in which they're listed."
# 2. Clients can easily iterate over all fields with the terse
# syntax: for f in descriptor.fields: ...
self.fields = fields
for field in self.fields:
field.containing_type = self
self.fields_by_number = dict((f.number, f) for f in fields)
self.fields_by_name = dict((f.name, f) for f in fields)
self._fields_by_camelcase_name = None
self.nested_types = nested_types
for nested_type in nested_types:
nested_type.containing_type = self
self.nested_types_by_name = dict((t.name, t) for t in nested_types)
self.enum_types = enum_types
for enum_type in self.enum_types:
enum_type.containing_type = self
self.enum_types_by_name = dict((t.name, t) for t in enum_types)
self.enum_values_by_name = dict(
(v.name, v) for t in enum_types for v in t.values)
self.extensions = extensions
for extension in self.extensions:
extension.extension_scope = self
self.extensions_by_name = dict((f.name, f) for f in extensions)
self.is_extendable = is_extendable
self.extension_ranges = extension_ranges
self.oneofs = oneofs if oneofs is not None else []
self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
for oneof in self.oneofs:
oneof.containing_type = self
self.syntax = syntax or "proto2" | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"filename",
",",
"containing_type",
",",
"fields",
",",
"nested_types",
",",
"enum_types",
",",
"extensions",
",",
"options",
"=",
"None",
",",
"is_extendable",
"=",
"True",
",",
"extension_... | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/descriptor.py#L269-L319 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiMDIChildFrame.Iconize | (*args, **kwargs) | return _aui.AuiMDIChildFrame_Iconize(*args, **kwargs) | Iconize(self, bool iconize=True) | Iconize(self, bool iconize=True) | [
"Iconize",
"(",
"self",
"bool",
"iconize",
"=",
"True",
")"
] | def Iconize(*args, **kwargs):
"""Iconize(self, bool iconize=True)"""
return _aui.AuiMDIChildFrame_Iconize(*args, **kwargs) | [
"def",
"Iconize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiMDIChildFrame_Iconize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1570-L1572 | |
mickem/nscp | 79f89fdbb6da63f91bc9dedb7aea202fe938f237 | scripts/python/lib/google/protobuf/descriptor.py | python | MethodDescriptor.__init__ | (self, name, full_name, index, containing_service,
input_type, output_type, options=None) | The arguments are as described in the description of MethodDescriptor
attributes above.
Note that containing_service may be None, and may be set later if necessary. | The arguments are as described in the description of MethodDescriptor
attributes above. | [
"The",
"arguments",
"are",
"as",
"described",
"in",
"the",
"description",
"of",
"MethodDescriptor",
"attributes",
"above",
"."
] | def __init__(self, name, full_name, index, containing_service,
input_type, output_type, options=None):
"""The arguments are as described in the description of MethodDescriptor
attributes above.
Note that containing_service may be None, and may be set later if necessary.
"""
super(MethodDescriptor, self).__init__(options, 'MethodOptions')
self.name = name
self.full_name = full_name
self.index = index
self.containing_service = containing_service
self.input_type = input_type
self.output_type = output_type | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"index",
",",
"containing_service",
",",
"input_type",
",",
"output_type",
",",
"options",
"=",
"None",
")",
":",
"super",
"(",
"MethodDescriptor",
",",
"self",
")",
".",
"__init__",
"(",
... | https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/descriptor.py#L545-L558 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/generator/cmake.py | python | SetVariableList | (output, variable_name, values) | Sets a CMake variable to a list. | Sets a CMake variable to a list. | [
"Sets",
"a",
"CMake",
"variable",
"to",
"a",
"list",
"."
] | def SetVariableList(output, variable_name, values):
"""Sets a CMake variable to a list."""
if not values:
return SetVariable(output, variable_name, "")
if len(values) == 1:
return SetVariable(output, variable_name, values[0])
output.write('list(APPEND ')
output.write(variable_name)
output.write('\n "')
output.write('"\n "'.join([CMakeStringEscape(value) for value in values]))
output.write('")\n') | [
"def",
"SetVariableList",
"(",
"output",
",",
"variable_name",
",",
"values",
")",
":",
"if",
"not",
"values",
":",
"return",
"SetVariable",
"(",
"output",
",",
"variable_name",
",",
"\"\"",
")",
"if",
"len",
"(",
"values",
")",
"==",
"1",
":",
"return",... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/cmake.py#L191-L201 | ||
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | Tools/mavlink_ulog_streaming.py | python | MavlinkLogStreaming.debug | (self, s, level=1) | write some debug text | write some debug text | [
"write",
"some",
"debug",
"text"
] | def debug(self, s, level=1):
'''write some debug text'''
if self._debug >= level:
print(s) | [
"def",
"debug",
"(",
"self",
",",
"s",
",",
"level",
"=",
"1",
")",
":",
"if",
"self",
".",
"_debug",
">=",
"level",
":",
"print",
"(",
"s",
")"
] | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_ulog_streaming.py#L57-L60 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_PCR_SetAuthPolicy_REQUEST.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
self.authPolicy = buf.readSizedByteBuf()
self.hashAlg = buf.readShort()
self.pcrNum = TPM_HANDLE.fromTpm(buf) | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"authPolicy",
"=",
"buf",
".",
"readSizedByteBuf",
"(",
")",
"self",
".",
"hashAlg",
"=",
"buf",
".",
"readShort",
"(",
")",
"self",
".",
"pcrNum",
"=",
"TPM_HANDLE",
".",
"fromTpm",... | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L14007-L14011 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | Distribution.load_entry_point | (self, group, name) | return ep.load() | Return the `name` entry point of `group` or raise ImportError | Return the `name` entry point of `group` or raise ImportError | [
"Return",
"the",
"name",
"entry",
"point",
"of",
"group",
"or",
"raise",
"ImportError"
] | def load_entry_point(self, group, name):
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group, name),))
return ep.load() | [
"def",
"load_entry_point",
"(",
"self",
",",
"group",
",",
"name",
")",
":",
"ep",
"=",
"self",
".",
"get_entry_info",
"(",
"group",
",",
"name",
")",
"if",
"ep",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"Entry point %r not found\"",
"%",
"(",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L2750-L2755 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetComputedDefines | (self, config) | return defines | Returns the set of defines that are injected to the defines list based
on other VS settings. | Returns the set of defines that are injected to the defines list based
on other VS settings. | [
"Returns",
"the",
"set",
"of",
"defines",
"that",
"are",
"injected",
"to",
"the",
"defines",
"list",
"based",
"on",
"other",
"VS",
"settings",
"."
] | def GetComputedDefines(self, config):
"""Returns the set of defines that are injected to the defines list based
on other VS settings."""
config = self._TargetConfig(config)
defines = []
if self._ConfigAttrib(["CharacterSet"], config) == "1":
defines.extend(("_UNICODE", "UNICODE"))
if self._ConfigAttrib(["CharacterSet"], config) == "2":
defines.append("_MBCS")
defines.extend(
self._Setting(
("VCCLCompilerTool", "PreprocessorDefinitions"), config, default=[]
)
)
return defines | [
"def",
"GetComputedDefines",
"(",
"self",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"defines",
"=",
"[",
"]",
"if",
"self",
".",
"_ConfigAttrib",
"(",
"[",
"\"CharacterSet\"",
"]",
",",
"config",
")",
"==",... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L399-L413 | |
google/certificate-transparency | 2588562fd306a447958471b6f06c1069619c1641 | python/ct/crypto/cert.py | python | certs_from_pem_file | (pem_file, skip_invalid_blobs=False, strict_der=True) | Read multiple PEM-encoded certificates from a file.
Args:
pem_file: the certificate file.
skip_invalid_blobs: if False, invalid PEM blobs cause a PemError.
If True, invalid blobs are skipped. In non-skip mode, an
immediate StopIteration before any valid blocks are found also
causes a PemError exception.
strict_der: if False, tolerate some non-fatal DER errors.
Yields:
Certificate objects.
Raises:
ct.crypto.pem.PemError, ct.crypto.error.ASN1Error:
a block was invalid
IOError: the file could not be read. | Read multiple PEM-encoded certificates from a file. | [
"Read",
"multiple",
"PEM",
"-",
"encoded",
"certificates",
"from",
"a",
"file",
"."
] | def certs_from_pem_file(pem_file, skip_invalid_blobs=False, strict_der=True):
"""Read multiple PEM-encoded certificates from a file.
Args:
pem_file: the certificate file.
skip_invalid_blobs: if False, invalid PEM blobs cause a PemError.
If True, invalid blobs are skipped. In non-skip mode, an
immediate StopIteration before any valid blocks are found also
causes a PemError exception.
strict_der: if False, tolerate some non-fatal DER errors.
Yields:
Certificate objects.
Raises:
ct.crypto.pem.PemError, ct.crypto.error.ASN1Error:
a block was invalid
IOError: the file could not be read.
"""
for der_cert, _ in pem.pem_blocks_from_file(
pem_file, Certificate.PEM_MARKERS,
skip_invalid_blobs=skip_invalid_blobs):
try:
yield Certificate.from_der(der_cert, strict_der=strict_der)
except error.ASN1Error:
if not skip_invalid_blobs:
raise | [
"def",
"certs_from_pem_file",
"(",
"pem_file",
",",
"skip_invalid_blobs",
"=",
"False",
",",
"strict_der",
"=",
"True",
")",
":",
"for",
"der_cert",
",",
"_",
"in",
"pem",
".",
"pem_blocks_from_file",
"(",
"pem_file",
",",
"Certificate",
".",
"PEM_MARKERS",
",... | https://github.com/google/certificate-transparency/blob/2588562fd306a447958471b6f06c1069619c1641/python/ct/crypto/cert.py#L935-L961 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | StandardPaths_Get | (*args) | return _misc_.StandardPaths_Get(*args) | StandardPaths_Get() -> StandardPaths
Return the global standard paths singleton | StandardPaths_Get() -> StandardPaths | [
"StandardPaths_Get",
"()",
"-",
">",
"StandardPaths"
] | def StandardPaths_Get(*args):
"""
StandardPaths_Get() -> StandardPaths
Return the global standard paths singleton
"""
return _misc_.StandardPaths_Get(*args) | [
"def",
"StandardPaths_Get",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"StandardPaths_Get",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6472-L6478 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | Grid.GetRowLabelAlignment | (*args, **kwargs) | return _grid.Grid_GetRowLabelAlignment(*args, **kwargs) | GetRowLabelAlignment() -> (horiz, vert) | GetRowLabelAlignment() -> (horiz, vert) | [
"GetRowLabelAlignment",
"()",
"-",
">",
"(",
"horiz",
"vert",
")"
] | def GetRowLabelAlignment(*args, **kwargs):
"""GetRowLabelAlignment() -> (horiz, vert)"""
return _grid.Grid_GetRowLabelAlignment(*args, **kwargs) | [
"def",
"GetRowLabelAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetRowLabelAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1498-L1500 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | CustomDataObject.GetData | (*args, **kwargs) | return _misc_.CustomDataObject_GetData(*args, **kwargs) | GetData(self) -> String
Returns the data bytes from the data object as a string. | GetData(self) -> String | [
"GetData",
"(",
"self",
")",
"-",
">",
"String"
] | def GetData(*args, **kwargs):
"""
GetData(self) -> String
Returns the data bytes from the data object as a string.
"""
return _misc_.CustomDataObject_GetData(*args, **kwargs) | [
"def",
"GetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"CustomDataObject_GetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L5398-L5404 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/base/role_maker.py | python | PaddleCloudRoleMaker._is_first_worker | (self) | return self._role == Role.WORKER and self._current_id == 0 | whether current process is worker of rank 0 | whether current process is worker of rank 0 | [
"whether",
"current",
"process",
"is",
"worker",
"of",
"rank",
"0"
] | def _is_first_worker(self):
"""
whether current process is worker of rank 0
"""
if not self._role_is_generated:
self._generate_role()
return self._role == Role.WORKER and self._current_id == 0 | [
"def",
"_is_first_worker",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_role_is_generated",
":",
"self",
".",
"_generate_role",
"(",
")",
"return",
"self",
".",
"_role",
"==",
"Role",
".",
"WORKER",
"and",
"self",
".",
"_current_id",
"==",
"0"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/base/role_maker.py#L609-L615 | |
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/tvm/contrib/graph_runtime.py | python | create | (graph_json_str, libmod, ctx) | return GraphModule(fcreate(graph_json_str, libmod, device_type, device_id), ctx) | Create a runtime executor module given a graph and module.
Parameters
----------
graph_json_str : str or graph class
The graph to be deployed in json format output by nnvm graph.
The graph can only contain one operator(tvm_op) that
points to the name of PackedFunc in the libmod.
libmod : tvm.Module
The module of the corresponding function
ctx : TVMContext
The context to deploy the module, can be local or remote.
Returns
-------
graph_module : GraphModule
Runtime graph module that can be used to execute the graph. | Create a runtime executor module given a graph and module. | [
"Create",
"a",
"runtime",
"executor",
"module",
"given",
"a",
"graph",
"and",
"module",
"."
] | def create(graph_json_str, libmod, ctx):
"""Create a runtime executor module given a graph and module.
Parameters
----------
graph_json_str : str or graph class
The graph to be deployed in json format output by nnvm graph.
The graph can only contain one operator(tvm_op) that
points to the name of PackedFunc in the libmod.
libmod : tvm.Module
The module of the corresponding function
ctx : TVMContext
The context to deploy the module, can be local or remote.
Returns
-------
graph_module : GraphModule
Runtime graph module that can be used to execute the graph.
"""
if not isinstance(graph_json_str, string_types):
try:
graph_json_str = graph_json_str._tvm_graph_json()
except AttributeError:
raise ValueError("Type %s is not supported" % type(graph_json_str))
device_type = ctx.device_type
device_id = ctx.device_id
if device_type >= rpc.RPC_SESS_MASK:
assert libmod.type_key == "rpc"
assert rpc._SessTableIndex(libmod) == ctx._rpc_sess._tbl_index
hmod = rpc._ModuleHandle(libmod)
fcreate = ctx._rpc_sess.get_function("tvm.graph_runtime.remote_create")
device_type = device_type % rpc.RPC_SESS_MASK
return GraphModule(fcreate(graph_json_str, hmod, device_type, device_id), ctx)
fcreate = get_global_func("tvm.graph_runtime.create")
return GraphModule(fcreate(graph_json_str, libmod, device_type, device_id), ctx) | [
"def",
"create",
"(",
"graph_json_str",
",",
"libmod",
",",
"ctx",
")",
":",
"if",
"not",
"isinstance",
"(",
"graph_json_str",
",",
"string_types",
")",
":",
"try",
":",
"graph_json_str",
"=",
"graph_json_str",
".",
"_tvm_graph_json",
"(",
")",
"except",
"At... | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/contrib/graph_runtime.py#L8-L44 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/mox3/mox3/mox.py | python | MockAnything.__eq__ | (self, rhs) | return (isinstance(rhs, MockAnything) and
self._replay_mode == rhs._replay_mode and
self._expected_calls_queue == rhs._expected_calls_queue) | Provide custom logic to compare objects. | Provide custom logic to compare objects. | [
"Provide",
"custom",
"logic",
"to",
"compare",
"objects",
"."
] | def __eq__(self, rhs):
"""Provide custom logic to compare objects."""
return (isinstance(rhs, MockAnything) and
self._replay_mode == rhs._replay_mode and
self._expected_calls_queue == rhs._expected_calls_queue) | [
"def",
"__eq__",
"(",
"self",
",",
"rhs",
")",
":",
"return",
"(",
"isinstance",
"(",
"rhs",
",",
"MockAnything",
")",
"and",
"self",
".",
"_replay_mode",
"==",
"rhs",
".",
"_replay_mode",
"and",
"self",
".",
"_expected_calls_queue",
"==",
"rhs",
".",
"_... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/mox3/mox3/mox.py#L509-L514 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/urllib.py | python | localhost | () | return _localhost | Return the IP address of the magic hostname 'localhost'. | Return the IP address of the magic hostname 'localhost'. | [
"Return",
"the",
"IP",
"address",
"of",
"the",
"magic",
"hostname",
"localhost",
"."
] | def localhost():
"""Return the IP address of the magic hostname 'localhost'."""
global _localhost
if _localhost is None:
_localhost = socket.gethostbyname('localhost')
return _localhost | [
"def",
"localhost",
"(",
")",
":",
"global",
"_localhost",
"if",
"_localhost",
"is",
"None",
":",
"_localhost",
"=",
"socket",
".",
"gethostbyname",
"(",
"'localhost'",
")",
"return",
"_localhost"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/urllib.py#L818-L823 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py | python | VSplit.walk | (self, cli) | Walk through children. | Walk through children. | [
"Walk",
"through",
"children",
"."
] | def walk(self, cli):
""" Walk through children. """
yield self
for c in self.children:
for i in c.walk(cli):
yield i | [
"def",
"walk",
"(",
"self",
",",
"cli",
")",
":",
"yield",
"self",
"for",
"c",
"in",
"self",
".",
"children",
":",
"for",
"i",
"in",
"c",
".",
"walk",
"(",
"cli",
")",
":",
"yield",
"i"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py#L351-L356 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/dashboard/services/access_control.py | python | ac_role_create_cmd | (_, rolename: str, description: Optional[str] = None) | Create a new access control role | Create a new access control role | [
"Create",
"a",
"new",
"access",
"control",
"role"
] | def ac_role_create_cmd(_, rolename: str, description: Optional[str] = None):
'''
Create a new access control role
'''
try:
role = mgr.ACCESS_CTRL_DB.create_role(rolename, description)
mgr.ACCESS_CTRL_DB.save()
return 0, json.dumps(role.to_dict()), ''
except RoleAlreadyExists as ex:
return -errno.EEXIST, '', str(ex) | [
"def",
"ac_role_create_cmd",
"(",
"_",
",",
"rolename",
":",
"str",
",",
"description",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"try",
":",
"role",
"=",
"mgr",
".",
"ACCESS_CTRL_DB",
".",
"create_role",
"(",
"rolename",
",",
"description... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/dashboard/services/access_control.py#L621-L630 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/py/py/_xmlgen.py | python | _escape.__call__ | (self, ustring) | return self.charef_rex.sub(self._replacer, ustring) | xml-escape the given unicode string. | xml-escape the given unicode string. | [
"xml",
"-",
"escape",
"the",
"given",
"unicode",
"string",
"."
] | def __call__(self, ustring):
""" xml-escape the given unicode string. """
try:
ustring = unicode(ustring)
except UnicodeDecodeError:
ustring = unicode(ustring, 'utf-8', errors='replace')
return self.charef_rex.sub(self._replacer, ustring) | [
"def",
"__call__",
"(",
"self",
",",
"ustring",
")",
":",
"try",
":",
"ustring",
"=",
"unicode",
"(",
"ustring",
")",
"except",
"UnicodeDecodeError",
":",
"ustring",
"=",
"unicode",
"(",
"ustring",
",",
"'utf-8'",
",",
"errors",
"=",
"'replace'",
")",
"r... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_xmlgen.py#L247-L253 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | GetEigenVectorCentr | (*args) | return _snap.GetEigenVectorCentr(*args) | GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4, int const & MaxIter=100)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
MaxIter: int const &
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH & | GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4, int const & MaxIter=100) | [
"GetEigenVectorCentr",
"(",
"PUNGraph",
"const",
"&",
"Graph",
"TIntFltH",
"&",
"NIdEigenH",
"double",
"const",
"&",
"Eps",
"=",
"1e",
"-",
"4",
"int",
"const",
"&",
"MaxIter",
"=",
"100",
")"
] | def GetEigenVectorCentr(*args):
"""
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4, int const & MaxIter=100)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
MaxIter: int const &
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
"""
return _snap.GetEigenVectorCentr(*args) | [
"def",
"GetEigenVectorCentr",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"GetEigenVectorCentr",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L626-L650 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/platform/benchmark.py | python | _rename_function | (f, arg_num, name) | return types.FunctionType(new_code, f.__globals__, name, f.__defaults__,
f.__closure__) | Rename the given function's name appears in the stack trace. | Rename the given function's name appears in the stack trace. | [
"Rename",
"the",
"given",
"function",
"s",
"name",
"appears",
"in",
"the",
"stack",
"trace",
"."
] | def _rename_function(f, arg_num, name):
"""Rename the given function's name appears in the stack trace."""
func_code = six.get_function_code(f)
if sys.version_info > (3, 8, 0, "alpha", 3):
# Python3.8 / PEP570 added co_posonlyargcount argument to CodeType.
new_code = types.CodeType(
arg_num, func_code.co_posonlyargcount, 0, func_code.co_nlocals,
func_code.co_stacksize, func_code.co_flags, func_code.co_code,
func_code.co_consts, func_code.co_names, func_code.co_varnames,
func_code.co_filename, name, func_code.co_firstlineno,
func_code.co_lnotab, func_code.co_freevars, func_code.co_cellvars)
else:
new_code = types.CodeType(arg_num, 0, func_code.co_nlocals,
func_code.co_stacksize, func_code.co_flags,
func_code.co_code, func_code.co_consts,
func_code.co_names, func_code.co_varnames,
func_code.co_filename, name,
func_code.co_firstlineno, func_code.co_lnotab,
func_code.co_freevars, func_code.co_cellvars)
return types.FunctionType(new_code, f.__globals__, name, f.__defaults__,
f.__closure__) | [
"def",
"_rename_function",
"(",
"f",
",",
"arg_num",
",",
"name",
")",
":",
"func_code",
"=",
"six",
".",
"get_function_code",
"(",
"f",
")",
"if",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"8",
",",
"0",
",",
"\"alpha\"",
",",
"3",
")",
":",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/platform/benchmark.py#L52-L73 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Misc.winfo_pointerxy | (self) | return self._getints(
self.tk.call('winfo', 'pointerxy', self._w)) | Return a tuple of x and y coordinates of the pointer on the root window. | Return a tuple of x and y coordinates of the pointer on the root window. | [
"Return",
"a",
"tuple",
"of",
"x",
"and",
"y",
"coordinates",
"of",
"the",
"pointer",
"on",
"the",
"root",
"window",
"."
] | def winfo_pointerxy(self):
"""Return a tuple of x and y coordinates of the pointer on the root window."""
return self._getints(
self.tk.call('winfo', 'pointerxy', self._w)) | [
"def",
"winfo_pointerxy",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'pointerxy'",
",",
"self",
".",
"_w",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1034-L1037 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/SaltRemover.py | python | SaltRemover.StripMol | (self, mol, dontRemoveEverything=False, sanitize=True) | return strippedMol.mol | >>> remover = SaltRemover(defnData="[Cl,Br]")
>>> len(remover.salts)
1
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl')
>>> res = remover.StripMol(mol)
>>> res is not None
True
>>> res.GetNumAtoms()
4
Notice that all salts are removed:
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl.Cl.Br')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Matching (e.g. "salt-like") atoms in the molecule are unchanged:
>>> mol = Chem.MolFromSmiles('CN(Br)Cl')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
>>> mol = Chem.MolFromSmiles('CN(Br)Cl.Cl')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Charged salts are handled reasonably:
>>> mol = Chem.MolFromSmiles('C[NH+](C)(C).[Cl-]')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Watch out for this case (everything removed):
>>> remover = SaltRemover()
>>> len(remover.salts)>1
True
>>> mol = Chem.MolFromSmiles('CC(=O)O.[Na]')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
0
dontRemoveEverything helps with this by leaving the last salt:
>>> res = remover.StripMol(mol,dontRemoveEverything=True)
>>> res.GetNumAtoms()
4
but in cases where the last salts are the same, it can't choose
between them, so it returns all of them:
>>> mol = Chem.MolFromSmiles('Cl.Cl')
>>> res = remover.StripMol(mol,dontRemoveEverything=True)
>>> res.GetNumAtoms()
2 | [] | def StripMol(self, mol, dontRemoveEverything=False, sanitize=True):
"""
>>> remover = SaltRemover(defnData="[Cl,Br]")
>>> len(remover.salts)
1
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl')
>>> res = remover.StripMol(mol)
>>> res is not None
True
>>> res.GetNumAtoms()
4
Notice that all salts are removed:
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl.Cl.Br')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Matching (e.g. "salt-like") atoms in the molecule are unchanged:
>>> mol = Chem.MolFromSmiles('CN(Br)Cl')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
>>> mol = Chem.MolFromSmiles('CN(Br)Cl.Cl')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Charged salts are handled reasonably:
>>> mol = Chem.MolFromSmiles('C[NH+](C)(C).[Cl-]')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Watch out for this case (everything removed):
>>> remover = SaltRemover()
>>> len(remover.salts)>1
True
>>> mol = Chem.MolFromSmiles('CC(=O)O.[Na]')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
0
dontRemoveEverything helps with this by leaving the last salt:
>>> res = remover.StripMol(mol,dontRemoveEverything=True)
>>> res.GetNumAtoms()
4
but in cases where the last salts are the same, it can't choose
between them, so it returns all of them:
>>> mol = Chem.MolFromSmiles('Cl.Cl')
>>> res = remover.StripMol(mol,dontRemoveEverything=True)
>>> res.GetNumAtoms()
2
"""
strippedMol = self._StripMol(mol, dontRemoveEverything, sanitize)
return strippedMol.mol | [
"def",
"StripMol",
"(",
"self",
",",
"mol",
",",
"dontRemoveEverything",
"=",
"False",
",",
"sanitize",
"=",
"True",
")",
":",
"strippedMol",
"=",
"self",
".",
"_StripMol",
"(",
"mol",
",",
"dontRemoveEverything",
",",
"sanitize",
")",
"return",
"strippedMol... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/SaltRemover.py#L145-L212 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/threading.py | python | Condition | (*args, **kwargs) | return _Condition(*args, **kwargs) | Factory function that returns a new condition variable object.
A condition variable allows one or more threads to wait until they are
notified by another thread.
If the lock argument is given and not None, it must be a Lock or RLock
object, and it is used as the underlying lock. Otherwise, a new RLock object
is created and used as the underlying lock. | Factory function that returns a new condition variable object. | [
"Factory",
"function",
"that",
"returns",
"a",
"new",
"condition",
"variable",
"object",
"."
] | def Condition(*args, **kwargs):
"""Factory function that returns a new condition variable object.
A condition variable allows one or more threads to wait until they are
notified by another thread.
If the lock argument is given and not None, it must be a Lock or RLock
object, and it is used as the underlying lock. Otherwise, a new RLock object
is created and used as the underlying lock.
"""
return _Condition(*args, **kwargs) | [
"def",
"Condition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_Condition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/threading.py#L241-L252 | |
envoyproxy/envoy | 65541accdafe255e72310b4298d646e091da2d80 | tools/protodoc/protodoc.py | python | format_header | (style, text) | return '%s\n%s\n\n' % (text, style * len(text)) | Format RST header.
Args:
style: underline style, e.g. '=', '-'.
text: header text
Returns:
RST formatted header. | Format RST header. | [
"Format",
"RST",
"header",
"."
] | def format_header(style, text):
"""Format RST header.
Args:
style: underline style, e.g. '=', '-'.
text: header text
Returns:
RST formatted header.
"""
return '%s\n%s\n\n' % (text, style * len(text)) | [
"def",
"format_header",
"(",
"style",
",",
"text",
")",
":",
"return",
"'%s\\n%s\\n\\n'",
"%",
"(",
"text",
",",
"style",
"*",
"len",
"(",
"text",
")",
")"
] | https://github.com/envoyproxy/envoy/blob/65541accdafe255e72310b4298d646e091da2d80/tools/protodoc/protodoc.py#L245-L255 | |
tomahawk-player/tomahawk-resolvers | 7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d | archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/text_format.py | python | _Tokenizer.ConsumeBool | (self) | Consumes a boolean value.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed. | Consumes a boolean value. | [
"Consumes",
"a",
"boolean",
"value",
"."
] | def ConsumeBool(self):
"""Consumes a boolean value.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
if self.token in ('true', 't', '1'):
self.NextToken()
return True
elif self.token in ('false', 'f', '0'):
self.NextToken()
return False
else:
raise self._ParseError('Expected "true" or "false".') | [
"def",
"ConsumeBool",
"(",
"self",
")",
":",
"if",
"self",
".",
"token",
"in",
"(",
"'true'",
",",
"'t'",
",",
"'1'",
")",
":",
"self",
".",
"NextToken",
"(",
")",
"return",
"True",
"elif",
"self",
".",
"token",
"in",
"(",
"'false'",
",",
"'f'",
... | https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/text_format.py#L514-L530 | ||
FirebirdSQL/firebird | 95e3e71622ab0b26cafa8b184ce08500f2eb613f | extern/re2/re2/make_unicode_groups.py | python | MakeRanges | (codes) | return ranges | Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]] | Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]] | [
"Turn",
"a",
"list",
"like",
"[",
"1",
"2",
"3",
"7",
"8",
"9",
"]",
"into",
"a",
"range",
"list",
"[[",
"1",
"3",
"]",
"[",
"7",
"9",
"]]"
] | def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges | [
"def",
"MakeRanges",
"(",
"codes",
")",
":",
"ranges",
"=",
"[",
"]",
"last",
"=",
"-",
"100",
"for",
"c",
"in",
"codes",
":",
"if",
"c",
"==",
"last",
"+",
"1",
":",
"ranges",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"=",
"c",
"else",
":",
"rang... | https://github.com/FirebirdSQL/firebird/blob/95e3e71622ab0b26cafa8b184ce08500f2eb613f/extern/re2/re2/make_unicode_groups.py#L34-L44 | |
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/ros_carla_bridge/rqt_carla_control/src/rqt_carla_control/rqt_carla_control.py | python | CarlaControlPlugin.carla_status_changed | (self, status) | callback whenever carla status changes | callback whenever carla status changes | [
"callback",
"whenever",
"carla",
"status",
"changes"
] | def carla_status_changed(self, status):
"""
callback whenever carla status changes
"""
self.carla_status = status
if status.synchronous_mode:
self._widget.pushButtonPlayPause.setDisabled(False)
self._widget.pushButtonStepOnce.setDisabled(False)
if status.synchronous_mode_running:
self._widget.pushButtonPlayPause.setIcon(self.pause_icon)
else:
self._widget.pushButtonPlayPause.setIcon(self.play_icon)
else:
self._widget.pushButtonPlayPause.setDisabled(True)
self._widget.pushButtonStepOnce.setDisabled(True) | [
"def",
"carla_status_changed",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"carla_status",
"=",
"status",
"if",
"status",
".",
"synchronous_mode",
":",
"self",
".",
"_widget",
".",
"pushButtonPlayPause",
".",
"setDisabled",
"(",
"False",
")",
"self",
... | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/rqt_carla_control/src/rqt_carla_control/rqt_carla_control.py#L85-L99 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/fixes/fix_urllib.py | python | FixUrllib.transform_dot | (self, node, results) | Transform for calls to module members in code. | Transform for calls to module members in code. | [
"Transform",
"for",
"calls",
"to",
"module",
"members",
"in",
"code",
"."
] | def transform_dot(self, node, results):
"""Transform for calls to module members in code."""
module_dot = results.get("bare_with_attr")
member = results.get("member")
new_name = None
if isinstance(member, list):
member = member[0]
for change in MAPPING[module_dot.value]:
if member.value in change[1]:
new_name = change[0]
break
if new_name:
module_dot.replace(Name(new_name,
prefix=module_dot.prefix))
else:
self.cannot_convert(node, "This is an invalid module element") | [
"def",
"transform_dot",
"(",
"self",
",",
"node",
",",
"results",
")",
":",
"module_dot",
"=",
"results",
".",
"get",
"(",
"\"bare_with_attr\"",
")",
"member",
"=",
"results",
".",
"get",
"(",
"\"member\"",
")",
"new_name",
"=",
"None",
"if",
"isinstance",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/fixes/fix_urllib.py#L168-L183 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/resources/ico_tools.py | python | ComputeANDMaskFromAlpha | (image_data, width, height) | return and_bytes | Compute an AND mask from 32-bit BGRA image data. | Compute an AND mask from 32-bit BGRA image data. | [
"Compute",
"an",
"AND",
"mask",
"from",
"32",
"-",
"bit",
"BGRA",
"image",
"data",
"."
] | def ComputeANDMaskFromAlpha(image_data, width, height):
"""Compute an AND mask from 32-bit BGRA image data."""
and_bytes = []
for y in range(height):
bit_count = 0
current_byte = 0
for x in range(width):
alpha = image_data[(y * width + x) * 4 + 3]
current_byte <<= 1
if ord(alpha) == 0:
current_byte |= 1
bit_count += 1
if bit_count == 8:
and_bytes.append(current_byte)
bit_count = 0
current_byte = 0
# At the end of a row, pad the current byte.
if bit_count > 0:
current_byte <<= (8 - bit_count)
and_bytes.append(current_byte)
# And keep padding until a multiple of 4 bytes.
while len(and_bytes) % 4 != 0:
and_bytes.append(0)
and_bytes = ''.join(map(chr, and_bytes))
return and_bytes | [
"def",
"ComputeANDMaskFromAlpha",
"(",
"image_data",
",",
"width",
",",
"height",
")",
":",
"and_bytes",
"=",
"[",
"]",
"for",
"y",
"in",
"range",
"(",
"height",
")",
":",
"bit_count",
"=",
"0",
"current_byte",
"=",
"0",
"for",
"x",
"in",
"range",
"(",... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/resources/ico_tools.py#L72-L98 | |
MirrorYuChen/ncnn_example | a42608e6e0e51ed68d3bd8ada853595980935220 | ncnn-20210525-full-source/python/ncnn/utils/download.py | python | check_sha1 | (filename, sha1_hash) | return sha1.hexdigest()[0:l] == sha1_hash[0:l] | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash. | Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash. | [
"Check",
"whether",
"the",
"sha1",
"hash",
"of",
"the",
"file",
"content",
"matches",
"the",
"expected",
"hash",
".",
"Parameters",
"----------",
"filename",
":",
"str",
"Path",
"to",
"the",
"file",
".",
"sha1_hash",
":",
"str",
"Expected",
"sha1",
"hash",
... | def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash.
"""
sha1 = hashlib.sha1()
with open(filename, "rb") as f:
while True:
data = f.read(1048576)
if not data:
break
sha1.update(data)
sha1_file = sha1.hexdigest()
l = min(len(sha1_file), len(sha1_hash))
return sha1.hexdigest()[0:l] == sha1_hash[0:l] | [
"def",
"check_sha1",
"(",
"filename",
",",
"sha1_hash",
")",
":",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"while",
"True",
":",
"data",
"=",
"f",
".",
"read",
"(",
"1048576... | https://github.com/MirrorYuChen/ncnn_example/blob/a42608e6e0e51ed68d3bd8ada853595980935220/ncnn-20210525-full-source/python/ncnn/utils/download.py#L23-L46 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | AnyButton.SetBitmapFocus | (*args, **kwargs) | return _controls_.AnyButton_SetBitmapFocus(*args, **kwargs) | SetBitmapFocus(self, Bitmap bitmap) | SetBitmapFocus(self, Bitmap bitmap) | [
"SetBitmapFocus",
"(",
"self",
"Bitmap",
"bitmap",
")"
] | def SetBitmapFocus(*args, **kwargs):
"""SetBitmapFocus(self, Bitmap bitmap)"""
return _controls_.AnyButton_SetBitmapFocus(*args, **kwargs) | [
"def",
"SetBitmapFocus",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"AnyButton_SetBitmapFocus",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L96-L98 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/sliceshell.py | python | SlicesShell.redirectStdin | (self, redirect=True) | If redirect is true then sys.stdin will come from the shell. | If redirect is true then sys.stdin will come from the shell. | [
"If",
"redirect",
"is",
"true",
"then",
"sys",
".",
"stdin",
"will",
"come",
"from",
"the",
"shell",
"."
] | def redirectStdin(self, redirect=True):
"""If redirect is true then sys.stdin will come from the shell."""
if redirect:
sys.stdin = self.reader
else:
sys.stdin = self.stdin | [
"def",
"redirectStdin",
"(",
"self",
",",
"redirect",
"=",
"True",
")",
":",
"if",
"redirect",
":",
"sys",
".",
"stdin",
"=",
"self",
".",
"reader",
"else",
":",
"sys",
".",
"stdin",
"=",
"self",
".",
"stdin"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/sliceshell.py#L3152-L3157 | ||
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | cpp/gdb_arrow.py | python | Buffer.bytes_view | (self, offset=0, length=None) | return mem.cast('B') | Return a view over the bytes of this buffer. | Return a view over the bytes of this buffer. | [
"Return",
"a",
"view",
"over",
"the",
"bytes",
"of",
"this",
"buffer",
"."
] | def bytes_view(self, offset=0, length=None):
"""
Return a view over the bytes of this buffer.
"""
if self.size > 0:
if length is None:
length = self.size
mem = gdb.selected_inferior().read_memory(
self.val['data_'] + offset, self.size)
else:
mem = memoryview(b"")
# Read individual bytes as unsigned integers rather than
# Python bytes objects
return mem.cast('B') | [
"def",
"bytes_view",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"length",
"=",
"None",
")",
":",
"if",
"self",
".",
"size",
">",
"0",
":",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"self",
".",
"size",
"mem",
"=",
"gdb",
".",
"selected_in... | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/cpp/gdb_arrow.py#L609-L622 | |
baoboa/pyqt5 | 11d5f43bc6f213d9d60272f3954a0048569cfc7c | configure.py | python | check_qt | (target_config) | Check the Qt installation. target_config is the target configuration. | Check the Qt installation. target_config is the target configuration. | [
"Check",
"the",
"Qt",
"installation",
".",
"target_config",
"is",
"the",
"target",
"configuration",
"."
] | def check_qt(target_config):
""" Check the Qt installation. target_config is the target configuration.
"""
# Starting with v4.7, Qt (when built with MinGW) assumes that stack frames
# are 16 byte aligned because it uses SSE. However the Python Windows
# installers are built with 4 byte aligned stack frames. We therefore need
# to tweak the g++ flags to deal with it.
if target_config.qmake_spec == 'win32-g++':
target_config.qmake_variables.append('QMAKE_CFLAGS += -mstackrealign')
target_config.qmake_variables.append('QMAKE_CXXFLAGS += -mstackrealign') | [
"def",
"check_qt",
"(",
"target_config",
")",
":",
"# Starting with v4.7, Qt (when built with MinGW) assumes that stack frames",
"# are 16 byte aligned because it uses SSE. However the Python Windows",
"# installers are built with 4 byte aligned stack frames. We therefore need",
"# to tweak the ... | https://github.com/baoboa/pyqt5/blob/11d5f43bc6f213d9d60272f3954a0048569cfc7c/configure.py#L2812-L2822 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/distributions/python/ops/quantized_distribution.py | python | QuantizedDistribution.distribution | (self) | return self._dist | Base distribution, p(x). | Base distribution, p(x). | [
"Base",
"distribution",
"p",
"(",
"x",
")",
"."
] | def distribution(self):
"""Base distribution, p(x)."""
return self._dist | [
"def",
"distribution",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dist"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/quantized_distribution.py#L507-L509 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/stats.py | python | _sum_of_squares | (a, axis=0) | return np.sum(a*a, axis) | Squares each element of the input array, and returns the sum(s) of that.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
sum_of_squares : ndarray
The sum along the given axis for (a**2).
See also
--------
_square_of_sums : The square(s) of the sum(s) (the opposite of
`_sum_of_squares`). | Squares each element of the input array, and returns the sum(s) of that. | [
"Squares",
"each",
"element",
"of",
"the",
"input",
"array",
"and",
"returns",
"the",
"sum",
"(",
"s",
")",
"of",
"that",
"."
] | def _sum_of_squares(a, axis=0):
"""
Squares each element of the input array, and returns the sum(s) of that.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
sum_of_squares : ndarray
The sum along the given axis for (a**2).
See also
--------
_square_of_sums : The square(s) of the sum(s) (the opposite of
`_sum_of_squares`).
"""
a, axis = _chk_asarray(a, axis)
return np.sum(a*a, axis) | [
"def",
"_sum_of_squares",
"(",
"a",
",",
"axis",
"=",
"0",
")",
":",
"a",
",",
"axis",
"=",
"_chk_asarray",
"(",
"a",
",",
"axis",
")",
"return",
"np",
".",
"sum",
"(",
"a",
"*",
"a",
",",
"axis",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/stats.py#L5222-L5245 | |
AndroidAdvanceWithGeektime/Chapter01 | da2bc56d708fa74035c64564b134189045f51213 | breakpad-build/src/main/cpp/external/libbreakpad/src/tools/python/filter_syms.py | python | SymbolFileParser._IsLineRecord | (self, record_type) | return True | Determines if the current record type is a Line record | Determines if the current record type is a Line record | [
"Determines",
"if",
"the",
"current",
"record",
"type",
"is",
"a",
"Line",
"record"
] | def _IsLineRecord(self, record_type):
"""Determines if the current record type is a Line record"""
try:
line = int(record_type, 16)
except (ValueError, TypeError):
return False
return True | [
"def",
"_IsLineRecord",
"(",
"self",
",",
"record_type",
")",
":",
"try",
":",
"line",
"=",
"int",
"(",
"record_type",
",",
"16",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/AndroidAdvanceWithGeektime/Chapter01/blob/da2bc56d708fa74035c64564b134189045f51213/breakpad-build/src/main/cpp/external/libbreakpad/src/tools/python/filter_syms.py#L155-L161 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/photos/service.py | python | PhotosService.SearchUserPhotos | (self, query, user='default', limit=100) | return self.GetFeed(uri, limit=limit) | Search through all photos for a specific user and return a feed.
This will look for matches in file names and image tags (a.k.a. keywords)
Arguments:
query: The string you're looking for, e.g. `vacation'
user (optional): The username of whose photos you want to search, defaults
to current user.
limit (optional): Don't return more than `limit' hits, defaults to 100
Only public photos are searched, unless you are authenticated and
searching through your own photos.
Returns:
gdata.photos.UserFeed with PhotoEntry elements | Search through all photos for a specific user and return a feed.
This will look for matches in file names and image tags (a.k.a. keywords) | [
"Search",
"through",
"all",
"photos",
"for",
"a",
"specific",
"user",
"and",
"return",
"a",
"feed",
".",
"This",
"will",
"look",
"for",
"matches",
"in",
"file",
"names",
"and",
"image",
"tags",
"(",
"a",
".",
"k",
".",
"a",
".",
"keywords",
")"
] | def SearchUserPhotos(self, query, user='default', limit=100):
"""Search through all photos for a specific user and return a feed.
This will look for matches in file names and image tags (a.k.a. keywords)
Arguments:
query: The string you're looking for, e.g. `vacation'
user (optional): The username of whose photos you want to search, defaults
to current user.
limit (optional): Don't return more than `limit' hits, defaults to 100
Only public photos are searched, unless you are authenticated and
searching through your own photos.
Returns:
gdata.photos.UserFeed with PhotoEntry elements
"""
uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query)
return self.GetFeed(uri, limit=limit) | [
"def",
"SearchUserPhotos",
"(",
"self",
",",
"query",
",",
"user",
"=",
"'default'",
",",
"limit",
"=",
"100",
")",
":",
"uri",
"=",
"'/data/feed/api/user/%s?kind=photo&q=%s'",
"%",
"(",
"user",
",",
"query",
")",
"return",
"self",
".",
"GetFeed",
"(",
"ur... | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/photos/service.py#L254-L271 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/experiment.py | python | Experiment.train | (self, delay_secs=None) | return self._call_train(input_fn=self._train_input_fn,
max_steps=self._train_steps,
hooks=self._train_monitors + extra_hooks) | Fit the estimator using the training data.
Train the estimator for `self._train_steps` steps, after waiting for
`delay_secs` seconds. If `self._train_steps` is `None`, train forever.
Args:
delay_secs: Start training after this many seconds.
Returns:
The trained estimator. | Fit the estimator using the training data. | [
"Fit",
"the",
"estimator",
"using",
"the",
"training",
"data",
"."
] | def train(self, delay_secs=None):
"""Fit the estimator using the training data.
Train the estimator for `self._train_steps` steps, after waiting for
`delay_secs` seconds. If `self._train_steps` is `None`, train forever.
Args:
delay_secs: Start training after this many seconds.
Returns:
The trained estimator.
"""
start = time.time()
# Start the server, if needed. It's important to start the server before
# we (optionally) sleep for the case where no device_filters are set.
# Otherwise, the servers will wait to connect to each other before starting
# to train. We might as well start as soon as we can.
config = self._estimator.config
if (config.cluster_spec and config.master and
config.environment == run_config.Environment.LOCAL):
logging.warn("ClusterSpec and master are provided, but environment is "
"set to 'local'. Set environment to 'cloud' if you intend "
"to use the distributed runtime.")
if (config.environment != run_config.Environment.LOCAL and
config.environment != run_config.Environment.GOOGLE and
config.cluster_spec and config.master):
self._start_server()
extra_hooks = []
if delay_secs is None:
task_id = self._estimator.config.task_id or 0
if self._delay_workers_by_global_step:
# Wait 5500 global steps for the second worker. Each worker waits more
# then previous one but with a diminishing number of steps.
extra_hooks.append(
basic_session_run_hooks.GlobalStepWaiterHook(
int(8000.0 * math.log(task_id + 1))))
delay_secs = 0
else:
# Wait 5 secs more for each new worker up to 60 secs.
delay_secs = min(60, task_id * 5)
if delay_secs > 0:
elapsed_secs = time.time() - start
remaining = delay_secs - elapsed_secs
logging.info("Waiting %d secs before starting training.", remaining)
time.sleep(delay_secs)
return self._call_train(input_fn=self._train_input_fn,
max_steps=self._train_steps,
hooks=self._train_monitors + extra_hooks) | [
"def",
"train",
"(",
"self",
",",
"delay_secs",
"=",
"None",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"# Start the server, if needed. It's important to start the server before",
"# we (optionally) sleep for the case where no device_filters are set.",
"# Otherwise,... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/experiment.py#L229-L280 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | TypeHandler.WriteGLES2InterfaceStub | (self, func, f) | Writes the GLES2 Interface stub declaration. | Writes the GLES2 Interface stub declaration. | [
"Writes",
"the",
"GLES2",
"Interface",
"stub",
"declaration",
"."
] | def WriteGLES2InterfaceStub(self, func, f):
"""Writes the GLES2 Interface stub declaration."""
f.write("%s %s(%s) override;\n" %
(func.return_type, func.original_name,
func.MakeTypedOriginalArgString(""))) | [
"def",
"WriteGLES2InterfaceStub",
"(",
"self",
",",
"func",
",",
"f",
")",
":",
"f",
".",
"write",
"(",
"\"%s %s(%s) override;\\n\"",
"%",
"(",
"func",
".",
"return_type",
",",
"func",
".",
"original_name",
",",
"func",
".",
"MakeTypedOriginalArgString",
"(",
... | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L5297-L5301 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Tool/packaging/msi.py | python | convert_to_id | (s, id_set) | Some parts of .wxs need an Id attribute (for example: The File and
Directory directives. The charset is limited to A-Z, a-z, digits,
underscores, periods. Each Id must begin with a letter or with a
underscore. Google for "CNDL0015" for information about this.
Requirements:
* the string created must only contain chars from the target charset.
* the string created must have a minimal editing distance from the
original string.
* the string created must be unique for the whole .wxs file.
Observation:
* There are 62 chars in the charset.
Idea:
* filter out forbidden characters. Check for a collision with the help
of the id_set. Add the number of the number of the collision at the
end of the created string. Furthermore care for a correct start of
the string. | Some parts of .wxs need an Id attribute (for example: The File and
Directory directives. The charset is limited to A-Z, a-z, digits,
underscores, periods. Each Id must begin with a letter or with a
underscore. Google for "CNDL0015" for information about this. | [
"Some",
"parts",
"of",
".",
"wxs",
"need",
"an",
"Id",
"attribute",
"(",
"for",
"example",
":",
"The",
"File",
"and",
"Directory",
"directives",
".",
"The",
"charset",
"is",
"limited",
"to",
"A",
"-",
"Z",
"a",
"-",
"z",
"digits",
"underscores",
"perio... | def convert_to_id(s, id_set):
""" Some parts of .wxs need an Id attribute (for example: The File and
Directory directives. The charset is limited to A-Z, a-z, digits,
underscores, periods. Each Id must begin with a letter or with a
underscore. Google for "CNDL0015" for information about this.
Requirements:
* the string created must only contain chars from the target charset.
* the string created must have a minimal editing distance from the
original string.
* the string created must be unique for the whole .wxs file.
Observation:
* There are 62 chars in the charset.
Idea:
* filter out forbidden characters. Check for a collision with the help
of the id_set. Add the number of the number of the collision at the
end of the created string. Furthermore care for a correct start of
the string.
"""
charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.'
if s[0] in '0123456789.':
s = '_' + s
id = ''.join([c for c in s if c in charset])
# did we already generate an id for this file?
try:
return id_set[id][s]
except KeyError:
# no we did not, so initialize with the id
if id not in id_set: id_set[id] = { s : id }
# there is a collision, generate an id which is unique by appending
# the collision number
else: id_set[id][s] = id + str(len(id_set[id]))
return id_set[id][s] | [
"def",
"convert_to_id",
"(",
"s",
",",
"id_set",
")",
":",
"charset",
"=",
"'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.'",
"if",
"s",
"[",
"0",
"]",
"in",
"'0123456789.'",
":",
"s",
"=",
"'_'",
"+",
"s",
"id",
"=",
"''",
".",
"join",
"("... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/packaging/msi.py#L43-L79 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | FontPickerEvent.GetFont | (*args, **kwargs) | return _controls_.FontPickerEvent_GetFont(*args, **kwargs) | GetFont(self) -> Font | GetFont(self) -> Font | [
"GetFont",
"(",
"self",
")",
"-",
">",
"Font"
] | def GetFont(*args, **kwargs):
"""GetFont(self) -> Font"""
return _controls_.FontPickerEvent_GetFont(*args, **kwargs) | [
"def",
"GetFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"FontPickerEvent_GetFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L7204-L7206 | |
YosysHQ/nextpnr | 74c99f9195eeb47d106ca74b7abb894cfd47cc03 | 3rdparty/pybind11/pybind11/setup_helpers.py | python | no_recompile | (obg, src) | return True | This is the safest but slowest choice (and is the default) - will always
recompile sources. | This is the safest but slowest choice (and is the default) - will always
recompile sources. | [
"This",
"is",
"the",
"safest",
"but",
"slowest",
"choice",
"(",
"and",
"is",
"the",
"default",
")",
"-",
"will",
"always",
"recompile",
"sources",
"."
] | def no_recompile(obg, src):
"""
This is the safest but slowest choice (and is the default) - will always
recompile sources.
"""
return True | [
"def",
"no_recompile",
"(",
"obg",
",",
"src",
")",
":",
"return",
"True"
] | https://github.com/YosysHQ/nextpnr/blob/74c99f9195eeb47d106ca74b7abb894cfd47cc03/3rdparty/pybind11/pybind11/setup_helpers.py#L306-L311 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/manager.py | python | TransferConfig.__init__ | (self,
multipart_threshold=8 * MB,
multipart_chunksize=8 * MB,
max_request_concurrency=10,
max_submission_concurrency=5,
max_request_queue_size=1000,
max_submission_queue_size=1000,
max_io_queue_size=1000,
io_chunksize=256 * KB,
num_download_attempts=5,
max_in_memory_upload_chunks=10,
max_in_memory_download_chunks=10,
max_bandwidth=None) | Configurations for the transfer mangager
:param multipart_threshold: The threshold for which multipart
transfers occur.
:param max_request_concurrency: The maximum number of S3 API
transfer-related requests that can happen at a time.
:param max_submission_concurrency: The maximum number of threads
processing a call to a TransferManager method. Processing a
call usually entails determining which S3 API requests that need
to be enqueued, but does **not** entail making any of the
S3 API data transfering requests needed to perform the transfer.
The threads controlled by ``max_request_concurrency`` is
responsible for that.
:param multipart_chunksize: The size of each transfer if a request
becomes a multipart transfer.
:param max_request_queue_size: The maximum amount of S3 API requests
that can be queued at a time. A value of zero means that there
is no maximum.
:param max_submission_queue_size: The maximum amount of
TransferManager method calls that can be queued at a time. A value
of zero means that there is no maximum.
:param max_io_queue_size: The maximum amount of read parts that
can be queued to be written to disk per download. A value of zero
means that there is no maximum. The default size for each element
in this queue is 8 KB.
:param io_chunksize: The max size of each chunk in the io queue.
Currently, this is size used when reading from the downloaded
stream as well.
:param num_download_attempts: The number of download attempts that
will be tried upon errors with downloading an object in S3. Note
that these retries account for errors that occur when streamming
down the data from s3 (i.e. socket errors and read timeouts that
occur after recieving an OK response from s3).
Other retryable exceptions such as throttling errors and 5xx errors
are already retried by botocore (this default is 5). The
``num_download_attempts`` does not take into account the
number of exceptions retried by botocore.
:param max_in_memory_upload_chunks: The number of chunks that can
be stored in memory at a time for all ongoing upload requests.
This pertains to chunks of data that need to be stored in memory
during an upload if the data is sourced from a file-like object.
The total maximum memory footprint due to a in-memory upload
chunks is roughly equal to:
max_in_memory_upload_chunks * multipart_chunksize
+ max_submission_concurrency * multipart_chunksize
``max_submission_concurrency`` has an affect on this value because
for each thread pulling data off of a file-like object, they may
be waiting with a single read chunk to be submitted for upload
because the ``max_in_memory_upload_chunks`` value has been reached
by the threads making the upload request.
:param max_in_memory_download_chunks: The number of chunks that can
be buffered in memory and **not** in the io queue at a time for all
ongoing dowload requests. This pertains specifically to file-like
objects that cannot be seeked. The total maximum memory footprint
due to a in-memory download chunks is roughly equal to:
max_in_memory_download_chunks * multipart_chunksize
:param max_bandwidth: The maximum bandwidth that will be consumed
in uploading and downloading file content. The value is in terms of
bytes per second. | Configurations for the transfer mangager | [
"Configurations",
"for",
"the",
"transfer",
"mangager"
] | def __init__(self,
multipart_threshold=8 * MB,
multipart_chunksize=8 * MB,
max_request_concurrency=10,
max_submission_concurrency=5,
max_request_queue_size=1000,
max_submission_queue_size=1000,
max_io_queue_size=1000,
io_chunksize=256 * KB,
num_download_attempts=5,
max_in_memory_upload_chunks=10,
max_in_memory_download_chunks=10,
max_bandwidth=None):
"""Configurations for the transfer mangager
:param multipart_threshold: The threshold for which multipart
transfers occur.
:param max_request_concurrency: The maximum number of S3 API
transfer-related requests that can happen at a time.
:param max_submission_concurrency: The maximum number of threads
processing a call to a TransferManager method. Processing a
call usually entails determining which S3 API requests that need
to be enqueued, but does **not** entail making any of the
S3 API data transfering requests needed to perform the transfer.
The threads controlled by ``max_request_concurrency`` is
responsible for that.
:param multipart_chunksize: The size of each transfer if a request
becomes a multipart transfer.
:param max_request_queue_size: The maximum amount of S3 API requests
that can be queued at a time. A value of zero means that there
is no maximum.
:param max_submission_queue_size: The maximum amount of
TransferManager method calls that can be queued at a time. A value
of zero means that there is no maximum.
:param max_io_queue_size: The maximum amount of read parts that
can be queued to be written to disk per download. A value of zero
means that there is no maximum. The default size for each element
in this queue is 8 KB.
:param io_chunksize: The max size of each chunk in the io queue.
Currently, this is size used when reading from the downloaded
stream as well.
:param num_download_attempts: The number of download attempts that
will be tried upon errors with downloading an object in S3. Note
that these retries account for errors that occur when streamming
down the data from s3 (i.e. socket errors and read timeouts that
occur after recieving an OK response from s3).
Other retryable exceptions such as throttling errors and 5xx errors
are already retried by botocore (this default is 5). The
``num_download_attempts`` does not take into account the
number of exceptions retried by botocore.
:param max_in_memory_upload_chunks: The number of chunks that can
be stored in memory at a time for all ongoing upload requests.
This pertains to chunks of data that need to be stored in memory
during an upload if the data is sourced from a file-like object.
The total maximum memory footprint due to a in-memory upload
chunks is roughly equal to:
max_in_memory_upload_chunks * multipart_chunksize
+ max_submission_concurrency * multipart_chunksize
``max_submission_concurrency`` has an affect on this value because
for each thread pulling data off of a file-like object, they may
be waiting with a single read chunk to be submitted for upload
because the ``max_in_memory_upload_chunks`` value has been reached
by the threads making the upload request.
:param max_in_memory_download_chunks: The number of chunks that can
be buffered in memory and **not** in the io queue at a time for all
ongoing dowload requests. This pertains specifically to file-like
objects that cannot be seeked. The total maximum memory footprint
due to a in-memory download chunks is roughly equal to:
max_in_memory_download_chunks * multipart_chunksize
:param max_bandwidth: The maximum bandwidth that will be consumed
in uploading and downloading file content. The value is in terms of
bytes per second.
"""
self.multipart_threshold = multipart_threshold
self.multipart_chunksize = multipart_chunksize
self.max_request_concurrency = max_request_concurrency
self.max_submission_concurrency = max_submission_concurrency
self.max_request_queue_size = max_request_queue_size
self.max_submission_queue_size = max_submission_queue_size
self.max_io_queue_size = max_io_queue_size
self.io_chunksize = io_chunksize
self.num_download_attempts = num_download_attempts
self.max_in_memory_upload_chunks = max_in_memory_upload_chunks
self.max_in_memory_download_chunks = max_in_memory_download_chunks
self.max_bandwidth = max_bandwidth
self._validate_attrs_are_nonzero() | [
"def",
"__init__",
"(",
"self",
",",
"multipart_threshold",
"=",
"8",
"*",
"MB",
",",
"multipart_chunksize",
"=",
"8",
"*",
"MB",
",",
"max_request_concurrency",
"=",
"10",
",",
"max_submission_concurrency",
"=",
"5",
",",
"max_request_queue_size",
"=",
"1000",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/manager.py#L48-L147 | ||
ros-planning/navigation2 | 70e7948afb45350e45c96b683518c1e6ba3f6010 | nav2_simple_commander/nav2_simple_commander/robot_navigator.py | python | BasicNavigator.getFeedback | (self) | return self.feedback | Get the pending action feedback message. | Get the pending action feedback message. | [
"Get",
"the",
"pending",
"action",
"feedback",
"message",
"."
] | def getFeedback(self):
"""Get the pending action feedback message."""
return self.feedback | [
"def",
"getFeedback",
"(",
"self",
")",
":",
"return",
"self",
".",
"feedback"
] | https://github.com/ros-planning/navigation2/blob/70e7948afb45350e45c96b683518c1e6ba3f6010/nav2_simple_commander/nav2_simple_commander/robot_navigator.py#L253-L255 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/examples/value_iteration.py | python | play_tic_tac_toe | () | Solves tic tac toe. | Solves tic tac toe. | [
"Solves",
"tic",
"tac",
"toe",
"."
] | def play_tic_tac_toe():
"""Solves tic tac toe."""
game = pyspiel.load_game("tic_tac_toe")
print("Solving the game; depth_limit = {}".format(-1))
values = value_iteration.value_iteration(game, -1, 0.01)
for state, value in values.items():
print("")
print(str(state))
print("Value = {}".format(value))
initial_state = "...\n...\n..."
cross_win_state = "...\n...\n.ox"
naught_win_state = "x..\noo.\nxx."
assert values[initial_state] == 0, "State should be drawn: \n" + initial_state
assert values[cross_win_state] == 1, ("State should be won by player 0: \n" +
cross_win_state)
assert values[naught_win_state] == -1, (
"State should be won by player 1: \n" + cross_win_state) | [
"def",
"play_tic_tac_toe",
"(",
")",
":",
"game",
"=",
"pyspiel",
".",
"load_game",
"(",
"\"tic_tac_toe\"",
")",
"print",
"(",
"\"Solving the game; depth_limit = {}\"",
".",
"format",
"(",
"-",
"1",
")",
")",
"values",
"=",
"value_iteration",
".",
"value_iterati... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/examples/value_iteration.py#L31-L51 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/msvc.py | python | PlatformInfo.current_is_x86 | (self) | return self.current_cpu == 'x86' | Return True if current CPU is x86 32 bits..
Return
------
bool
CPU is x86 32 bits | Return True if current CPU is x86 32 bits.. | [
"Return",
"True",
"if",
"current",
"CPU",
"is",
"x86",
"32",
"bits",
".."
] | def current_is_x86(self):
"""
Return True if current CPU is x86 32 bits..
Return
------
bool
CPU is x86 32 bits
"""
return self.current_cpu == 'x86' | [
"def",
"current_is_x86",
"(",
"self",
")",
":",
"return",
"self",
".",
"current_cpu",
"==",
"'x86'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/msvc.py#L406-L415 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/imaplib.py | python | IMAP4.shutdown | (self) | Close I/O established in "open". | Close I/O established in "open". | [
"Close",
"I",
"/",
"O",
"established",
"in",
"open",
"."
] | def shutdown(self):
"""Close I/O established in "open"."""
self.file.close()
try:
self.sock.shutdown(socket.SHUT_RDWR)
except socket.error as e:
# The server might already have closed the connection.
# On Windows, this may result in WSAEINVAL (error 10022):
# An invalid operation was attempted.
if e.errno not in (errno.ENOTCONN, 10022):
raise
finally:
self.sock.close() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"file",
".",
"close",
"(",
")",
"try",
":",
"self",
".",
"sock",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"# The server might already... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/imaplib.py#L262-L274 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/httplib.py | python | HTTPConnection._send_output | (self, message_body=None) | Send the currently buffered request and clear the buffer.
Appends an extra \\r\\n to the buffer.
A message_body may be specified, to be appended to the request. | Send the currently buffered request and clear the buffer. | [
"Send",
"the",
"currently",
"buffered",
"request",
"and",
"clear",
"the",
"buffer",
"."
] | def _send_output(self, message_body=None):
"""Send the currently buffered request and clear the buffer.
Appends an extra \\r\\n to the buffer.
A message_body may be specified, to be appended to the request.
"""
self._buffer.extend(("", ""))
msg = "\r\n".join(self._buffer)
del self._buffer[:]
# If msg and message_body are sent in a single send() call,
# it will avoid performance problems caused by the interaction
# between delayed ack and the Nagle algorithm.
if isinstance(message_body, str):
msg += message_body
message_body = None
self.send(msg)
if message_body is not None:
#message_body was not a string (i.e. it is a file) and
#we must run the risk of Nagle
self.send(message_body) | [
"def",
"_send_output",
"(",
"self",
",",
"message_body",
"=",
"None",
")",
":",
"self",
".",
"_buffer",
".",
"extend",
"(",
"(",
"\"\"",
",",
"\"\"",
")",
")",
"msg",
"=",
"\"\\r\\n\"",
".",
"join",
"(",
"self",
".",
"_buffer",
")",
"del",
"self",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/httplib.py#L814-L833 | ||
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/utils/pyparsing.py | python | ParserElement.setDebugActions | (self, startAction, successAction, exceptionAction) | return self | Enable display of debugging messages while doing pattern matching. | Enable display of debugging messages while doing pattern matching. | [
"Enable",
"display",
"of",
"debugging",
"messages",
"while",
"doing",
"pattern",
"matching",
"."
] | def setDebugActions(self, startAction, successAction, exceptionAction):
"""Enable display of debugging messages while doing pattern matching."""
self.debugActions = (
startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction,
)
self.debug = True
return self | [
"def",
"setDebugActions",
"(",
"self",
",",
"startAction",
",",
"successAction",
",",
"exceptionAction",
")",
":",
"self",
".",
"debugActions",
"=",
"(",
"startAction",
"or",
"_defaultStartDebugAction",
",",
"successAction",
"or",
"_defaultSuccessDebugAction",
",",
... | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/utils/pyparsing.py#L1121-L1129 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/s3fs/core.py | python | S3FileSystem.getxattr | (self, path, attr_name, **kwargs) | return None | Get an attribute from the metadata.
Examples
--------
>>> mys3fs.getxattr('mykey', 'attribute_1') # doctest: +SKIP
'value_1' | Get an attribute from the metadata. | [
"Get",
"an",
"attribute",
"from",
"the",
"metadata",
"."
] | def getxattr(self, path, attr_name, **kwargs):
""" Get an attribute from the metadata.
Examples
--------
>>> mys3fs.getxattr('mykey', 'attribute_1') # doctest: +SKIP
'value_1'
"""
xattr = self.metadata(path, **kwargs)
if attr_name in xattr:
return xattr[attr_name]
return None | [
"def",
"getxattr",
"(",
"self",
",",
"path",
",",
"attr_name",
",",
"*",
"*",
"kwargs",
")",
":",
"xattr",
"=",
"self",
".",
"metadata",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
"if",
"attr_name",
"in",
"xattr",
":",
"return",
"xattr",
"[",
"attr... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/s3fs/core.py#L719-L730 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/plotting/_matplotlib/converter.py | python | TimeSeries_DateLocator.__call__ | (self) | return locs | Return the locations of the ticks. | Return the locations of the ticks. | [
"Return",
"the",
"locations",
"of",
"the",
"ticks",
"."
] | def __call__(self):
"Return the locations of the ticks."
# axis calls Locator.set_axis inside set_m<xxxx>_formatter
vi = tuple(self.axis.get_view_interval())
if vi != self.plot_obj.view_interval:
self.plot_obj.date_axis_info = None
self.plot_obj.view_interval = vi
vmin, vmax = vi
if vmax < vmin:
vmin, vmax = vmax, vmin
if self.isdynamic:
locs = self._get_default_locs(vmin, vmax)
else: # pragma: no cover
base = self.base
(d, m) = divmod(vmin, base)
vmin = (d + 1) * base
locs = list(range(vmin, vmax + 1, base))
return locs | [
"def",
"__call__",
"(",
"self",
")",
":",
"# axis calls Locator.set_axis inside set_m<xxxx>_formatter",
"vi",
"=",
"tuple",
"(",
"self",
".",
"axis",
".",
"get_view_interval",
"(",
")",
")",
"if",
"vi",
"!=",
"self",
".",
"plot_obj",
".",
"view_interval",
":",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/plotting/_matplotlib/converter.py#L996-L1014 | |
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/util/utility.py | python | replace_suffix | (name, new_suffix) | return split [0] + new_suffix | Replaces the suffix of name by new_suffix.
If no suffix exists, the new one is added. | Replaces the suffix of name by new_suffix.
If no suffix exists, the new one is added. | [
"Replaces",
"the",
"suffix",
"of",
"name",
"by",
"new_suffix",
".",
"If",
"no",
"suffix",
"exists",
"the",
"new",
"one",
"is",
"added",
"."
] | def replace_suffix (name, new_suffix):
""" Replaces the suffix of name by new_suffix.
If no suffix exists, the new one is added.
"""
assert isinstance(name, basestring)
assert isinstance(new_suffix, basestring)
split = os.path.splitext (name)
return split [0] + new_suffix | [
"def",
"replace_suffix",
"(",
"name",
",",
"new_suffix",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"new_suffix",
",",
"basestring",
")",
"split",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name"... | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/util/utility.py#L114-L121 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/awsrequest.py | python | AWSResponse.text | (self) | Content of the response as a proper text type.
Uses the encoding type provided in the reponse headers to decode the
response content into a proper text type. If the encoding is not
present in the headers, UTF-8 is used as a default. | Content of the response as a proper text type. | [
"Content",
"of",
"the",
"response",
"as",
"a",
"proper",
"text",
"type",
"."
] | def text(self):
"""Content of the response as a proper text type.
Uses the encoding type provided in the reponse headers to decode the
response content into a proper text type. If the encoding is not
present in the headers, UTF-8 is used as a default.
"""
encoding = botocore.utils.get_encoding_from_headers(self.headers)
if encoding:
return self.content.decode(encoding)
else:
return self.content.decode('utf-8') | [
"def",
"text",
"(",
"self",
")",
":",
"encoding",
"=",
"botocore",
".",
"utils",
".",
"get_encoding_from_headers",
"(",
"self",
".",
"headers",
")",
"if",
"encoding",
":",
"return",
"self",
".",
"content",
".",
"decode",
"(",
"encoding",
")",
"else",
":"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/awsrequest.py#L559-L570 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/internal/utils.py | python | get_python_function_arguments | (f) | return (arg_names, annotations) | Helper to get the parameter names and annotations of a Python function. | Helper to get the parameter names and annotations of a Python function. | [
"Helper",
"to",
"get",
"the",
"parameter",
"names",
"and",
"annotations",
"of",
"a",
"Python",
"function",
"."
] | def get_python_function_arguments(f):
'''
Helper to get the parameter names and annotations of a Python function.
'''
# Note that we only return non-optional arguments (we assume that any optional args are not specified).
# This allows to, e.g., accept max(a, b, *more, name='') as a binary function
import sys
if sys.version_info.major >= 3:
from inspect import getfullargspec
else:
def getfullargspec(f):
from inspect import getargspec
from ..variables import Record
annotations = getattr(f, '__annotations__', {})
#f.__annotations__ = None # needed when faking it under Python 3 for debugging purposes
a = getargspec(f)
#f.__annotations__ = annotations
return Record(args=a.args, varargs=a.varargs, varkw=a.keywords, defaults=a.defaults, kwonlyargs=[], kwonlydefaults=None, annotations=annotations)
param_specs = getfullargspec(f)
annotations = param_specs.annotations
arg_names = param_specs.args
defaults = param_specs.defaults # "if this tuple has n elements, they correspond to the last n elements listed in args"
if defaults:
arg_names = arg_names[:-len(defaults)] # we allow Function(functions with default arguments), but those args will always have default values since CNTK Functions do not support this
return (arg_names, annotations) | [
"def",
"get_python_function_arguments",
"(",
"f",
")",
":",
"# Note that we only return non-optional arguments (we assume that any optional args are not specified).",
"# This allows to, e.g., accept max(a, b, *more, name='') as a binary function",
"import",
"sys",
"if",
"sys",
".",
"versio... | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/internal/utils.py#L87-L112 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py | python | PlatformDetail.get_configuration_names | (self) | return list(self.platform_configs.keys()) | Return the list of all the configuration names that this platform manages
:return: | Return the list of all the configuration names that this platform manages
:return: | [
"Return",
"the",
"list",
"of",
"all",
"the",
"configuration",
"names",
"that",
"this",
"platform",
"manages",
":",
"return",
":"
] | def get_configuration_names(self):
"""
Return the list of all the configuration names that this platform manages
:return:
"""
return list(self.platform_configs.keys()) | [
"def",
"get_configuration_names",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"platform_configs",
".",
"keys",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py#L258-L263 | |
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_transport.py | python | Transport.capacity | (self) | Get the amount of free space for input following the transport's
tail pointer.
:return: Available space for input in bytes.
:raise: :exc:`TransportException` if there is any Proton error. | Get the amount of free space for input following the transport's
tail pointer. | [
"Get",
"the",
"amount",
"of",
"free",
"space",
"for",
"input",
"following",
"the",
"transport",
"s",
"tail",
"pointer",
"."
] | def capacity(self) -> int:
"""
Get the amount of free space for input following the transport's
tail pointer.
:return: Available space for input in bytes.
:raise: :exc:`TransportException` if there is any Proton error.
"""
c = pn_transport_capacity(self._impl)
if c >= PN_EOS:
return c
else:
return self._check(c) | [
"def",
"capacity",
"(",
"self",
")",
"->",
"int",
":",
"c",
"=",
"pn_transport_capacity",
"(",
"self",
".",
"_impl",
")",
"if",
"c",
">=",
"PN_EOS",
":",
"return",
"c",
"else",
":",
"return",
"self",
".",
"_check",
"(",
"c",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_transport.py#L272-L284 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | uCSIsSupplementaryPrivateUseAreaA | (code) | return ret | Check whether the character is part of
SupplementaryPrivateUseArea-A UCS Block | Check whether the character is part of
SupplementaryPrivateUseArea-A UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"SupplementaryPrivateUseArea",
"-",
"A",
"UCS",
"Block"
] | def uCSIsSupplementaryPrivateUseAreaA(code):
"""Check whether the character is part of
SupplementaryPrivateUseArea-A UCS Block """
ret = libxml2mod.xmlUCSIsSupplementaryPrivateUseAreaA(code)
return ret | [
"def",
"uCSIsSupplementaryPrivateUseAreaA",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsSupplementaryPrivateUseAreaA",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L2888-L2892 | |
schwehr/libais | 1e19605942c8e155cd02fde6d1acde75ecd15d75 | third_party/gmock/scripts/gmock_doctor.py | python | _NeedToReturnSomethingDiagnoser | (msg) | return _GenericDiagnoser(
'NRS',
'Need to Return Something',
[(gcc_regex, diagnosis % {'return_type': '*something*'}),
(clang_regex1, diagnosis),
(clang_regex2, diagnosis)],
msg) | Diagnoses the NRS disease, given the error messages by the compiler. | Diagnoses the NRS disease, given the error messages by the compiler. | [
"Diagnoses",
"the",
"NRS",
"disease",
"given",
"the",
"error",
"messages",
"by",
"the",
"compiler",
"."
] | def _NeedToReturnSomethingDiagnoser(msg):
"""Diagnoses the NRS disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'(instantiated from here\n.'
r'*gmock.*actions\.h.*error: void value not ignored)'
r'|(error: control reaches end of non-void function)')
clang_regex1 = (_CLANG_FILE_LINE_RE +
r'error: cannot initialize return object '
r'of type \'Result\' \(aka \'(?P<return_type>.*)\'\) '
r'with an rvalue of type \'void\'')
clang_regex2 = (_CLANG_FILE_LINE_RE +
r'error: cannot initialize return object '
r'of type \'(?P<return_type>.*)\' '
r'with an rvalue of type \'void\'')
diagnosis = """
You are using an action that returns void, but it needs to return
%(return_type)s. Please tell it *what* to return. Perhaps you can use
the pattern DoAll(some_action, Return(some_value))?"""
return _GenericDiagnoser(
'NRS',
'Need to Return Something',
[(gcc_regex, diagnosis % {'return_type': '*something*'}),
(clang_regex1, diagnosis),
(clang_regex2, diagnosis)],
msg) | [
"def",
"_NeedToReturnSomethingDiagnoser",
"(",
"msg",
")",
":",
"gcc_regex",
"=",
"(",
"_GCC_FILE_LINE_RE",
"+",
"r'(instantiated from here\\n.'",
"r'*gmock.*actions\\.h.*error: void value not ignored)'",
"r'|(error: control reaches end of non-void function)'",
")",
"clang_regex1",
"... | https://github.com/schwehr/libais/blob/1e19605942c8e155cd02fde6d1acde75ecd15d75/third_party/gmock/scripts/gmock_doctor.py#L191-L215 | |
raymondlu/super-animation-samples | 04234269112ff0dc32447f27a761dbbb00b8ba17 | samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | Type.translation_unit | (self) | return self._tu | The TranslationUnit to which this Type is associated. | The TranslationUnit to which this Type is associated. | [
"The",
"TranslationUnit",
"to",
"which",
"this",
"Type",
"is",
"associated",
"."
] | def translation_unit(self):
"""The TranslationUnit to which this Type is associated."""
# If this triggers an AttributeError, the instance was not properly
# instantiated.
return self._tu | [
"def",
"translation_unit",
"(",
"self",
")",
":",
"# If this triggers an AttributeError, the instance was not properly",
"# instantiated.",
"return",
"self",
".",
"_tu"
] | https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1703-L1707 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.