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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | ext/ply/example/unicalc/calc.py | python | t_NUMBER | (t) | return t | ur'\d+ | ur'\d+ | [
"ur",
"\\",
"d",
"+"
] | def t_NUMBER(t):
ur'\d+'
try:
t.value = int(t.value)
except ValueError:
print "Integer value too large", t.value
t.value = 0
return t | [
"def",
"t_NUMBER",
"(",
"t",
")",
":",
"try",
":",
"t",
".",
"value",
"=",
"int",
"(",
"t",
".",
"value",
")",
"except",
"ValueError",
":",
"print",
"\"Integer value too large\"",
",",
"t",
".",
"value",
"t",
".",
"value",
"=",
"0",
"return",
"t"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/unicalc/calc.py#L30-L37 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | Decimal._isinfinity | (self) | return 0 | Returns whether the number is infinite
0 if finite or not a number
1 if +INF
-1 if -INF | Returns whether the number is infinite | [
"Returns",
"whether",
"the",
"number",
"is",
"infinite"
] | def _isinfinity(self):
"""Returns whether the number is infinite
0 if finite or not a number
1 if +INF
-1 if -INF
"""
if self._exp == 'F':
if self._sign:
return -1
return 1
return 0 | [
"def",
"_isinfinity",
"(",
"self",
")",
":",
"if",
"self",
".",
"_exp",
"==",
"'F'",
":",
"if",
"self",
".",
"_sign",
":",
"return",
"-",
"1",
"return",
"1",
"return",
"0"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L715-L726 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | clang/utils/token-delta.py | python | DeltaAlgorithm.split | (self, S) | split(set) -> [sets]
Partition a set into one or two pieces. | split(set) -> [sets] | [
"split",
"(",
"set",
")",
"-",
">",
"[",
"sets",
"]"
] | def split(self, S):
"""split(set) -> [sets]
Partition a set into one or two pieces.
"""
# There are many ways to split, we could do a better job with more
# context information (but then the API becomes grosser).
L = list(S)
mid = len(L)//2
if mid==0:
return L,
else:
return L[:mid],L[mid:] | [
"def",
"split",
"(",
"self",
",",
"S",
")",
":",
"# There are many ways to split, we could do a better job with more",
"# context information (but then the API becomes grosser).",
"L",
"=",
"list",
"(",
"S",
")",
"mid",
"=",
"len",
"(",
"L",
")",
"//",
"2",
"if",
"m... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/utils/token-delta.py#L49-L62 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/cookies.py | python | get_cookie_header | (jar, request) | return r.get_new_headers().get('Cookie') | Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str | Produce an appropriate Cookie header string to be sent with `request`, or None. | [
"Produce",
"an",
"appropriate",
"Cookie",
"header",
"string",
"to",
"be",
"sent",
"with",
"request",
"or",
"None",
"."
] | def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie') | [
"def",
"get_cookie_header",
"(",
"jar",
",",
"request",
")",
":",
"r",
"=",
"MockRequest",
"(",
"request",
")",
"jar",
".",
"add_cookie_header",
"(",
"r",
")",
"return",
"r",
".",
"get_new_headers",
"(",
")",
".",
"get",
"(",
"'Cookie'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/cookies.py#L135-L143 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/code_coverage/process_coverage.py | python | GenerateHtml | (lcov_path, dash_root) | return 'dummy' | Runs genhtml to convert lcov data to human readable HTML.
This script expects the LCOV file name to be in the format:
chrome_<platform>_<revision#>.lcov.
This method parses the file name and then sets up the correct folder
hierarchy for the coverage data and then runs genhtml to get the actual HTML
formatted coverage data.
Args:
lcov_path: Path of the lcov data file.
dash_root: Root location of the dashboard.
Returns:
Code coverage percentage on sucess.
None on failure. | Runs genhtml to convert lcov data to human readable HTML. | [
"Runs",
"genhtml",
"to",
"convert",
"lcov",
"data",
"to",
"human",
"readable",
"HTML",
"."
] | def GenerateHtml(lcov_path, dash_root):
"""Runs genhtml to convert lcov data to human readable HTML.
This script expects the LCOV file name to be in the format:
chrome_<platform>_<revision#>.lcov.
This method parses the file name and then sets up the correct folder
hierarchy for the coverage data and then runs genhtml to get the actual HTML
formatted coverage data.
Args:
lcov_path: Path of the lcov data file.
dash_root: Root location of the dashboard.
Returns:
Code coverage percentage on sucess.
None on failure.
"""
# Parse the LCOV file name.
filename = os.path.basename(lcov_path).split('.')[0]
buffer = filename.split('_')
dash_root = dash_root.rstrip('/') # Remove trailing '/'
# Set up correct folder hierarchy in the dashboard root
# TODO(niranjan): Check the formatting using a regexp
if len(buffer) >= 3: # Check if filename has right formatting
platform = buffer[len(buffer) - 2]
revision = buffer[len(buffer) - 1]
if os.path.exists(os.path.join(dash_root, platform)) == False:
os.mkdir(os.path.join(dash_root, platform))
output_dir = os.path.join(dash_root, platform, revision)
os.mkdir(output_dir)
else:
# TODO(niranjan): Add failure logging here.
return None # File not formatted correctly
# Run genhtml
os.system('/usr/bin/genhtml -o %s %s' % (output_dir, lcov_path))
# TODO(niranjan): Check the exit status of the genhtml command.
# TODO(niranjan): Parse the stdout and return coverage percentage.
CleanPathNames(output_dir)
return 'dummy' | [
"def",
"GenerateHtml",
"(",
"lcov_path",
",",
"dash_root",
")",
":",
"# Parse the LCOV file name.",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"lcov_path",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"buffer",
"=",
"filename",
".",
... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/code_coverage/process_coverage.py#L60-L100 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py | python | LogInputReader.__str__ | (self) | return "LogInputReader(%s)" % ", ".join(params) | Returns the string representation of this LogInputReader. | Returns the string representation of this LogInputReader. | [
"Returns",
"the",
"string",
"representation",
"of",
"this",
"LogInputReader",
"."
] | def __str__(self):
"""Returns the string representation of this LogInputReader."""
params = []
for key in sorted(self.__params.keys()):
value = self.__params[key]
if key is self._PROTOTYPE_REQUEST_PARAM:
params.append("%s='%s'" % (key, value))
elif key is self._OFFSET_PARAM:
params.append("%s='%s'" % (key, value))
else:
params.append("%s=%s" % (key, value))
return "LogInputReader(%s)" % ", ".join(params) | [
"def",
"__str__",
"(",
"self",
")",
":",
"params",
"=",
"[",
"]",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"__params",
".",
"keys",
"(",
")",
")",
":",
"value",
"=",
"self",
".",
"__params",
"[",
"key",
"]",
"if",
"key",
"is",
"self",
".... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py#L2232-L2244 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py | python | get_common_complete_suffix | (
document: Document, completions: Sequence[Completion]
) | return _commonprefix([get_suffix(c) for c in completions2]) | Return the common prefix for all completions. | Return the common prefix for all completions. | [
"Return",
"the",
"common",
"prefix",
"for",
"all",
"completions",
"."
] | def get_common_complete_suffix(
document: Document, completions: Sequence[Completion]
) -> str:
"""
Return the common prefix for all completions.
"""
# Take only completions that don't change the text before the cursor.
def doesnt_change_before_cursor(completion: Completion) -> bool:
end = completion.text[: -completion.start_position]
return document.text_before_cursor.endswith(end)
completions2 = [c for c in completions if doesnt_change_before_cursor(c)]
# When there is at least one completion that changes the text before the
# cursor, don't return any common part.
if len(completions2) != len(completions):
return ""
# Return the common prefix.
def get_suffix(completion: Completion) -> str:
return completion.text[-completion.start_position :]
return _commonprefix([get_suffix(c) for c in completions2]) | [
"def",
"get_common_complete_suffix",
"(",
"document",
":",
"Document",
",",
"completions",
":",
"Sequence",
"[",
"Completion",
"]",
")",
"->",
"str",
":",
"# Take only completions that don't change the text before the cursor.",
"def",
"doesnt_change_before_cursor",
"(",
"co... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py#L360-L382 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | PhysicsTools/HeppyCore/python/statistics/average.py | python | Average.write | (self, dirname) | Dump the average to a pickle file and to a text file in dirname. | Dump the average to a pickle file and to a text file in dirname. | [
"Dump",
"the",
"average",
"to",
"a",
"pickle",
"file",
"and",
"to",
"a",
"text",
"file",
"in",
"dirname",
"."
] | def write(self, dirname):
'''Dump the average to a pickle file and to a text file in dirname.'''
pckfname = '{d}/{f}.pck'.format(d=dirname, f=self.name)
pckfile = open( pckfname, 'w' )
pickle.dump(self, pckfile)
txtfile = open( pckfname.replace('.pck', '.txt'), 'w')
txtfile.write( str(self) )
txtfile.write( '\n' )
txtfile.close() | [
"def",
"write",
"(",
"self",
",",
"dirname",
")",
":",
"pckfname",
"=",
"'{d}/{f}.pck'",
".",
"format",
"(",
"d",
"=",
"dirname",
",",
"f",
"=",
"self",
".",
"name",
")",
"pckfile",
"=",
"open",
"(",
"pckfname",
",",
"'w'",
")",
"pickle",
".",
"dum... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/HeppyCore/python/statistics/average.py#L65-L73 | ||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | tools/pytorch-quantization/pytorch_quantization/tensor_quant.py | python | ScaledQuantDescriptor.__eq__ | (self, rhs) | return self.__dict__ == rhs.__dict__ | Compare 2 descriptors | Compare 2 descriptors | [
"Compare",
"2",
"descriptors"
] | def __eq__(self, rhs):
"""Compare 2 descriptors"""
return self.__dict__ == rhs.__dict__ | [
"def",
"__eq__",
"(",
"self",
",",
"rhs",
")",
":",
"return",
"self",
".",
"__dict__",
"==",
"rhs",
".",
"__dict__"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/pytorch-quantization/pytorch_quantization/tensor_quant.py#L167-L169 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | Log_SetActiveTarget | (*args, **kwargs) | return _misc_.Log_SetActiveTarget(*args, **kwargs) | Log_SetActiveTarget(Log pLogger) -> Log | Log_SetActiveTarget(Log pLogger) -> Log | [
"Log_SetActiveTarget",
"(",
"Log",
"pLogger",
")",
"-",
">",
"Log"
] | def Log_SetActiveTarget(*args, **kwargs):
"""Log_SetActiveTarget(Log pLogger) -> Log"""
return _misc_.Log_SetActiveTarget(*args, **kwargs) | [
"def",
"Log_SetActiveTarget",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Log_SetActiveTarget",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1668-L1670 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/nn_ops.py | python | _MaxPool3DGradShape | (op) | return [orig_input_shape] | Shape function for the MaxPoolGrad op. | Shape function for the MaxPoolGrad op. | [
"Shape",
"function",
"for",
"the",
"MaxPoolGrad",
"op",
"."
] | def _MaxPool3DGradShape(op):
"""Shape function for the MaxPoolGrad op."""
orig_input_shape = op.inputs[0].get_shape().with_rank(5)
return [orig_input_shape] | [
"def",
"_MaxPool3DGradShape",
"(",
"op",
")",
":",
"orig_input_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"5",
")",
"return",
"[",
"orig_input_shape",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/nn_ops.py#L1007-L1010 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/bijector/scalar_affine.py | python | ScalarAffine._forward | (self, x) | return forward_v | r"""
.. math::
f(x) = a * x + b | r"""
.. math::
f(x) = a * x + b | [
"r",
"..",
"math",
"::",
"f",
"(",
"x",
")",
"=",
"a",
"*",
"x",
"+",
"b"
] | def _forward(self, x):
r"""
.. math::
f(x) = a * x + b
"""
x = self._check_value_dtype(x)
scale_local = self.cast_param_by_value(x, self.scale)
shift_local = self.cast_param_by_value(x, self.shift)
forward_v = scale_local * x + shift_local * self.oneslike(x)
return forward_v | [
"def",
"_forward",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"self",
".",
"_check_value_dtype",
"(",
"x",
")",
"scale_local",
"=",
"self",
".",
"cast_param_by_value",
"(",
"x",
",",
"self",
".",
"scale",
")",
"shift_local",
"=",
"self",
".",
"cast_par... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/bijector/scalar_affine.py#L136-L145 | |
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/python_version/optimization.py | python | LBFGSBOptimizer._optimize_core | (self, **kwargs) | return scipy.optimize.fmin_l_bfgs_b(
func=self._scipy_decorator(self.objective_function.compute_objective_function, **kwargs),
x0=self.objective_function.current_point.flatten(),
bounds=domain_numpy,
fprime=self._scipy_decorator(self.objective_function.compute_grad_objective_function, **kwargs),
**self.optimization_parameters.scipy_kwargs()
)[0] | Perform an L-BFGS-B optimization given the parameters in ``self.optimization_parameters``. | Perform an L-BFGS-B optimization given the parameters in ``self.optimization_parameters``. | [
"Perform",
"an",
"L",
"-",
"BFGS",
"-",
"B",
"optimization",
"given",
"the",
"parameters",
"in",
"self",
".",
"optimization_parameters",
"."
] | def _optimize_core(self, **kwargs):
"""Perform an L-BFGS-B optimization given the parameters in ``self.optimization_parameters``."""
domain_bounding_box = self.domain.get_bounding_box()
domain_list = [(interval.min, interval.max) for interval in domain_bounding_box]
domain_numpy = numpy.array(domain_list * self._num_points)
# Parameters defined above in :class:`~moe.optimal_learning.python.python_version.optimization.LBFGSBParameters` class.
return scipy.optimize.fmin_l_bfgs_b(
func=self._scipy_decorator(self.objective_function.compute_objective_function, **kwargs),
x0=self.objective_function.current_point.flatten(),
bounds=domain_numpy,
fprime=self._scipy_decorator(self.objective_function.compute_grad_objective_function, **kwargs),
**self.optimization_parameters.scipy_kwargs()
)[0] | [
"def",
"_optimize_core",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"domain_bounding_box",
"=",
"self",
".",
"domain",
".",
"get_bounding_box",
"(",
")",
"domain_list",
"=",
"[",
"(",
"interval",
".",
"min",
",",
"interval",
".",
"max",
")",
"for",
... | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/python_version/optimization.py#L727-L740 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py | python | MaskedArray.view | (self, dtype=None, type=None, fill_value=None) | return output | Return a view of the MaskedArray data.
Parameters
----------
dtype : data-type or ndarray sub-class, optional
Data-type descriptor of the returned view, e.g., float32 or int16.
The default, None, results in the view having the same data-type
as `a`. As with ``ndarray.view``, dtype can also be specified as
an ndarray sub-class, which then specifies the type of the
returned object (this is equivalent to setting the ``type``
parameter).
type : Python type, optional
Type of the returned view, either ndarray or a subclass. The
default None results in type preservation.
fill_value : scalar, optional
The value to use for invalid entries (None by default).
If None, then this argument is inferred from the passed `dtype`, or
in its absence the original array, as discussed in the notes below.
See Also
--------
numpy.ndarray.view : Equivalent method on ndarray object.
Notes
-----
``a.view()`` is used two different ways:
``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
of the array's memory with a different data-type. This can cause a
reinterpretation of the bytes of memory.
``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
returns an instance of `ndarray_subclass` that looks at the same array
(same shape, dtype, etc.) This does not cause a reinterpretation of the
memory.
If `fill_value` is not specified, but `dtype` is specified (and is not
an ndarray sub-class), the `fill_value` of the MaskedArray will be
reset. If neither `fill_value` nor `dtype` are specified (or if
`dtype` is an ndarray sub-class), then the fill value is preserved.
Finally, if `fill_value` is specified, but `dtype` is not, the fill
value is set to the specified value.
For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
bytes per entry than the previous dtype (for example, converting a
regular array to a structured array), then the behavior of the view
cannot be predicted just from the superficial appearance of ``a`` (shown
by ``print(a)``). It also depends on exactly how ``a`` is stored in
memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
defined as a slice or transpose, etc., the view may give different
results. | Return a view of the MaskedArray data. | [
"Return",
"a",
"view",
"of",
"the",
"MaskedArray",
"data",
"."
] | def view(self, dtype=None, type=None, fill_value=None):
"""
Return a view of the MaskedArray data.
Parameters
----------
dtype : data-type or ndarray sub-class, optional
Data-type descriptor of the returned view, e.g., float32 or int16.
The default, None, results in the view having the same data-type
as `a`. As with ``ndarray.view``, dtype can also be specified as
an ndarray sub-class, which then specifies the type of the
returned object (this is equivalent to setting the ``type``
parameter).
type : Python type, optional
Type of the returned view, either ndarray or a subclass. The
default None results in type preservation.
fill_value : scalar, optional
The value to use for invalid entries (None by default).
If None, then this argument is inferred from the passed `dtype`, or
in its absence the original array, as discussed in the notes below.
See Also
--------
numpy.ndarray.view : Equivalent method on ndarray object.
Notes
-----
``a.view()`` is used two different ways:
``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
of the array's memory with a different data-type. This can cause a
reinterpretation of the bytes of memory.
``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
returns an instance of `ndarray_subclass` that looks at the same array
(same shape, dtype, etc.) This does not cause a reinterpretation of the
memory.
If `fill_value` is not specified, but `dtype` is specified (and is not
an ndarray sub-class), the `fill_value` of the MaskedArray will be
reset. If neither `fill_value` nor `dtype` are specified (or if
`dtype` is an ndarray sub-class), then the fill value is preserved.
Finally, if `fill_value` is specified, but `dtype` is not, the fill
value is set to the specified value.
For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
bytes per entry than the previous dtype (for example, converting a
regular array to a structured array), then the behavior of the view
cannot be predicted just from the superficial appearance of ``a`` (shown
by ``print(a)``). It also depends on exactly how ``a`` is stored in
memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
defined as a slice or transpose, etc., the view may give different
results.
"""
if dtype is None:
if type is None:
output = ndarray.view(self)
else:
output = ndarray.view(self, type)
elif type is None:
try:
if issubclass(dtype, ndarray):
output = ndarray.view(self, dtype)
dtype = None
else:
output = ndarray.view(self, dtype)
except TypeError:
output = ndarray.view(self, dtype)
else:
output = ndarray.view(self, dtype, type)
# also make the mask be a view (so attr changes to the view's
# mask do no affect original object's mask)
# (especially important to avoid affecting np.masked singleton)
if getmask(output) is not nomask:
output._mask = output._mask.view()
# Make sure to reset the _fill_value if needed
if getattr(output, '_fill_value', None) is not None:
if fill_value is None:
if dtype is None:
pass # leave _fill_value as is
else:
output._fill_value = None
else:
output.fill_value = fill_value
return output | [
"def",
"view",
"(",
"self",
",",
"dtype",
"=",
"None",
",",
"type",
"=",
"None",
",",
"fill_value",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"if",
"type",
"is",
"None",
":",
"output",
"=",
"ndarray",
".",
"view",
"(",
"self",
")",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L3087-L3175 | |
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | IndigoObject.symbol | (self) | return self.dispatcher._checkResultString(
Indigo._lib.indigoSymbol(self.id)
) | Atom method returns string symbol
Returns:
str: atom symbol | Atom method returns string symbol | [
"Atom",
"method",
"returns",
"string",
"symbol"
] | def symbol(self):
"""Atom method returns string symbol
Returns:
str: atom symbol
"""
self.dispatcher._setSessionId()
return self.dispatcher._checkResultString(
Indigo._lib.indigoSymbol(self.id)
) | [
"def",
"symbol",
"(",
"self",
")",
":",
"self",
".",
"dispatcher",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"dispatcher",
".",
"_checkResultString",
"(",
"Indigo",
".",
"_lib",
".",
"indigoSymbol",
"(",
"self",
".",
"id",
")",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L1044-L1053 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/packaging/py2/packaging/specifiers.py | python | BaseSpecifier.__ne__ | (self, other) | Returns a boolean representing whether or not the two Specifier like
objects are not equal. | Returns a boolean representing whether or not the two Specifier like
objects are not equal. | [
"Returns",
"a",
"boolean",
"representing",
"whether",
"or",
"not",
"the",
"two",
"Specifier",
"like",
"objects",
"are",
"not",
"equal",
"."
] | def __ne__(self, other):
# type: (object) -> bool
"""
Returns a boolean representing whether or not the two Specifier like
objects are not equal.
""" | [
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"# type: (object) -> bool"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/packaging/py2/packaging/specifiers.py#L56-L61 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/traceback.py | python | FrameSummary.__init__ | (self, filename, lineno, name, *, lookup_line=True,
locals=None, line=None) | Construct a FrameSummary.
:param lookup_line: If True, `linecache` is consulted for the source
code line. Otherwise, the line will be looked up when first needed.
:param locals: If supplied the frame locals, which will be captured as
object representations.
:param line: If provided, use this instead of looking up the line in
the linecache. | Construct a FrameSummary. | [
"Construct",
"a",
"FrameSummary",
"."
] | def __init__(self, filename, lineno, name, *, lookup_line=True,
locals=None, line=None):
"""Construct a FrameSummary.
:param lookup_line: If True, `linecache` is consulted for the source
code line. Otherwise, the line will be looked up when first needed.
:param locals: If supplied the frame locals, which will be captured as
object representations.
:param line: If provided, use this instead of looking up the line in
the linecache.
"""
self.filename = filename
self.lineno = lineno
self.name = name
self._line = line
if lookup_line:
self.line
self.locals = {k: repr(v) for k, v in locals.items()} if locals else None | [
"def",
"__init__",
"(",
"self",
",",
"filename",
",",
"lineno",
",",
"name",
",",
"*",
",",
"lookup_line",
"=",
"True",
",",
"locals",
"=",
"None",
",",
"line",
"=",
"None",
")",
":",
"self",
".",
"filename",
"=",
"filename",
"self",
".",
"lineno",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/traceback.py#L243-L260 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/build/mac/change_mach_o_flags.py | python | ReadMachHeader | (file, endian) | return magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags | Reads an entire |mach_header| structure (<mach-o/loader.h>) from the
file-like |file| object, treating it as having endianness specified by
|endian| (per the |struct| module), and returns a 7-tuple of its members
as numbers. Raises a MachOError if the proper length of data can't be read
from |file|. | Reads an entire |mach_header| structure (<mach-o/loader.h>) from the
file-like |file| object, treating it as having endianness specified by
|endian| (per the |struct| module), and returns a 7-tuple of its members
as numbers. Raises a MachOError if the proper length of data can't be read
from |file|. | [
"Reads",
"an",
"entire",
"|mach_header|",
"structure",
"(",
"<mach",
"-",
"o",
"/",
"loader",
".",
"h",
">",
")",
"from",
"the",
"file",
"-",
"like",
"|file|",
"object",
"treating",
"it",
"as",
"having",
"endianness",
"specified",
"by",
"|endian|",
"(",
... | def ReadMachHeader(file, endian):
"""Reads an entire |mach_header| structure (<mach-o/loader.h>) from the
file-like |file| object, treating it as having endianness specified by
|endian| (per the |struct| module), and returns a 7-tuple of its members
as numbers. Raises a MachOError if the proper length of data can't be read
from |file|."""
bytes = CheckedRead(file, 28)
magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags = \
struct.unpack(endian + '7I', bytes)
return magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags | [
"def",
"ReadMachHeader",
"(",
"file",
",",
"endian",
")",
":",
"bytes",
"=",
"CheckedRead",
"(",
"file",
",",
"28",
")",
"magic",
",",
"cputype",
",",
"cpusubtype",
",",
"filetype",
",",
"ncmds",
",",
"sizeofcmds",
",",
"flags",
"=",
"struct",
".",
"un... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/mac/change_mach_o_flags.py#L137-L148 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/core/multiarray.py | python | putmask | (a, mask, values) | return (a, mask, values) | putmask(a, mask, values)
Changes elements of an array based on conditional and input values.
Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
If `values` is not the same size as `a` and `mask` then it will repeat.
This gives behavior different from ``a[mask] = values``.
Parameters
----------
a : array_like
Target array.
mask : array_like
Boolean mask array. It has to be the same shape as `a`.
values : array_like
Values to put into `a` where `mask` is True. If `values` is smaller
than `a` it will be repeated.
See Also
--------
place, put, take, copyto
Examples
--------
>>> x = np.arange(6).reshape(2, 3)
>>> np.putmask(x, x>2, x**2)
>>> x
array([[ 0, 1, 2],
[ 9, 16, 25]])
If `values` is smaller than `a` it is repeated:
>>> x = np.arange(5)
>>> np.putmask(x, x>1, [-33, -44])
>>> x
array([ 0, 1, -33, -44, -33]) | putmask(a, mask, values) | [
"putmask",
"(",
"a",
"mask",
"values",
")"
] | def putmask(a, mask, values):
"""
putmask(a, mask, values)
Changes elements of an array based on conditional and input values.
Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
If `values` is not the same size as `a` and `mask` then it will repeat.
This gives behavior different from ``a[mask] = values``.
Parameters
----------
a : array_like
Target array.
mask : array_like
Boolean mask array. It has to be the same shape as `a`.
values : array_like
Values to put into `a` where `mask` is True. If `values` is smaller
than `a` it will be repeated.
See Also
--------
place, put, take, copyto
Examples
--------
>>> x = np.arange(6).reshape(2, 3)
>>> np.putmask(x, x>2, x**2)
>>> x
array([[ 0, 1, 2],
[ 9, 16, 25]])
If `values` is smaller than `a` it is repeated:
>>> x = np.arange(5)
>>> np.putmask(x, x>1, [-33, -44])
>>> x
array([ 0, 1, -33, -44, -33])
"""
return (a, mask, values) | [
"def",
"putmask",
"(",
"a",
",",
"mask",
",",
"values",
")",
":",
"return",
"(",
"a",
",",
"mask",
",",
"values",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/multiarray.py#L1072-L1113 | |
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/utility.py | python | ArrayManager.adosc | (
self,
fast_period: int,
slow_period: int,
array: bool = False
) | return result[-1] | ADOSC. | ADOSC. | [
"ADOSC",
"."
] | def adosc(
self,
fast_period: int,
slow_period: int,
array: bool = False
) -> Union[float, np.ndarray]:
"""
ADOSC.
"""
result = talib.ADOSC(self.high, self.low, self.close, self.volume, fast_period, slow_period)
if array:
return result
return result[-1] | [
"def",
"adosc",
"(",
"self",
",",
"fast_period",
":",
"int",
",",
"slow_period",
":",
"int",
",",
"array",
":",
"bool",
"=",
"False",
")",
"->",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
":",
"result",
"=",
"talib",
".",
"ADOSC",
"(",
... | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/utility.py#L931-L943 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/special/basic.py | python | factorialk | (n, k, exact=True) | Multifactorial of n of order k, n(!!...!).
This is the multifactorial of n skipping k values. For example,
factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
In particular, for any integer ``n``, we have
factorialk(n, 1) = factorial(n)
factorialk(n, 2) = factorial2(n)
Parameters
----------
n : int
Calculate multifactorial. If `n` < 0, the return value is 0.
k : int
Order of multifactorial.
exact : bool, optional
If exact is set to True, calculate the answer exactly using
integer arithmetic.
Returns
-------
val : int
Multifactorial of `n`.
Raises
------
NotImplementedError
Raises when exact is False
Examples
--------
>>> from scipy.special import factorialk
>>> factorialk(5, 1, exact=True)
120L
>>> factorialk(5, 3, exact=True)
10L | Multifactorial of n of order k, n(!!...!). | [
"Multifactorial",
"of",
"n",
"of",
"order",
"k",
"n",
"(",
"!!",
"...",
"!",
")",
"."
] | def factorialk(n, k, exact=True):
"""Multifactorial of n of order k, n(!!...!).
This is the multifactorial of n skipping k values. For example,
factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
In particular, for any integer ``n``, we have
factorialk(n, 1) = factorial(n)
factorialk(n, 2) = factorial2(n)
Parameters
----------
n : int
Calculate multifactorial. If `n` < 0, the return value is 0.
k : int
Order of multifactorial.
exact : bool, optional
If exact is set to True, calculate the answer exactly using
integer arithmetic.
Returns
-------
val : int
Multifactorial of `n`.
Raises
------
NotImplementedError
Raises when exact is False
Examples
--------
>>> from scipy.special import factorialk
>>> factorialk(5, 1, exact=True)
120L
>>> factorialk(5, 3, exact=True)
10L
"""
if exact:
if n < 1-k:
return 0
if n <= 0:
return 1
val = 1
for j in xrange(n, 0, -k):
val = val*j
return val
else:
raise NotImplementedError | [
"def",
"factorialk",
"(",
"n",
",",
"k",
",",
"exact",
"=",
"True",
")",
":",
"if",
"exact",
":",
"if",
"n",
"<",
"1",
"-",
"k",
":",
"return",
"0",
"if",
"n",
"<=",
"0",
":",
"return",
"1",
"val",
"=",
"1",
"for",
"j",
"in",
"xrange",
"(",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/special/basic.py#L2168-L2220 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/dis.py | python | _get_instructions_bytes | (code, varnames=None, names=None, constants=None,
cells=None, linestarts=None, line_offset=0) | Iterate over the instructions in a bytecode string.
Generates a sequence of Instruction namedtuples giving the details of each
opcode. Additional information about the code's runtime environment
(e.g. variable names, constants) can be specified using optional
arguments. | Iterate over the instructions in a bytecode string. | [
"Iterate",
"over",
"the",
"instructions",
"in",
"a",
"bytecode",
"string",
"."
] | def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
cells=None, linestarts=None, line_offset=0):
"""Iterate over the instructions in a bytecode string.
Generates a sequence of Instruction namedtuples giving the details of each
opcode. Additional information about the code's runtime environment
(e.g. variable names, constants) can be specified using optional
arguments.
"""
labels = findlabels(code)
starts_line = None
for offset, op, arg in _unpack_opargs(code):
if linestarts is not None:
starts_line = linestarts.get(offset, None)
if starts_line is not None:
starts_line += line_offset
is_jump_target = offset in labels
argval = None
argrepr = ''
if arg is not None:
# Set argval to the dereferenced value of the argument when
# available, and argrepr to the string representation of argval.
# _disassemble_bytes needs the string repr of the
# raw name index for LOAD_GLOBAL, LOAD_CONST, etc.
argval = arg
if op in hasconst:
argval, argrepr = _get_const_info(arg, constants)
elif op in hasname:
argval, argrepr = _get_name_info(arg, names)
elif op in hasjrel:
argval = offset + 2 + arg
argrepr = "to " + repr(argval)
elif op in haslocal:
argval, argrepr = _get_name_info(arg, varnames)
elif op in hascompare:
argval = cmp_op[arg]
argrepr = argval
elif op in hasfree:
argval, argrepr = _get_name_info(arg, cells)
elif op == FORMAT_VALUE:
argval = ((None, str, repr, ascii)[arg & 0x3], bool(arg & 0x4))
argrepr = ('', 'str', 'repr', 'ascii')[arg & 0x3]
if argval[1]:
if argrepr:
argrepr += ', '
argrepr += 'with format'
yield Instruction(opname[op], op,
arg, argval, argrepr,
offset, starts_line, is_jump_target) | [
"def",
"_get_instructions_bytes",
"(",
"code",
",",
"varnames",
"=",
"None",
",",
"names",
"=",
"None",
",",
"constants",
"=",
"None",
",",
"cells",
"=",
"None",
",",
"linestarts",
"=",
"None",
",",
"line_offset",
"=",
"0",
")",
":",
"labels",
"=",
"fi... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/dis.py#L301-L350 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/ecdsa/ellipticcurve.py | python | CurveFp.contains_point | ( self, x, y ) | return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 | Is the point (x,y) on this curve? | Is the point (x,y) on this curve? | [
"Is",
"the",
"point",
"(",
"x",
"y",
")",
"on",
"this",
"curve?"
] | def contains_point( self, x, y ):
"""Is the point (x,y) on this curve?"""
return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 | [
"def",
"contains_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"(",
"y",
"*",
"y",
"-",
"(",
"x",
"*",
"x",
"*",
"x",
"+",
"self",
".",
"__a",
"*",
"x",
"+",
"self",
".",
"__b",
")",
")",
"%",
"self",
".",
"__p",
"==",
"0"
... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/ecdsa/ellipticcurve.py#L57-L59 | |
akai-katto/dandere2x | bf1a46d5c9f9ffc8145a412c3571b283345b8512 | src/dandere2x/dandere2xlib/wrappers/ffmpeg/ffmpeg.py | python | divide_and_reencode_video | (ffmpeg_path: str, ffprobe_path: str,
input_video: str, output_options: dict,
divide: int, output_dir: str) | return return_string | Attempts to divide a video into N different segments, using the ffmpeg segment_time argument. See the reading
I referenced here:
https://superuser.com/questions/692714/how-to-split-videos-with-ffmpeg-and-segment-times-option
Note that this will not perfectly divide the video into N different, equally sized chunks, but rather will cut them
where keyframes allow them to be split.
Args:
ffmpeg_path: ffmpeg binary
ffprobe_path: ffprobe binary
input_video: File to be split
output_options: Dictionary containing the loaded ./config_files/output_options.yaml
divide: N divisions.
output_dir: Where to save split_video%d.mkv's.
Returns:
Nothing, but split_video%d.mkv files will appear in output_dir. | Attempts to divide a video into N different segments, using the ffmpeg segment_time argument. See the reading
I referenced here:
https://superuser.com/questions/692714/how-to-split-videos-with-ffmpeg-and-segment-times-option
Note that this will not perfectly divide the video into N different, equally sized chunks, but rather will cut them
where keyframes allow them to be split. | [
"Attempts",
"to",
"divide",
"a",
"video",
"into",
"N",
"different",
"segments",
"using",
"the",
"ffmpeg",
"segment_time",
"argument",
".",
"See",
"the",
"reading",
"I",
"referenced",
"here",
":",
"https",
":",
"//",
"superuser",
".",
"com",
"/",
"questions",... | def divide_and_reencode_video(ffmpeg_path: str, ffprobe_path: str,
input_video: str, output_options: dict,
divide: int, output_dir: str):
"""
Attempts to divide a video into N different segments, using the ffmpeg segment_time argument. See the reading
I referenced here:
https://superuser.com/questions/692714/how-to-split-videos-with-ffmpeg-and-segment-times-option
Note that this will not perfectly divide the video into N different, equally sized chunks, but rather will cut them
where keyframes allow them to be split.
Args:
ffmpeg_path: ffmpeg binary
ffprobe_path: ffprobe binary
input_video: File to be split
output_options: Dictionary containing the loaded ./config_files/output_options.yaml
divide: N divisions.
output_dir: Where to save split_video%d.mkv's.
Returns:
Nothing, but split_video%d.mkv files will appear in output_dir.
"""
import math
seconds = int(get_seconds(ffprobe_dir=ffprobe_path, input_video=input_video))
ratio = math.ceil(seconds / divide)
frame_rate = VideoSettings(ffprobe_dir=ffprobe_path, video_file=input_video).frame_rate
execute = [ffmpeg_path,
"-i", input_video,
"-f", "segment",
"-segment_time", str(ratio),
"-r", str(frame_rate)]
options = get_options_from_section(output_options["ffmpeg"]['pre_process_video']['output_options'],
ffmpeg_command=True)
for element in options:
execute.append(element)
execute.append(os.path.join(output_dir, "split_video%d.mkv"))
return_bytes = subprocess.run(execute, check=True, stdout=subprocess.PIPE).stdout
return_string = return_bytes.decode("utf-8")
return return_string | [
"def",
"divide_and_reencode_video",
"(",
"ffmpeg_path",
":",
"str",
",",
"ffprobe_path",
":",
"str",
",",
"input_video",
":",
"str",
",",
"output_options",
":",
"dict",
",",
"divide",
":",
"int",
",",
"output_dir",
":",
"str",
")",
":",
"import",
"math",
"... | https://github.com/akai-katto/dandere2x/blob/bf1a46d5c9f9ffc8145a412c3571b283345b8512/src/dandere2x/dandere2xlib/wrappers/ffmpeg/ffmpeg.py#L162-L208 | |
microsoft/EdgeML | ef9f8a77f096acbdeb941014791f8eda1c1bc35b | examples/pytorch/DROCC/main_tabular.py | python | adjust_learning_rate | (epoch, total_epochs, only_ce_epochs, learning_rate, optimizer) | return optimizer | Adjust learning rate during training.
Parameters
----------
epoch: Current training epoch.
total_epochs: Total number of epochs for training.
only_ce_epochs: Number of epochs for initial pretraining.
learning_rate: Initial learning rate for training. | Adjust learning rate during training. | [
"Adjust",
"learning",
"rate",
"during",
"training",
"."
] | def adjust_learning_rate(epoch, total_epochs, only_ce_epochs, learning_rate, optimizer):
"""Adjust learning rate during training.
Parameters
----------
epoch: Current training epoch.
total_epochs: Total number of epochs for training.
only_ce_epochs: Number of epochs for initial pretraining.
learning_rate: Initial learning rate for training.
"""
#We dont want to consider the only ce
#based epochs for the lr scheduler
epoch = epoch - only_ce_epochs
drocc_epochs = total_epochs - only_ce_epochs
# lr = learning_rate
if epoch <= drocc_epochs:
lr = learning_rate * 0.001
if epoch <= 0.90 * drocc_epochs:
lr = learning_rate * 0.01
if epoch <= 0.60 * drocc_epochs:
lr = learning_rate * 0.1
if epoch <= 0.30 * drocc_epochs:
lr = learning_rate
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return optimizer | [
"def",
"adjust_learning_rate",
"(",
"epoch",
",",
"total_epochs",
",",
"only_ce_epochs",
",",
"learning_rate",
",",
"optimizer",
")",
":",
"#We dont want to consider the only ce ",
"#based epochs for the lr scheduler",
"epoch",
"=",
"epoch",
"-",
"only_ce_epochs",
"drocc_ep... | https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/examples/pytorch/DROCC/main_tabular.py#L40-L66 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Tools/c_config.py | python | validate_cfg | (self, kw) | Searches for the program *pkg-config* if missing, and validates the
parameters to pass to :py:func:`waflib.Tools.c_config.exec_cfg`.
:param path: the **-config program to use** (default is *pkg-config*)
:type path: list of string
:param msg: message to display to describe the test executed
:type msg: string
:param okmsg: message to display when the test is successful
:type okmsg: string
:param errmsg: message to display in case of error
:type errmsg: string | Searches for the program *pkg-config* if missing, and validates the
parameters to pass to :py:func:`waflib.Tools.c_config.exec_cfg`. | [
"Searches",
"for",
"the",
"program",
"*",
"pkg",
"-",
"config",
"*",
"if",
"missing",
"and",
"validates",
"the",
"parameters",
"to",
"pass",
"to",
":",
"py",
":",
"func",
":",
"waflib",
".",
"Tools",
".",
"c_config",
".",
"exec_cfg",
"."
] | def validate_cfg(self, kw):
"""
Searches for the program *pkg-config* if missing, and validates the
parameters to pass to :py:func:`waflib.Tools.c_config.exec_cfg`.
:param path: the **-config program to use** (default is *pkg-config*)
:type path: list of string
:param msg: message to display to describe the test executed
:type msg: string
:param okmsg: message to display when the test is successful
:type okmsg: string
:param errmsg: message to display in case of error
:type errmsg: string
"""
if not 'path' in kw:
if not self.env.PKGCONFIG:
self.find_program('pkg-config', var='PKGCONFIG')
kw['path'] = self.env.PKGCONFIG
# verify that exactly one action is requested
s = ('atleast_pkgconfig_version' in kw) + ('modversion' in kw) + ('package' in kw)
if s != 1:
raise ValueError('exactly one of atleast_pkgconfig_version, modversion and package must be set')
if not 'msg' in kw:
if 'atleast_pkgconfig_version' in kw:
kw['msg'] = 'Checking for pkg-config version >= %r' % kw['atleast_pkgconfig_version']
elif 'modversion' in kw:
kw['msg'] = 'Checking for %r version' % kw['modversion']
else:
kw['msg'] = 'Checking for %r' %(kw['package'])
# let the modversion check set the okmsg to the detected version
if not 'okmsg' in kw and not 'modversion' in kw:
kw['okmsg'] = 'yes'
if not 'errmsg' in kw:
kw['errmsg'] = 'not found'
# pkg-config version
if 'atleast_pkgconfig_version' in kw:
pass
elif 'modversion' in kw:
if not 'uselib_store' in kw:
kw['uselib_store'] = kw['modversion']
if not 'define_name' in kw:
kw['define_name'] = '%s_VERSION' % Utils.quote_define_name(kw['uselib_store'])
else:
if not 'uselib_store' in kw:
kw['uselib_store'] = Utils.to_list(kw['package'])[0].upper()
if not 'define_name' in kw:
kw['define_name'] = self.have_define(kw['uselib_store']) | [
"def",
"validate_cfg",
"(",
"self",
",",
"kw",
")",
":",
"if",
"not",
"'path'",
"in",
"kw",
":",
"if",
"not",
"self",
".",
"env",
".",
"PKGCONFIG",
":",
"self",
".",
"find_program",
"(",
"'pkg-config'",
",",
"var",
"=",
"'PKGCONFIG'",
")",
"kw",
"[",... | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/c_config.py#L189-L238 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/contrib/_securetransport/low_level.py | python | _assert_no_error | (error, exception_class=None) | Checks the return code and throws an exception if there is an error to
report | Checks the return code and throws an exception if there is an error to
report | [
"Checks",
"the",
"return",
"code",
"and",
"throws",
"an",
"exception",
"if",
"there",
"is",
"an",
"error",
"to",
"report"
] | def _assert_no_error(error, exception_class=None):
"""
Checks the return code and throws an exception if there is an error to
report
"""
if error == 0:
return
cf_error_string = Security.SecCopyErrorMessageString(error, None)
output = _cf_string_to_unicode(cf_error_string)
CoreFoundation.CFRelease(cf_error_string)
if output is None or output == u"":
output = u"OSStatus %s" % error
if exception_class is None:
exception_class = ssl.SSLError
raise exception_class(output) | [
"def",
"_assert_no_error",
"(",
"error",
",",
"exception_class",
"=",
"None",
")",
":",
"if",
"error",
"==",
"0",
":",
"return",
"cf_error_string",
"=",
"Security",
".",
"SecCopyErrorMessageString",
"(",
"error",
",",
"None",
")",
"output",
"=",
"_cf_string_to... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/contrib/_securetransport/low_level.py#L84-L102 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlDoc.addDtdEntity | (self, name, type, ExternalID, SystemID, content) | return __tmp | Register a new entity for this document DTD external subset. | Register a new entity for this document DTD external subset. | [
"Register",
"a",
"new",
"entity",
"for",
"this",
"document",
"DTD",
"external",
"subset",
"."
] | def addDtdEntity(self, name, type, ExternalID, SystemID, content):
"""Register a new entity for this document DTD external subset. """
ret = libxml2mod.xmlAddDtdEntity(self._o, name, type, ExternalID, SystemID, content)
if ret is None:raise treeError('xmlAddDtdEntity() failed')
__tmp = xmlEntity(_obj=ret)
return __tmp | [
"def",
"addDtdEntity",
"(",
"self",
",",
"name",
",",
"type",
",",
"ExternalID",
",",
"SystemID",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlAddDtdEntity",
"(",
"self",
".",
"_o",
",",
"name",
",",
"type",
",",
"ExternalID",
",",
"Sys... | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4050-L4055 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/PhasedObject.py | python | PhasedObject.getAliasPhase | (self, alias) | return self.aliasPhaseMap.get(alias, alias) | Returns the phase number of an alias, if it exists.
Otherwise, returns the alias. | Returns the phase number of an alias, if it exists.
Otherwise, returns the alias. | [
"Returns",
"the",
"phase",
"number",
"of",
"an",
"alias",
"if",
"it",
"exists",
".",
"Otherwise",
"returns",
"the",
"alias",
"."
] | def getAliasPhase(self, alias):
"""
Returns the phase number of an alias, if it exists.
Otherwise, returns the alias.
"""
return self.aliasPhaseMap.get(alias, alias) | [
"def",
"getAliasPhase",
"(",
"self",
",",
"alias",
")",
":",
"return",
"self",
".",
"aliasPhaseMap",
".",
"get",
"(",
"alias",
",",
"alias",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/PhasedObject.py#L74-L79 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/Blast/Editor/Scripts/external/scripts/transformations.py | python | Arcball.matrix | (self) | return quaternion_matrix(self._qnow) | Return homogeneous rotation matrix. | Return homogeneous rotation matrix. | [
"Return",
"homogeneous",
"rotation",
"matrix",
"."
] | def matrix(self):
"""Return homogeneous rotation matrix."""
return quaternion_matrix(self._qnow) | [
"def",
"matrix",
"(",
"self",
")",
":",
"return",
"quaternion_matrix",
"(",
"self",
".",
"_qnow",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/Editor/Scripts/external/scripts/transformations.py#L1467-L1469 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/vendored/six.py | python | python_2_unicode_compatible | (klass) | return klass | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class. | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing. | [
"A",
"decorator",
"that",
"defines",
"__unicode__",
"and",
"__str__",
"methods",
"under",
"Python",
"2",
".",
"Under",
"Python",
"3",
"it",
"does",
"nothing",
"."
] | def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass | [
"def",
"python_2_unicode_compatible",
"(",
"klass",
")",
":",
"if",
"PY2",
":",
"if",
"'__str__'",
"not",
"in",
"klass",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"\"@python_2_unicode_compatible cannot be applied \"",
"\"to %s because it doesn't define __str__().\""... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/vendored/six.py#L828-L843 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/setup_multiversion/download.py | python | mkdir_p | (path) | Python equivalent of `mkdir -p`. | Python equivalent of `mkdir -p`. | [
"Python",
"equivalent",
"of",
"mkdir",
"-",
"p",
"."
] | def mkdir_p(path):
"""Python equivalent of `mkdir -p`."""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise | [
"def",
"mkdir_p",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")"... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/setup_multiversion/download.py#L107-L115 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/symbolic.py | python | _concat_hyper_shape | (sh1,sh2) | Describes the shape of the object where every primitive element of the type described by sh1
is replaced by an element of the type described by sh2. In other words, performs the Cartesian
product. | Describes the shape of the object where every primitive element of the type described by sh1
is replaced by an element of the type described by sh2. In other words, performs the Cartesian
product. | [
"Describes",
"the",
"shape",
"of",
"the",
"object",
"where",
"every",
"primitive",
"element",
"of",
"the",
"type",
"described",
"by",
"sh1",
"is",
"replaced",
"by",
"an",
"element",
"of",
"the",
"type",
"described",
"by",
"sh2",
".",
"In",
"other",
"words"... | def _concat_hyper_shape(sh1,sh2):
"""Describes the shape of the object where every primitive element of the type described by sh1
is replaced by an element of the type described by sh2. In other words, performs the Cartesian
product."""
if _is_numpy_shape(sh2):
if isinstance(sh1,(tuple,list,np.ndarray)):
return tuple(sh1) + tuple(sh2)
else:
assert isinstance(sh1,dict),"Erroneous hypershape object class "+sh1.__class__.__name__
res = {}
for (k,v) in sh1.iteritems():
res[k] = _concat_hyper_shape(v,sh2)
return res
else:
if isinstance(sh1,(tuple,list,np.ndarray)):
if len(sh1) == 0:
return sh2
elif len(sh1) == 1:
return dict((i,sh2) for i in xrange(sh1[0]))
else:
raise NotImplementedError("TODO: cartesian product of multidimensional hyper-shapes")
else:
assert isinstance(sh1,dict),"Erroneous hypershape object class "+sh1.__class__.__name__
res = {}
for (k,v) in sh1.iteritems():
res[k] = _concat_hyper_shape(v,sh2)
return res | [
"def",
"_concat_hyper_shape",
"(",
"sh1",
",",
"sh2",
")",
":",
"if",
"_is_numpy_shape",
"(",
"sh2",
")",
":",
"if",
"isinstance",
"(",
"sh1",
",",
"(",
"tuple",
",",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"return",
"tuple",
"(",
"sh1",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/symbolic.py#L964-L990 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py | python | FileNodeInfo.__getstate__ | (self) | return state | Return all fields that shall be pickled. Walk the slots in the class
hierarchy and add those to the state dictionary. If a '__dict__' slot is
available, copy all entries to the dictionary. Also include the version
id, which is fixed for all instances of a class. | Return all fields that shall be pickled. Walk the slots in the class
hierarchy and add those to the state dictionary. If a '__dict__' slot is
available, copy all entries to the dictionary. Also include the version
id, which is fixed for all instances of a class. | [
"Return",
"all",
"fields",
"that",
"shall",
"be",
"pickled",
".",
"Walk",
"the",
"slots",
"in",
"the",
"class",
"hierarchy",
"and",
"add",
"those",
"to",
"the",
"state",
"dictionary",
".",
"If",
"a",
"__dict__",
"slot",
"is",
"available",
"copy",
"all",
... | def __getstate__(self):
"""
Return all fields that shall be pickled. Walk the slots in the class
hierarchy and add those to the state dictionary. If a '__dict__' slot is
available, copy all entries to the dictionary. Also include the version
id, which is fixed for all instances of a class.
"""
state = getattr(self, '__dict__', {}).copy()
for obj in type(self).mro():
for name in getattr(obj,'__slots__',()):
if hasattr(self, name):
state[name] = getattr(self, name)
state['_version_id'] = self.current_version_id
try:
del state['__weakref__']
except KeyError:
pass
return state | [
"def",
"__getstate__",
"(",
"self",
")",
":",
"state",
"=",
"getattr",
"(",
"self",
",",
"'__dict__'",
",",
"{",
"}",
")",
".",
"copy",
"(",
")",
"for",
"obj",
"in",
"type",
"(",
"self",
")",
".",
"mro",
"(",
")",
":",
"for",
"name",
"in",
"get... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L2465-L2484 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | tools/rec2idx.py | python | IndexCreator.tell | (self) | return pos.value | Returns the current position of read head. | Returns the current position of read head. | [
"Returns",
"the",
"current",
"position",
"of",
"read",
"head",
"."
] | def tell(self):
"""Returns the current position of read head.
"""
pos = ctypes.c_size_t()
check_call(_LIB.MXRecordIOReaderTell(self.handle, ctypes.byref(pos)))
return pos.value | [
"def",
"tell",
"(",
"self",
")",
":",
"pos",
"=",
"ctypes",
".",
"c_size_t",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXRecordIOReaderTell",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"pos",
")",
")",
")",
"return",
"pos",
".",
... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/tools/rec2idx.py#L65-L70 | |
borglab/gtsam | a5bee157efce6a0563704bce6a5d188c29817f39 | python/gtsam/utils/plot.py | python | plot_pose2 | (
fignum: int,
pose: Pose2,
axis_length: float = 0.1,
covariance: np.ndarray = None,
axis_labels=("X axis", "Y axis", "Z axis"),
) | return fig | Plot a 2D pose on given figure with given `axis_length`.
Args:
fignum: Integer representing the figure number to use for plotting.
pose: The pose to be plotted.
axis_length: The length of the camera axes.
covariance: Marginal covariance matrix to plot
the uncertainty of the estimation.
axis_labels (iterable[string]): List of axis labels to set. | Plot a 2D pose on given figure with given `axis_length`. | [
"Plot",
"a",
"2D",
"pose",
"on",
"given",
"figure",
"with",
"given",
"axis_length",
"."
] | def plot_pose2(
fignum: int,
pose: Pose2,
axis_length: float = 0.1,
covariance: np.ndarray = None,
axis_labels=("X axis", "Y axis", "Z axis"),
) -> plt.Figure:
"""
Plot a 2D pose on given figure with given `axis_length`.
Args:
fignum: Integer representing the figure number to use for plotting.
pose: The pose to be plotted.
axis_length: The length of the camera axes.
covariance: Marginal covariance matrix to plot
the uncertainty of the estimation.
axis_labels (iterable[string]): List of axis labels to set.
"""
# get figure object
fig = plt.figure(fignum)
axes = fig.gca()
plot_pose2_on_axes(axes,
pose,
axis_length=axis_length,
covariance=covariance)
axes.set_xlabel(axis_labels[0])
axes.set_ylabel(axis_labels[1])
return fig | [
"def",
"plot_pose2",
"(",
"fignum",
":",
"int",
",",
"pose",
":",
"Pose2",
",",
"axis_length",
":",
"float",
"=",
"0.1",
",",
"covariance",
":",
"np",
".",
"ndarray",
"=",
"None",
",",
"axis_labels",
"=",
"(",
"\"X axis\"",
",",
"\"Y axis\"",
",",
"\"Z... | https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/python/gtsam/utils/plot.py#L224-L253 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/websocket-client/websocket.py | python | WebSocketApp.close | (self) | close websocket connection. | close websocket connection. | [
"close",
"websocket",
"connection",
"."
] | def close(self):
"""
close websocket connection.
"""
self.keep_running = False
self.sock.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"keep_running",
"=",
"False",
"self",
".",
"sock",
".",
"close",
"(",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/websocket-client/websocket.py#L815-L820 | ||
google/benchmark | d2cbd4b26abf77e799d96f868dcc3a0d9996d913 | tools/gbench/util.py | python | is_executable_file | (filename) | Return 'True' if 'filename' names a valid file which is likely
an executable. A file is considered an executable if it starts with the
magic bytes for a EXE, Mach O, or ELF file. | Return 'True' if 'filename' names a valid file which is likely
an executable. A file is considered an executable if it starts with the
magic bytes for a EXE, Mach O, or ELF file. | [
"Return",
"True",
"if",
"filename",
"names",
"a",
"valid",
"file",
"which",
"is",
"likely",
"an",
"executable",
".",
"A",
"file",
"is",
"considered",
"an",
"executable",
"if",
"it",
"starts",
"with",
"the",
"magic",
"bytes",
"for",
"a",
"EXE",
"Mach",
"O... | def is_executable_file(filename):
"""
Return 'True' if 'filename' names a valid file which is likely
an executable. A file is considered an executable if it starts with the
magic bytes for a EXE, Mach O, or ELF file.
"""
if not os.path.isfile(filename):
return False
with open(filename, mode='rb') as f:
magic_bytes = f.read(_num_magic_bytes)
if sys.platform == 'darwin':
return magic_bytes in [
b'\xfe\xed\xfa\xce', # MH_MAGIC
b'\xce\xfa\xed\xfe', # MH_CIGAM
b'\xfe\xed\xfa\xcf', # MH_MAGIC_64
b'\xcf\xfa\xed\xfe', # MH_CIGAM_64
b'\xca\xfe\xba\xbe', # FAT_MAGIC
b'\xbe\xba\xfe\xca' # FAT_CIGAM
]
elif sys.platform.startswith('win'):
return magic_bytes == b'MZ'
else:
return magic_bytes == b'\x7FELF' | [
"def",
"is_executable_file",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"False",
"with",
"open",
"(",
"filename",
",",
"mode",
"=",
"'rb'",
")",
"as",
"f",
":",
"magic_bytes",
"=",
"... | https://github.com/google/benchmark/blob/d2cbd4b26abf77e799d96f868dcc3a0d9996d913/tools/gbench/util.py#L18-L40 | ||
carla-simulator/carla | 8854804f4d7748e14d937ec763a2912823a7e5f5 | Co-Simulation/Sumo/sumo_integration/sumo_simulation.py | python | SumoSimulation.switch_off_traffic_lights | (self) | Switch off all traffic lights. | Switch off all traffic lights. | [
"Switch",
"off",
"all",
"traffic",
"lights",
"."
] | def switch_off_traffic_lights(self):
"""
Switch off all traffic lights.
"""
self.traffic_light_manager.switch_off() | [
"def",
"switch_off_traffic_lights",
"(",
"self",
")",
":",
"self",
".",
"traffic_light_manager",
".",
"switch_off",
"(",
")"
] | https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/Co-Simulation/Sumo/sumo_integration/sumo_simulation.py#L468-L472 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/meta.py | python | TrackingCodeGenerator.enter_frame | (self, frame) | Remember all undeclared identifiers. | Remember all undeclared identifiers. | [
"Remember",
"all",
"undeclared",
"identifiers",
"."
] | def enter_frame(self, frame):
"""Remember all undeclared identifiers."""
CodeGenerator.enter_frame(self, frame)
for _, (action, param) in iteritems(frame.symbols.loads):
if action == 'resolve':
self.undeclared_identifiers.add(param) | [
"def",
"enter_frame",
"(",
"self",
",",
"frame",
")",
":",
"CodeGenerator",
".",
"enter_frame",
"(",
"self",
",",
"frame",
")",
"for",
"_",
",",
"(",
"action",
",",
"param",
")",
"in",
"iteritems",
"(",
"frame",
".",
"symbols",
".",
"loads",
")",
":"... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/meta.py#L28-L33 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/core.py | python | CherryTree.text_selection_change_case | (self, change_type) | Change the Case of the Selected Text/the Underlying Word | Change the Case of the Selected Text/the Underlying Word | [
"Change",
"the",
"Case",
"of",
"the",
"Selected",
"Text",
"/",
"the",
"Underlying",
"Word"
] | def text_selection_change_case(self, change_type):
"""Change the Case of the Selected Text/the Underlying Word"""
text_view, text_buffer, syntax_highl, from_codebox = self.get_text_view_n_buffer_codebox_proof()
if not text_buffer: return
if not self.is_curr_node_not_read_only_or_error(): return
if not text_buffer.get_has_selection() and not support.apply_tag_try_automatic_bounds(self, text_buffer=text_buffer):
support.dialog_warning(_("No Text is Selected"), self.window)
return
iter_start, iter_end = text_buffer.get_selection_bounds()
if from_codebox or self.syntax_highlighting != cons.RICH_TEXT_ID:
text_to_change_case = text_buffer.get_text(iter_start, iter_end)
if change_type == "l": text_to_change_case = text_to_change_case.lower()
elif change_type == "u": text_to_change_case = text_to_change_case.upper()
elif change_type == "t": text_to_change_case = text_to_change_case.swapcase()
else:
rich_text = self.clipboard_handler.rich_text_get_from_text_buffer_selection(text_buffer,
iter_start,
iter_end,
change_case=change_type)
start_offset = iter_start.get_offset()
end_offset = iter_end.get_offset()
text_buffer.delete(iter_start, iter_end)
iter_insert = text_buffer.get_iter_at_offset(start_offset)
if from_codebox or self.syntax_highlighting != cons.RICH_TEXT_ID:
text_buffer.insert(iter_insert, text_to_change_case)
else:
text_buffer.move_mark(text_buffer.get_insert(), iter_insert)
self.clipboard_handler.from_xml_string_to_buffer(rich_text)
text_buffer.select_range(text_buffer.get_iter_at_offset(start_offset),
text_buffer.get_iter_at_offset(end_offset)) | [
"def",
"text_selection_change_case",
"(",
"self",
",",
"change_type",
")",
":",
"text_view",
",",
"text_buffer",
",",
"syntax_highl",
",",
"from_codebox",
"=",
"self",
".",
"get_text_view_n_buffer_codebox_proof",
"(",
")",
"if",
"not",
"text_buffer",
":",
"return",
... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L327-L356 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | PrintPreview.AdjustScrollbars | (*args, **kwargs) | return _windows_.PrintPreview_AdjustScrollbars(*args, **kwargs) | AdjustScrollbars(self, PreviewCanvas canvas) | AdjustScrollbars(self, PreviewCanvas canvas) | [
"AdjustScrollbars",
"(",
"self",
"PreviewCanvas",
"canvas",
")"
] | def AdjustScrollbars(*args, **kwargs):
"""AdjustScrollbars(self, PreviewCanvas canvas)"""
return _windows_.PrintPreview_AdjustScrollbars(*args, **kwargs) | [
"def",
"AdjustScrollbars",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintPreview_AdjustScrollbars",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L5625-L5627 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/depends.py | python | Require.is_current | (self, paths=None) | return self.version_ok(version) | Return true if dependency is present and up-to-date on 'paths | Return true if dependency is present and up-to-date on 'paths | [
"Return",
"true",
"if",
"dependency",
"is",
"present",
"and",
"up",
"-",
"to",
"-",
"date",
"on",
"paths"
] | def is_current(self, paths=None):
"""Return true if dependency is present and up-to-date on 'paths'"""
version = self.get_version(paths)
if version is None:
return False
return self.version_ok(version) | [
"def",
"is_current",
"(",
"self",
",",
"paths",
"=",
"None",
")",
":",
"version",
"=",
"self",
".",
"get_version",
"(",
"paths",
")",
"if",
"version",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"version_ok",
"(",
"version",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/depends.py#L74-L79 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/sharedexample.py | python | SharedExampleDocumenter._document | (self, section, value, comments, path, shape) | :param section: The section to add the docs to.
:param value: The input / output values representing the parameters that
are included in the example.
:param comments: The dictionary containing all the comments to be
applied to the example.
:param path: A list describing where the documenter is in traversing the
parameters. This is used to find the equivalent location
in the comments dictionary. | :param section: The section to add the docs to. | [
":",
"param",
"section",
":",
"The",
"section",
"to",
"add",
"the",
"docs",
"to",
"."
] | def _document(self, section, value, comments, path, shape):
"""
:param section: The section to add the docs to.
:param value: The input / output values representing the parameters that
are included in the example.
:param comments: The dictionary containing all the comments to be
applied to the example.
:param path: A list describing where the documenter is in traversing the
parameters. This is used to find the equivalent location
in the comments dictionary.
"""
if isinstance(value, dict):
self._document_dict(section, value, comments, path, shape)
elif isinstance(value, list):
self._document_list(section, value, comments, path, shape)
elif isinstance(value, numbers.Number):
self._document_number(section, value, path)
elif shape and shape.type_name == 'timestamp':
self._document_datetime(section, value, path)
else:
self._document_str(section, value, path) | [
"def",
"_document",
"(",
"self",
",",
"section",
",",
"value",
",",
"comments",
",",
"path",
",",
"shape",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"self",
".",
"_document_dict",
"(",
"section",
",",
"value",
",",
"comments",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/sharedexample.py#L74-L97 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32com/server/policy.py | python | CreateInstance | (clsid, reqIID) | return retObj._CreateInstance_(clsid, reqIID) | Create a new instance of the specified IID
The COM framework **always** calls this function to create a new
instance for the specified CLSID. This function looks up the
registry for the name of a policy, creates the policy, and asks the
policy to create the specified object by calling the _CreateInstance_ method.
Exactly how the policy creates the instance is up to the policy. See the
specific policy documentation for more details. | Create a new instance of the specified IID | [
"Create",
"a",
"new",
"instance",
"of",
"the",
"specified",
"IID"
] | def CreateInstance(clsid, reqIID):
"""Create a new instance of the specified IID
The COM framework **always** calls this function to create a new
instance for the specified CLSID. This function looks up the
registry for the name of a policy, creates the policy, and asks the
policy to create the specified object by calling the _CreateInstance_ method.
Exactly how the policy creates the instance is up to the policy. See the
specific policy documentation for more details.
"""
# First see is sys.path should have something on it.
try:
addnPaths = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT,
regAddnPath % clsid).split(';')
for newPath in addnPaths:
if newPath not in sys.path:
sys.path.insert(0, newPath)
except win32api.error:
pass
try:
policy = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT,
regPolicy % clsid)
policy = resolve_func(policy)
except win32api.error:
policy = DefaultPolicy
try:
dispatcher = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT,
regDispatcher % clsid)
if dispatcher: dispatcher = resolve_func(dispatcher)
except win32api.error:
dispatcher = None
if dispatcher:
retObj = dispatcher(policy, None)
else:
retObj = policy(None)
return retObj._CreateInstance_(clsid, reqIID) | [
"def",
"CreateInstance",
"(",
"clsid",
",",
"reqIID",
")",
":",
"# First see is sys.path should have something on it.",
"try",
":",
"addnPaths",
"=",
"win32api",
".",
"RegQueryValue",
"(",
"win32con",
".",
"HKEY_CLASSES_ROOT",
",",
"regAddnPath",
"%",
"clsid",
")",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32com/server/policy.py#L98-L136 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/utils/check_cfc/check_cfc.py | python | is_normal_compile | (args) | return compile_step and not bitcode and not query and not dependency and input_is_valid | Check if this is a normal compile which will output an object file rather
than a preprocess or link. args is a list of command line arguments. | Check if this is a normal compile which will output an object file rather
than a preprocess or link. args is a list of command line arguments. | [
"Check",
"if",
"this",
"is",
"a",
"normal",
"compile",
"which",
"will",
"output",
"an",
"object",
"file",
"rather",
"than",
"a",
"preprocess",
"or",
"link",
".",
"args",
"is",
"a",
"list",
"of",
"command",
"line",
"arguments",
"."
] | def is_normal_compile(args):
"""Check if this is a normal compile which will output an object file rather
than a preprocess or link. args is a list of command line arguments."""
compile_step = '-c' in args
# Bitcode cannot be disassembled in the same way
bitcode = '-flto' in args or '-emit-llvm' in args
# Version and help are queries of the compiler and override -c if specified
query = '--version' in args or '--help' in args
# Options to output dependency files for make
dependency = '-M' in args or '-MM' in args
# Check if the input is recognised as a source file (this may be too
# strong a restriction)
input_is_valid = bool(get_input_file(args))
return compile_step and not bitcode and not query and not dependency and input_is_valid | [
"def",
"is_normal_compile",
"(",
"args",
")",
":",
"compile_step",
"=",
"'-c'",
"in",
"args",
"# Bitcode cannot be disassembled in the same way",
"bitcode",
"=",
"'-flto'",
"in",
"args",
"or",
"'-emit-llvm'",
"in",
"args",
"# Version and help are queries of the compiler and... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/utils/check_cfc/check_cfc.py#L217-L230 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetExtraPlistItems | (self, configname=None) | return items | Returns a dictionary with extra items to insert into Info.plist. | Returns a dictionary with extra items to insert into Info.plist. | [
"Returns",
"a",
"dictionary",
"with",
"extra",
"items",
"to",
"insert",
"into",
"Info",
".",
"plist",
"."
] | def GetExtraPlistItems(self, configname=None):
"""Returns a dictionary with extra items to insert into Info.plist."""
if configname not in XcodeSettings._plist_cache:
cache = {}
cache['BuildMachineOSBuild'] = self._BuildMachineOSBuild()
xcode_version, xcode_build = XcodeVersion()
cache['DTXcode'] = xcode_version
cache['DTXcodeBuild'] = xcode_build
compiler = self.xcode_settings[configname].get('GCC_VERSION')
if compiler is not None:
cache['DTCompiler'] = compiler
sdk_root = self._SdkRoot(configname)
if not sdk_root:
sdk_root = self._DefaultSdkRoot()
sdk_version = self._GetSdkVersionInfoItem(sdk_root, '--show-sdk-version')
cache['DTSDKName'] = sdk_root + (sdk_version or '')
if xcode_version >= '0720':
cache['DTSDKBuild'] = self._GetSdkVersionInfoItem(
sdk_root, '--show-sdk-build-version')
elif xcode_version >= '0430':
cache['DTSDKBuild'] = sdk_version
else:
cache['DTSDKBuild'] = cache['BuildMachineOSBuild']
if self.isIOS:
cache['MinimumOSVersion'] = self.xcode_settings[configname].get(
'IPHONEOS_DEPLOYMENT_TARGET')
cache['DTPlatformName'] = sdk_root
cache['DTPlatformVersion'] = sdk_version
if configname.endswith("iphoneos"):
cache['CFBundleSupportedPlatforms'] = ['iPhoneOS']
cache['DTPlatformBuild'] = cache['DTSDKBuild']
else:
cache['CFBundleSupportedPlatforms'] = ['iPhoneSimulator']
# This is weird, but Xcode sets DTPlatformBuild to an empty field
# for simulator builds.
cache['DTPlatformBuild'] = ""
XcodeSettings._plist_cache[configname] = cache
# Include extra plist items that are per-target, not per global
# XcodeSettings.
items = dict(XcodeSettings._plist_cache[configname])
if self.isIOS:
items['UIDeviceFamily'] = self._XcodeIOSDeviceFamily(configname)
return items | [
"def",
"GetExtraPlistItems",
"(",
"self",
",",
"configname",
"=",
"None",
")",
":",
"if",
"configname",
"not",
"in",
"XcodeSettings",
".",
"_plist_cache",
":",
"cache",
"=",
"{",
"}",
"cache",
"[",
"'BuildMachineOSBuild'",
"]",
"=",
"self",
".",
"_BuildMachi... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/xcode_emulation.py#L1204-L1251 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/ma/mrecords.py | python | MaskedRecords.tolist | (self, fill_value=None) | return result.tolist() | Return the data portion of the array as a list.
Data items are converted to the nearest compatible Python type.
Masked values are converted to fill_value. If fill_value is None,
the corresponding entries in the output list will be ``None``. | Return the data portion of the array as a list. | [
"Return",
"the",
"data",
"portion",
"of",
"the",
"array",
"as",
"a",
"list",
"."
] | def tolist(self, fill_value=None):
"""
Return the data portion of the array as a list.
Data items are converted to the nearest compatible Python type.
Masked values are converted to fill_value. If fill_value is None,
the corresponding entries in the output list will be ``None``.
"""
if fill_value is not None:
return self.filled(fill_value).tolist()
result = narray(self.filled().tolist(), dtype=object)
mask = narray(self._mask.tolist())
result[mask] = None
return result.tolist() | [
"def",
"tolist",
"(",
"self",
",",
"fill_value",
"=",
"None",
")",
":",
"if",
"fill_value",
"is",
"not",
"None",
":",
"return",
"self",
".",
"filled",
"(",
"fill_value",
")",
".",
"tolist",
"(",
")",
"result",
"=",
"narray",
"(",
"self",
".",
"filled... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/mrecords.py#L427-L441 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/ide/activegrid/util/utillang.py | python | toUnicode | (value) | return value | Converts all strings non-string values to unicode.
This assumes string instances are encoded in utf-8.
Note that us-ascii is a subset of utf-8. | Converts all strings non-string values to unicode.
This assumes string instances are encoded in utf-8.
Note that us-ascii is a subset of utf-8. | [
"Converts",
"all",
"strings",
"non",
"-",
"string",
"values",
"to",
"unicode",
".",
"This",
"assumes",
"string",
"instances",
"are",
"encoded",
"in",
"utf",
"-",
"8",
".",
"Note",
"that",
"us",
"-",
"ascii",
"is",
"a",
"subset",
"of",
"utf",
"-",
"8",
... | def toUnicode(value):
"""
Converts all strings non-string values to unicode.
This assumes string instances are encoded in utf-8.
Note that us-ascii is a subset of utf-8.
"""
if not isinstance(value, unicode):
if not isinstance(value, str):
return unicode(value)
return unicode(value, 'utf-8')
return value | [
"def",
"toUnicode",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"unicode",
"(",
"value",
")",
"return",
"unicode",
"(",
"value",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/util/utillang.py#L61-L71 | |
apache/trafodion | 8455c839ad6b6d7b6e04edda5715053095b78046 | install/python-installer/db_install.py | python | UserInput.notify_user | (self) | show the final configs to user | show the final configs to user | [
"show",
"the",
"final",
"configs",
"to",
"user"
] | def notify_user(self):
""" show the final configs to user """
format_output('Final Configs')
title = ['config type', 'value']
pt = PrettyTable(title)
for item in title:
pt.align[item] = 'l'
for key, value in sorted(cfgs.items()):
# only notify user input value
if self.in_data.has_key(key) and value:
if self.in_data[key].has_key('ispasswd'): continue
pt.add_row([key, value])
print pt
confirm = self.get_confirm()
if confirm != 'Y':
if os.path.exists(DBCFG_FILE): os.remove(DBCFG_FILE)
run_cmd('rm -rf %s/*.status' % INSTALLER_LOC)
log_err('User quit') | [
"def",
"notify_user",
"(",
"self",
")",
":",
"format_output",
"(",
"'Final Configs'",
")",
"title",
"=",
"[",
"'config type'",
",",
"'value'",
"]",
"pt",
"=",
"PrettyTable",
"(",
"title",
")",
"for",
"item",
"in",
"title",
":",
"pt",
".",
"align",
"[",
... | https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/install/python-installer/db_install.py#L164-L182 | ||
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/google/protobuf/internal/containers.py | python | BaseContainer.__len__ | (self) | return len(self._values) | Returns the number of elements in the container. | Returns the number of elements in the container. | [
"Returns",
"the",
"number",
"of",
"elements",
"in",
"the",
"container",
"."
] | def __len__(self):
"""Returns the number of elements in the container."""
return len(self._values) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_values",
")"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/internal/containers.py#L206-L208 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/insights/module.py | python | Module._health_prune_history | (self, hours) | Prune old health entries | Prune old health entries | [
"Prune",
"old",
"health",
"entries"
] | def _health_prune_history(self, hours):
"""Prune old health entries"""
cutoff = datetime.datetime.utcnow() - datetime.timedelta(hours=hours)
for key in self._health_filter(lambda ts: ts <= cutoff):
self.log.info("Removing old health slot key {}".format(key))
self.set_store(key, None)
if not hours:
self._health_slot = health_util.HealthHistorySlot() | [
"def",
"_health_prune_history",
"(",
"self",
",",
"hours",
")",
":",
"cutoff",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"hours",
")",
"for",
"key",
"in",
"self",
".",
"_health_filter... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/insights/module.py#L137-L144 | ||
cinder/Cinder | e83f5bb9c01a63eec20168d02953a0879e5100f7 | docs/libs/markdown/extensions/attr_list.py | python | get_attrs | (str) | return _scanner.scan(str)[0] | Parse attribute list and return a list of attribute tuples. | Parse attribute list and return a list of attribute tuples. | [
"Parse",
"attribute",
"list",
"and",
"return",
"a",
"list",
"of",
"attribute",
"tuples",
"."
] | def get_attrs(str):
""" Parse attribute list and return a list of attribute tuples. """
return _scanner.scan(str)[0] | [
"def",
"get_attrs",
"(",
"str",
")",
":",
"return",
"_scanner",
".",
"scan",
"(",
"str",
")",
"[",
"0",
"]"
] | https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/libs/markdown/extensions/attr_list.py#L64-L66 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/autograd/profiler_util.py | python | EventList.total_average | (self) | return total_stat | Averages all events.
Returns:
A FunctionEventAvg object. | Averages all events. | [
"Averages",
"all",
"events",
"."
] | def total_average(self):
"""Averages all events.
Returns:
A FunctionEventAvg object.
"""
total_stat = FunctionEventAvg()
for evt in self:
total_stat += evt
total_stat.key = None
total_stat.key = 'Total'
return total_stat | [
"def",
"total_average",
"(",
"self",
")",
":",
"total_stat",
"=",
"FunctionEventAvg",
"(",
")",
"for",
"evt",
"in",
"self",
":",
"total_stat",
"+=",
"evt",
"total_stat",
".",
"key",
"=",
"None",
"total_stat",
".",
"key",
"=",
"'Total'",
"return",
"total_st... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/autograd/profiler_util.py#L290-L301 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/mesh.py | python | ComputedTag.__init__ | (self, f, mesh=None, name=None, doc=None) | Parameters
----------
f : callable object
The function that performs the computation.
mesh : Mesh, optional
The PyNE mesh to tag.
name : str, optional
The name of the tag.
doc : str, optional
Documentation string for the tag. | Parameters
----------
f : callable object
The function that performs the computation.
mesh : Mesh, optional
The PyNE mesh to tag.
name : str, optional
The name of the tag.
doc : str, optional
Documentation string for the tag. | [
"Parameters",
"----------",
"f",
":",
"callable",
"object",
"The",
"function",
"that",
"performs",
"the",
"computation",
".",
"mesh",
":",
"Mesh",
"optional",
"The",
"PyNE",
"mesh",
"to",
"tag",
".",
"name",
":",
"str",
"optional",
"The",
"name",
"of",
"th... | def __init__(self, f, mesh=None, name=None, doc=None):
"""Parameters
----------
f : callable object
The function that performs the computation.
mesh : Mesh, optional
The PyNE mesh to tag.
name : str, optional
The name of the tag.
doc : str, optional
Documentation string for the tag.
"""
doc = doc or f.__doc__
super(ComputedTag, self).__init__(mesh=mesh, name=name, doc=doc)
if mesh is None or name is None:
self._lazy_args['f'] = f
return
self.f = f | [
"def",
"__init__",
"(",
"self",
",",
"f",
",",
"mesh",
"=",
"None",
",",
"name",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"doc",
"=",
"doc",
"or",
"f",
".",
"__doc__",
"super",
"(",
"ComputedTag",
",",
"self",
")",
".",
"__init__",
"(",
... | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/mesh.py#L686-L704 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_array_simple.py | python | LinkArray.Activated | (self) | Execute when the command is called. | Execute when the command is called. | [
"Execute",
"when",
"the",
"command",
"is",
"called",
"."
] | def Activated(self):
"""Execute when the command is called."""
super(LinkArray, self).Activated(name="Link array") | [
"def",
"Activated",
"(",
"self",
")",
":",
"super",
"(",
"LinkArray",
",",
"self",
")",
".",
"Activated",
"(",
"name",
"=",
"\"Link array\"",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_array_simple.py#L122-L124 | ||
NervanaSystems/ngraph | f677a119765ca30636cf407009dabd118664951f | python/src/ngraph/utils/types.py | python | get_ndarray | (data: NumericData) | return np.array(data) | Wrap data into a numpy ndarray. | Wrap data into a numpy ndarray. | [
"Wrap",
"data",
"into",
"a",
"numpy",
"ndarray",
"."
] | def get_ndarray(data: NumericData) -> np.ndarray:
"""Wrap data into a numpy ndarray."""
if type(data) == np.ndarray:
return data
return np.array(data) | [
"def",
"get_ndarray",
"(",
"data",
":",
"NumericData",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"type",
"(",
"data",
")",
"==",
"np",
".",
"ndarray",
":",
"return",
"data",
"return",
"np",
".",
"array",
"(",
"data",
")"
] | https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/utils/types.py#L120-L124 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/findertools.py | python | comment | (object, comment=None) | comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window. | comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window. | [
"comment",
":",
"get",
"or",
"set",
"the",
"Finder",
"-",
"comment",
"of",
"the",
"item",
"displayed",
"in",
"the",
"Get",
"Info",
"window",
"."
] | def comment(object, comment=None):
"""comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window."""
object = Carbon.File.FSRef(object)
object_alias = object.FSNewAliasMinimal()
if comment is None:
return _getcomment(object_alias)
else:
return _setcomment(object_alias, comment) | [
"def",
"comment",
"(",
"object",
",",
"comment",
"=",
"None",
")",
":",
"object",
"=",
"Carbon",
".",
"File",
".",
"FSRef",
"(",
"object",
")",
"object_alias",
"=",
"object",
".",
"FSNewAliasMinimal",
"(",
")",
"if",
"comment",
"is",
"None",
":",
"retu... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/findertools.py#L128-L135 | ||
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/cef_parser.py | python | format_translation_changes | (old, new) | return result | Return a comment stating what is different between the old and new
function prototype parts. | Return a comment stating what is different between the old and new
function prototype parts. | [
"Return",
"a",
"comment",
"stating",
"what",
"is",
"different",
"between",
"the",
"old",
"and",
"new",
"function",
"prototype",
"parts",
"."
] | def format_translation_changes(old, new):
""" Return a comment stating what is different between the old and new
function prototype parts.
"""
changed = False
result = ''
# normalize C API attributes
oldargs = [x.replace('struct _', '') for x in old['args']]
oldretval = old['retval'].replace('struct _', '')
newargs = [x.replace('struct _', '') for x in new['args']]
newretval = new['retval'].replace('struct _', '')
# check if the prototype has changed
oldset = set(oldargs)
newset = set(newargs)
if len(oldset.symmetric_difference(newset)) > 0:
changed = True
result += '\n // WARNING - CHANGED ATTRIBUTES'
# in the implementation set only
oldonly = oldset.difference(newset)
for arg in oldonly:
result += '\n // REMOVED: ' + arg
# in the current set only
newonly = newset.difference(oldset)
for arg in newonly:
result += '\n // ADDED: ' + arg
# check if the return value has changed
if oldretval != newretval:
changed = True
result += '\n // WARNING - CHANGED RETURN VALUE'+ \
'\n // WAS: '+old['retval']+ \
'\n // NOW: '+new['retval']
if changed:
result += '\n #pragma message("Warning: "__FILE__": '+new['name']+ \
' prototype has changed")\n'
return result | [
"def",
"format_translation_changes",
"(",
"old",
",",
"new",
")",
":",
"changed",
"=",
"False",
"result",
"=",
"''",
"# normalize C API attributes",
"oldargs",
"=",
"[",
"x",
".",
"replace",
"(",
"'struct _'",
",",
"''",
")",
"for",
"x",
"in",
"old",
"[",
... | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/cef_parser.py#L212-L253 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/internals/blocks.py | python | NonConsolidatableMixIn._get_unstack_items | (self, unstacker, new_columns) | return new_placement, new_values, mask | Get the placement, values, and mask for a Block unstack.
This is shared between ObjectBlock and ExtensionBlock. They
differ in that ObjectBlock passes the values, while ExtensionBlock
passes the dummy ndarray of positions to be used by a take
later.
Parameters
----------
unstacker : pandas.core.reshape.reshape._Unstacker
new_columns : Index
All columns of the unstacked BlockManager.
Returns
-------
new_placement : ndarray[int]
The placement of the new columns in `new_columns`.
new_values : Union[ndarray, ExtensionArray]
The first return value from _Unstacker.get_new_values.
mask : ndarray[bool]
The second return value from _Unstacker.get_new_values. | Get the placement, values, and mask for a Block unstack. | [
"Get",
"the",
"placement",
"values",
"and",
"mask",
"for",
"a",
"Block",
"unstack",
"."
] | def _get_unstack_items(self, unstacker, new_columns):
"""
Get the placement, values, and mask for a Block unstack.
This is shared between ObjectBlock and ExtensionBlock. They
differ in that ObjectBlock passes the values, while ExtensionBlock
passes the dummy ndarray of positions to be used by a take
later.
Parameters
----------
unstacker : pandas.core.reshape.reshape._Unstacker
new_columns : Index
All columns of the unstacked BlockManager.
Returns
-------
new_placement : ndarray[int]
The placement of the new columns in `new_columns`.
new_values : Union[ndarray, ExtensionArray]
The first return value from _Unstacker.get_new_values.
mask : ndarray[bool]
The second return value from _Unstacker.get_new_values.
"""
# shared with ExtensionBlock
new_items = unstacker.get_new_columns()
new_placement = new_columns.get_indexer(new_items)
new_values, mask = unstacker.get_new_values()
mask = mask.any(0)
return new_placement, new_values, mask | [
"def",
"_get_unstack_items",
"(",
"self",
",",
"unstacker",
",",
"new_columns",
")",
":",
"# shared with ExtensionBlock",
"new_items",
"=",
"unstacker",
".",
"get_new_columns",
"(",
")",
"new_placement",
"=",
"new_columns",
".",
"get_indexer",
"(",
"new_items",
")",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/internals/blocks.py#L1679-L1709 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | RigidObjectModel.getVelocity | (self) | return _robotsim.RigidObjectModel_getVelocity(self) | getVelocity(RigidObjectModel self)
Retrieves the (angular velocity, velocity) of the rigid object.
Returns:
(tuple): a pair of 3-lists (w,v) where w is the angular velocity
vector and v is the translational velocity vector (both in world
coordinates) | getVelocity(RigidObjectModel self) | [
"getVelocity",
"(",
"RigidObjectModel",
"self",
")"
] | def getVelocity(self):
"""
getVelocity(RigidObjectModel self)
Retrieves the (angular velocity, velocity) of the rigid object.
Returns:
(tuple): a pair of 3-lists (w,v) where w is the angular velocity
vector and v is the translational velocity vector (both in world
coordinates)
"""
return _robotsim.RigidObjectModel_getVelocity(self) | [
"def",
"getVelocity",
"(",
"self",
")",
":",
"return",
"_robotsim",
".",
"RigidObjectModel_getVelocity",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L5485-L5500 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/_pyio.py | python | IOBase.isatty | (self) | return False | Return a bool indicating whether this is an 'interactive' stream.
Return False if it can't be determined. | Return a bool indicating whether this is an 'interactive' stream. | [
"Return",
"a",
"bool",
"indicating",
"whether",
"this",
"is",
"an",
"interactive",
"stream",
"."
] | def isatty(self):
"""Return a bool indicating whether this is an 'interactive' stream.
Return False if it can't be determined.
"""
self._checkClosed()
return False | [
"def",
"isatty",
"(",
"self",
")",
":",
"self",
".",
"_checkClosed",
"(",
")",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pyio.py#L515-L521 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/MythTV/dataheap.py | python | Video.getHash | (self) | return hash | Video.getHash() -> file hash | Video.getHash() -> file hash | [
"Video",
".",
"getHash",
"()",
"-",
">",
"file",
"hash"
] | def getHash(self):
"""Video.getHash() -> file hash"""
if self.host is None:
return None
be = FileOps(db=self._db)
hash = be.getHash(self.filename, 'Videos', self.host)
return hash | [
"def",
"getHash",
"(",
"self",
")",
":",
"if",
"self",
".",
"host",
"is",
"None",
":",
"return",
"None",
"be",
"=",
"FileOps",
"(",
"db",
"=",
"self",
".",
"_db",
")",
"hash",
"=",
"be",
".",
"getHash",
"(",
"self",
".",
"filename",
",",
"'Videos... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/dataheap.py#L1007-L1013 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/training/moving_averages.py | python | ExponentialMovingAverage.__init__ | (self, decay, num_updates=None, name="ExponentialMovingAverage") | Creates a new ExponentialMovingAverage object.
The `apply()` method has to be called to create shadow variables and add
ops to maintain moving averages.
The optional `num_updates` parameter allows one to tweak the decay rate
dynamically. . It is typical to pass the count of training steps, usually
kept in a variable that is incremented at each step, in which case the
decay rate is lower at the start of training. This makes moving averages
move faster. If passed, the actual decay rate used is:
`min(decay, (1 + num_updates) / (10 + num_updates))`
Args:
decay: Float. The decay to use.
num_updates: Optional count of number of updates applied to variables.
name: String. Optional prefix name to use for the name of ops added in
`apply()`. | Creates a new ExponentialMovingAverage object. | [
"Creates",
"a",
"new",
"ExponentialMovingAverage",
"object",
"."
] | def __init__(self, decay, num_updates=None, name="ExponentialMovingAverage"):
"""Creates a new ExponentialMovingAverage object.
The `apply()` method has to be called to create shadow variables and add
ops to maintain moving averages.
The optional `num_updates` parameter allows one to tweak the decay rate
dynamically. . It is typical to pass the count of training steps, usually
kept in a variable that is incremented at each step, in which case the
decay rate is lower at the start of training. This makes moving averages
move faster. If passed, the actual decay rate used is:
`min(decay, (1 + num_updates) / (10 + num_updates))`
Args:
decay: Float. The decay to use.
num_updates: Optional count of number of updates applied to variables.
name: String. Optional prefix name to use for the name of ops added in
`apply()`.
"""
self._decay = decay
self._num_updates = num_updates
self._name = name
self._averages = {} | [
"def",
"__init__",
"(",
"self",
",",
"decay",
",",
"num_updates",
"=",
"None",
",",
"name",
"=",
"\"ExponentialMovingAverage\"",
")",
":",
"self",
".",
"_decay",
"=",
"decay",
"self",
".",
"_num_updates",
"=",
"num_updates",
"self",
".",
"_name",
"=",
"nam... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/moving_averages.py#L210-L233 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/module/executor_group.py | python | _load_data | (batch, targets, major_axis) | Load data into sliced arrays. | Load data into sliced arrays. | [
"Load",
"data",
"into",
"sliced",
"arrays",
"."
] | def _load_data(batch, targets, major_axis):
"""Load data into sliced arrays."""
_load_general(batch.data, targets, major_axis) | [
"def",
"_load_data",
"(",
"batch",
",",
"targets",
",",
"major_axis",
")",
":",
"_load_general",
"(",
"batch",
".",
"data",
",",
"targets",
",",
"major_axis",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/module/executor_group.py#L65-L67 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | TreeCtrl._setCallbackInfo | (*args, **kwargs) | return _controls_.TreeCtrl__setCallbackInfo(*args, **kwargs) | _setCallbackInfo(self, PyObject self, PyObject _class) | _setCallbackInfo(self, PyObject self, PyObject _class) | [
"_setCallbackInfo",
"(",
"self",
"PyObject",
"self",
"PyObject",
"_class",
")"
] | def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _controls_.TreeCtrl__setCallbackInfo(*args, **kwargs) | [
"def",
"_setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl__setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5212-L5214 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/zeros.py | python | toms748 | (f, a, b, args=(), k=1,
xtol=_xtol, rtol=_rtol, maxiter=_iter,
full_output=False, disp=True) | return _results_select(full_output, (x, function_calls, iterations, flag)) | Find a zero using TOMS Algorithm 748 method.
Implements the Algorithm 748 method of Alefeld, Potro and Shi to find a
zero of the function `f` on the interval `[a , b]`, where `f(a)` and
`f(b)` must have opposite signs.
It uses a mixture of inverse cubic interpolation and
"Newton-quadratic" steps. [APS1995].
Parameters
----------
f : function
Python function returning a scalar. The function :math:`f`
must be continuous, and :math:`f(a)` and :math:`f(b)`
have opposite signs.
a : scalar,
lower boundary of the search interval
b : scalar,
upper boundary of the search interval
args : tuple, optional
containing extra arguments for the function `f`.
`f` is called by ``f(x, *args)``.
k : int, optional
The number of Newton quadratic steps to perform each iteration. ``k>=1``.
xtol : scalar, optional
The computed root ``x0`` will satisfy ``np.allclose(x, x0,
atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
parameter must be nonnegative.
rtol : scalar, optional
The computed root ``x0`` will satisfy ``np.allclose(x, x0,
atol=xtol, rtol=rtol)``, where ``x`` is the exact root.
maxiter : int, optional
if convergence is not achieved in `maxiter` iterations, an error is
raised. Must be >= 0.
full_output : bool, optional
If `full_output` is False, the root is returned. If `full_output` is
True, the return value is ``(x, r)``, where `x` is the root, and `r` is
a `RootResults` object.
disp : bool, optional
If True, raise RuntimeError if the algorithm didn't converge.
Otherwise the convergence status is recorded in the `RootResults`
return object.
Returns
-------
x0 : float
Approximate Zero of `f`
r : `RootResults` (present if ``full_output = True``)
Object containing information about the convergence. In particular,
``r.converged`` is True if the routine converged.
See Also
--------
brentq, brenth, ridder, bisect, newton
fsolve : find zeroes in n dimensions.
Notes
-----
`f` must be continuous.
Algorithm 748 with ``k=2`` is asymptotically the most efficient
algorithm known for finding roots of a four times continuously
differentiable function.
In contrast with Brent's algorithm, which may only decrease the length of
the enclosing bracket on the last step, Algorithm 748 decreases it each
iteration with the same asymptotic efficiency as it finds the root.
For easy statement of efficiency indices, assume that `f` has 4
continuouous deriviatives.
For ``k=1``, the convergence order is at least 2.7, and with about
asymptotically 2 function evaluations per iteration, the efficiency
index is approximately 1.65.
For ``k=2``, the order is about 4.6 with asymptotically 3 function
evaluations per iteration, and the efficiency index 1.66.
For higher values of `k`, the efficiency index approaches
the `k`-th root of ``(3k-2)``, hence ``k=1`` or ``k=2`` are
usually appropriate.
References
----------
.. [APS1995]
Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
*Algorithm 748: Enclosing Zeros of Continuous Functions*,
ACM Trans. Math. Softw. Volume 221(1995)
doi = {10.1145/210089.210111}
Examples
--------
>>> def f(x):
... return (x**3 - 1) # only one real root at x = 1
>>> from scipy import optimize
>>> root, results = optimize.toms748(f, 0, 2, full_output=True)
>>> root
1.0
>>> results
converged: True
flag: 'converged'
function_calls: 11
iterations: 5
root: 1.0 | Find a zero using TOMS Algorithm 748 method. | [
"Find",
"a",
"zero",
"using",
"TOMS",
"Algorithm",
"748",
"method",
"."
] | def toms748(f, a, b, args=(), k=1,
xtol=_xtol, rtol=_rtol, maxiter=_iter,
full_output=False, disp=True):
"""
Find a zero using TOMS Algorithm 748 method.
Implements the Algorithm 748 method of Alefeld, Potro and Shi to find a
zero of the function `f` on the interval `[a , b]`, where `f(a)` and
`f(b)` must have opposite signs.
It uses a mixture of inverse cubic interpolation and
"Newton-quadratic" steps. [APS1995].
Parameters
----------
f : function
Python function returning a scalar. The function :math:`f`
must be continuous, and :math:`f(a)` and :math:`f(b)`
have opposite signs.
a : scalar,
lower boundary of the search interval
b : scalar,
upper boundary of the search interval
args : tuple, optional
containing extra arguments for the function `f`.
`f` is called by ``f(x, *args)``.
k : int, optional
The number of Newton quadratic steps to perform each iteration. ``k>=1``.
xtol : scalar, optional
The computed root ``x0`` will satisfy ``np.allclose(x, x0,
atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
parameter must be nonnegative.
rtol : scalar, optional
The computed root ``x0`` will satisfy ``np.allclose(x, x0,
atol=xtol, rtol=rtol)``, where ``x`` is the exact root.
maxiter : int, optional
if convergence is not achieved in `maxiter` iterations, an error is
raised. Must be >= 0.
full_output : bool, optional
If `full_output` is False, the root is returned. If `full_output` is
True, the return value is ``(x, r)``, where `x` is the root, and `r` is
a `RootResults` object.
disp : bool, optional
If True, raise RuntimeError if the algorithm didn't converge.
Otherwise the convergence status is recorded in the `RootResults`
return object.
Returns
-------
x0 : float
Approximate Zero of `f`
r : `RootResults` (present if ``full_output = True``)
Object containing information about the convergence. In particular,
``r.converged`` is True if the routine converged.
See Also
--------
brentq, brenth, ridder, bisect, newton
fsolve : find zeroes in n dimensions.
Notes
-----
`f` must be continuous.
Algorithm 748 with ``k=2`` is asymptotically the most efficient
algorithm known for finding roots of a four times continuously
differentiable function.
In contrast with Brent's algorithm, which may only decrease the length of
the enclosing bracket on the last step, Algorithm 748 decreases it each
iteration with the same asymptotic efficiency as it finds the root.
For easy statement of efficiency indices, assume that `f` has 4
continuouous deriviatives.
For ``k=1``, the convergence order is at least 2.7, and with about
asymptotically 2 function evaluations per iteration, the efficiency
index is approximately 1.65.
For ``k=2``, the order is about 4.6 with asymptotically 3 function
evaluations per iteration, and the efficiency index 1.66.
For higher values of `k`, the efficiency index approaches
the `k`-th root of ``(3k-2)``, hence ``k=1`` or ``k=2`` are
usually appropriate.
References
----------
.. [APS1995]
Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
*Algorithm 748: Enclosing Zeros of Continuous Functions*,
ACM Trans. Math. Softw. Volume 221(1995)
doi = {10.1145/210089.210111}
Examples
--------
>>> def f(x):
... return (x**3 - 1) # only one real root at x = 1
>>> from scipy import optimize
>>> root, results = optimize.toms748(f, 0, 2, full_output=True)
>>> root
1.0
>>> results
converged: True
flag: 'converged'
function_calls: 11
iterations: 5
root: 1.0
"""
if xtol <= 0:
raise ValueError("xtol too small (%g <= 0)" % xtol)
if rtol < _rtol / 4:
raise ValueError("rtol too small (%g < %g)" % (rtol, _rtol))
if maxiter < 1:
raise ValueError("maxiter must be greater than 0")
if not np.isfinite(a):
raise ValueError("a is not finite %s" % a)
if not np.isfinite(b):
raise ValueError("b is not finite %s" % b)
if a >= b:
raise ValueError("a and b are not an interval [%d, %d]" % (a, b))
if not k >= 1:
raise ValueError("k too small (%s < 1)" % k)
if not isinstance(args, tuple):
args = (args,)
solver = TOMS748Solver()
result = solver.solve(f, a, b, args=args, k=k, xtol=xtol, rtol=rtol,
maxiter=maxiter, disp=disp)
x, function_calls, iterations, flag = result
return _results_select(full_output, (x, function_calls, iterations, flag)) | [
"def",
"toms748",
"(",
"f",
",",
"a",
",",
"b",
",",
"args",
"=",
"(",
")",
",",
"k",
"=",
"1",
",",
"xtol",
"=",
"_xtol",
",",
"rtol",
"=",
"_rtol",
",",
"maxiter",
"=",
"_iter",
",",
"full_output",
"=",
"False",
",",
"disp",
"=",
"True",
")... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/zeros.py#L1218-L1344 | |
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/utils/lit/lit/util.py | python | to_bytes | (s) | return s.encode('utf-8') | Return the parameter as type 'bytes', possibly encoding it.
In Python2, the 'bytes' type is the same as 'str'. In Python3, they
are distinct. | Return the parameter as type 'bytes', possibly encoding it. | [
"Return",
"the",
"parameter",
"as",
"type",
"bytes",
"possibly",
"encoding",
"it",
"."
] | def to_bytes(s):
"""Return the parameter as type 'bytes', possibly encoding it.
In Python2, the 'bytes' type is the same as 'str'. In Python3, they
are distinct.
"""
if isinstance(s, bytes):
# In Python2, this branch is taken for both 'str' and 'bytes'.
# In Python3, this branch is taken only for 'bytes'.
return s
# In Python2, 's' is a 'unicode' object.
# In Python3, 's' is a 'str' object.
# Encode to UTF-8 to get 'bytes' data.
return s.encode('utf-8') | [
"def",
"to_bytes",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"# In Python2, this branch is taken for both 'str' and 'bytes'.",
"# In Python3, this branch is taken only for 'bytes'.",
"return",
"s",
"# In Python2, 's' is a 'unicode' object.",
"# I... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/utils/lit/lit/util.py#L49-L63 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/trajectory.py | python | GeodesicHermiteTrajectory.extractDofs | (self,dofs) | Invalid for GeodesicHermiteTrajectory. | Invalid for GeodesicHermiteTrajectory. | [
"Invalid",
"for",
"GeodesicHermiteTrajectory",
"."
] | def extractDofs(self,dofs):
"""Invalid for GeodesicHermiteTrajectory."""
raise ValueError("Cannot extract DOFs from a GeodesicHermiteTrajectory") | [
"def",
"extractDofs",
"(",
"self",
",",
"dofs",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot extract DOFs from a GeodesicHermiteTrajectory\"",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L1294-L1296 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/__init__.py | python | ToolInitializer.remove_methods | (self, env) | Removes the methods that were added by the tool initialization
so we no longer copy and re-bind them when the construction
environment gets cloned. | Removes the methods that were added by the tool initialization
so we no longer copy and re-bind them when the construction
environment gets cloned. | [
"Removes",
"the",
"methods",
"that",
"were",
"added",
"by",
"the",
"tool",
"initialization",
"so",
"we",
"no",
"longer",
"copy",
"and",
"re",
"-",
"bind",
"them",
"when",
"the",
"construction",
"environment",
"gets",
"cloned",
"."
] | def remove_methods(self, env):
"""
Removes the methods that were added by the tool initialization
so we no longer copy and re-bind them when the construction
environment gets cloned.
"""
for method in list(self.methods.values()):
env.RemoveMethod(method) | [
"def",
"remove_methods",
"(",
"self",
",",
"env",
")",
":",
"for",
"method",
"in",
"list",
"(",
"self",
".",
"methods",
".",
"values",
"(",
")",
")",
":",
"env",
".",
"RemoveMethod",
"(",
"method",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/__init__.py#L1127-L1134 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/core.py | python | default_fill_value | (obj) | return defval | Return the default fill value for the argument object.
The default filling value depends on the datatype of the input
array or the type of the input scalar:
======== ========
datatype default
======== ========
bool True
int 999999
float 1.e20
complex 1.e20+0j
object '?'
string 'N/A'
======== ========
Parameters
----------
obj : ndarray, dtype or scalar
The array data-type or scalar for which the default fill value
is returned.
Returns
-------
fill_value : scalar
The default fill value.
Examples
--------
>>> np.ma.default_fill_value(1)
999999
>>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
1e+20
>>> np.ma.default_fill_value(np.dtype(complex))
(1e+20+0j) | Return the default fill value for the argument object. | [
"Return",
"the",
"default",
"fill",
"value",
"for",
"the",
"argument",
"object",
"."
] | def default_fill_value(obj):
"""
Return the default fill value for the argument object.
The default filling value depends on the datatype of the input
array or the type of the input scalar:
======== ========
datatype default
======== ========
bool True
int 999999
float 1.e20
complex 1.e20+0j
object '?'
string 'N/A'
======== ========
Parameters
----------
obj : ndarray, dtype or scalar
The array data-type or scalar for which the default fill value
is returned.
Returns
-------
fill_value : scalar
The default fill value.
Examples
--------
>>> np.ma.default_fill_value(1)
999999
>>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
1e+20
>>> np.ma.default_fill_value(np.dtype(complex))
(1e+20+0j)
"""
if hasattr(obj, 'dtype'):
defval = _check_fill_value(None, obj.dtype)
elif isinstance(obj, np.dtype):
if obj.subdtype:
defval = default_filler.get(obj.subdtype[0].kind, '?')
else:
defval = default_filler.get(obj.kind, '?')
elif isinstance(obj, float):
defval = default_filler['f']
elif isinstance(obj, int) or isinstance(obj, long):
defval = default_filler['i']
elif isinstance(obj, str):
defval = default_filler['S']
elif isinstance(obj, unicode):
defval = default_filler['U']
elif isinstance(obj, complex):
defval = default_filler['c']
else:
defval = default_filler['O']
return defval | [
"def",
"default_fill_value",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'dtype'",
")",
":",
"defval",
"=",
"_check_fill_value",
"(",
"None",
",",
"obj",
".",
"dtype",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"np",
".",
"dtype",
")",
... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L156-L215 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/cifar_tfrecords.py | python | convert_to_tfrecord | (input_files, output_file, folder) | Converts files with pickled data to TFRecords. | Converts files with pickled data to TFRecords. | [
"Converts",
"files",
"with",
"pickled",
"data",
"to",
"TFRecords",
"."
] | def convert_to_tfrecord(input_files, output_file, folder):
"""Converts files with pickled data to TFRecords."""
assert folder in ['cifar-10', 'cifar-100']
print('Generating %s' % output_file)
with tf.python_io.TFRecordWriter(output_file) as record_writer:
for input_file in input_files:
data_dict = read_pickle_from_file(input_file)
data = data_dict[b'data']
try:
labels = data_dict[b'labels']
except KeyError:
labels = data_dict[b'fine_labels']
if folder == 'cifar-100' and input_file.endswith('train.tfrecords'):
data = data[:40000]
labels = labels[:40000]
elif folder == 'cifar-100' and input_file.endswith(
'validation.tfrecords'):
data = data[40000:]
labels = labels[40000:]
num_entries_in_batch = len(labels)
for i in range(num_entries_in_batch):
example = tf.train.Example(
features=tf.train.Features(
feature={
'image': _bytes_feature(data[i].tobytes()),
'label': _int64_feature(labels[i])
}))
record_writer.write(example.SerializeToString()) | [
"def",
"convert_to_tfrecord",
"(",
"input_files",
",",
"output_file",
",",
"folder",
")",
":",
"assert",
"folder",
"in",
"[",
"'cifar-10'",
",",
"'cifar-100'",
"]",
"print",
"(",
"'Generating %s'",
"%",
"output_file",
")",
"with",
"tf",
".",
"python_io",
".",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/cifar_tfrecords.py#L91-L122 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Defaults.py | python | _defines | (prefix, defs, suffix, env, c=_concat_ixes) | return c(prefix, env.subst_path(processDefines(defs)), suffix, env) | A wrapper around _concat_ixes that turns a list or string
into a list of C preprocessor command-line definitions. | A wrapper around _concat_ixes that turns a list or string
into a list of C preprocessor command-line definitions. | [
"A",
"wrapper",
"around",
"_concat_ixes",
"that",
"turns",
"a",
"list",
"or",
"string",
"into",
"a",
"list",
"of",
"C",
"preprocessor",
"command",
"-",
"line",
"definitions",
"."
] | def _defines(prefix, defs, suffix, env, c=_concat_ixes):
"""A wrapper around _concat_ixes that turns a list or string
into a list of C preprocessor command-line definitions.
"""
return c(prefix, env.subst_path(processDefines(defs)), suffix, env) | [
"def",
"_defines",
"(",
"prefix",
",",
"defs",
",",
"suffix",
",",
"env",
",",
"c",
"=",
"_concat_ixes",
")",
":",
"return",
"c",
"(",
"prefix",
",",
"env",
".",
"subst_path",
"(",
"processDefines",
"(",
"defs",
")",
")",
",",
"suffix",
",",
"env",
... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Defaults.py#L514-L519 | |
xbmc/xbmc | 091211a754589fc40a2a1f239b0ce9f4ee138268 | addons/service.xbmc.versioncheck/resources/lib/version_check/common.py | python | get_password_from_user | () | return pwd | Prompt user to input password
:return: password
:rtype: str | Prompt user to input password | [
"Prompt",
"user",
"to",
"input",
"password"
] | def get_password_from_user():
""" Prompt user to input password
:return: password
:rtype: str
"""
pwd = ''
keyboard = xbmc.Keyboard('', ADDON_NAME + ': ' + localise(32022), True)
keyboard.doModal()
if keyboard.isConfirmed():
pwd = keyboard.getText()
return pwd | [
"def",
"get_password_from_user",
"(",
")",
":",
"pwd",
"=",
"''",
"keyboard",
"=",
"xbmc",
".",
"Keyboard",
"(",
"''",
",",
"ADDON_NAME",
"+",
"': '",
"+",
"localise",
"(",
"32022",
")",
",",
"True",
")",
"keyboard",
".",
"doModal",
"(",
")",
"if",
"... | https://github.com/xbmc/xbmc/blob/091211a754589fc40a2a1f239b0ce9f4ee138268/addons/service.xbmc.versioncheck/resources/lib/version_check/common.py#L126-L137 | |
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | python/taichi/lang/ops.py | python | sin | (a) | return _unary_operation(_ti_core.expr_sin, math.sin, a) | The sine function.
Args:
a (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
Returns:
Sine of `a`. | The sine function. | [
"The",
"sine",
"function",
"."
] | def sin(a):
"""The sine function.
Args:
a (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
Returns:
Sine of `a`.
"""
return _unary_operation(_ti_core.expr_sin, math.sin, a) | [
"def",
"sin",
"(",
"a",
")",
":",
"return",
"_unary_operation",
"(",
"_ti_core",
".",
"expr_sin",
",",
"math",
".",
"sin",
",",
"a",
")"
] | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/ops.py#L174-L183 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/auth.py | python | SigV4Auth.headers_to_sign | (self, request) | return header_map | Select the headers from the request that need to be included
in the StringToSign. | Select the headers from the request that need to be included
in the StringToSign. | [
"Select",
"the",
"headers",
"from",
"the",
"request",
"that",
"need",
"to",
"be",
"included",
"in",
"the",
"StringToSign",
"."
] | def headers_to_sign(self, request):
"""
Select the headers from the request that need to be included
in the StringToSign.
"""
header_map = HTTPHeaders()
for name, value in request.headers.items():
lname = name.lower()
if lname not in SIGNED_HEADERS_BLACKLIST:
header_map[lname] = value
if 'host' not in header_map:
# Ensure we sign the lowercased version of the host, as that
# is what will ultimately be sent on the wire.
# TODO: We should set the host ourselves, instead of relying on our
# HTTP client to set it for us.
header_map['host'] = self._canonical_host(request.url).lower()
return header_map | [
"def",
"headers_to_sign",
"(",
"self",
",",
"request",
")",
":",
"header_map",
"=",
"HTTPHeaders",
"(",
")",
"for",
"name",
",",
"value",
"in",
"request",
".",
"headers",
".",
"items",
"(",
")",
":",
"lname",
"=",
"name",
".",
"lower",
"(",
")",
"if"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/auth.py#L172-L188 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/integration/AsyncStateMachine.py | python | AsyncStateMachine.setCloseOp | (self) | Start a close operation. | Start a close operation. | [
"Start",
"a",
"close",
"operation",
"."
] | def setCloseOp(self):
"""Start a close operation.
"""
try:
self._checkAssert(0)
self.closer = self.tlsConnection.closeAsync()
self._doCloseOp()
except:
self._clear()
raise | [
"def",
"setCloseOp",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_checkAssert",
"(",
"0",
")",
"self",
".",
"closer",
"=",
"self",
".",
"tlsConnection",
".",
"closeAsync",
"(",
")",
"self",
".",
"_doCloseOp",
"(",
")",
"except",
":",
"self",
"."... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/integration/AsyncStateMachine.py#L211-L220 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/monitors.py | python | _as_graph_element | (obj) | return element | Retrieves Graph element. | Retrieves Graph element. | [
"Retrieves",
"Graph",
"element",
"."
] | def _as_graph_element(obj):
"""Retrieves Graph element."""
graph = ops.get_default_graph()
if not isinstance(obj, six.string_types):
if not hasattr(obj, "graph") or obj.graph != graph:
raise ValueError("Passed %s should have graph attribute that is equal "
"to current graph %s." % (obj, graph))
return obj
if ":" in obj:
element = graph.as_graph_element(obj)
else:
element = graph.as_graph_element(obj + ":0")
# Check that there is no :1 (e.g. it's single output).
try:
graph.as_graph_element(obj + ":1")
except (KeyError, ValueError):
pass
else:
raise ValueError("Name %s is ambiguous, "
"as this `Operation` has multiple outputs "
"(at least 2)." % obj)
return element | [
"def",
"_as_graph_element",
"(",
"obj",
")",
":",
"graph",
"=",
"ops",
".",
"get_default_graph",
"(",
")",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"\"graph\"",
")",
"or"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/monitors.py#L1256-L1277 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_NV_CERTIFY_INFO.toTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def toTpm(self, buf):
""" TpmMarshaller method """
buf.writeSizedByteBuf(self.indexName)
buf.writeShort(self.offset)
buf.writeSizedByteBuf(self.nvContents) | [
"def",
"toTpm",
"(",
"self",
",",
"buf",
")",
":",
"buf",
".",
"writeSizedByteBuf",
"(",
"self",
".",
"indexName",
")",
"buf",
".",
"writeShort",
"(",
"self",
".",
"offset",
")",
"buf",
".",
"writeSizedByteBuf",
"(",
"self",
".",
"nvContents",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L5337-L5341 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/version.py | python | Matcher.match | (self, version) | return True | Check if the provided version matches the constraints.
:param version: The version to match against this instance.
:type version: String or :class:`Version` instance. | Check if the provided version matches the constraints. | [
"Check",
"if",
"the",
"provided",
"version",
"matches",
"the",
"constraints",
"."
] | def match(self, version):
"""
Check if the provided version matches the constraints.
:param version: The version to match against this instance.
:type version: String or :class:`Version` instance.
"""
if isinstance(version, string_types):
version = self.version_class(version)
for operator, constraint, prefix in self._parts:
f = self._operators.get(operator)
if isinstance(f, string_types):
f = getattr(self, f)
if not f:
msg = ('%r not implemented '
'for %s' % (operator, self.__class__.__name__))
raise NotImplementedError(msg)
if not f(version, constraint, prefix):
return False
return True | [
"def",
"match",
"(",
"self",
",",
"version",
")",
":",
"if",
"isinstance",
"(",
"version",
",",
"string_types",
")",
":",
"version",
"=",
"self",
".",
"version_class",
"(",
"version",
")",
"for",
"operator",
",",
"constraint",
",",
"prefix",
"in",
"self"... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/version.py#L129-L148 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewModel.IsListModel | (*args, **kwargs) | return _dataview.DataViewModel_IsListModel(*args, **kwargs) | IsListModel(self) -> bool | IsListModel(self) -> bool | [
"IsListModel",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsListModel(*args, **kwargs):
"""IsListModel(self) -> bool"""
return _dataview.DataViewModel_IsListModel(*args, **kwargs) | [
"def",
"IsListModel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModel_IsListModel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L690-L692 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/pexpect-2.4/pexpect.py | python | searcher_re.__str__ | (self) | return '\n'.join(ss) | This returns a human-readable string that represents the state of
the object. | This returns a human-readable string that represents the state of
the object. | [
"This",
"returns",
"a",
"human",
"-",
"readable",
"string",
"that",
"represents",
"the",
"state",
"of",
"the",
"object",
"."
] | def __str__(self):
"""This returns a human-readable string that represents the state of
the object."""
ss = [(n, ' %d: re.compile("%s")' % (n, str(s.pattern)))
for n, s in self._searches]
ss.append((-1, 'searcher_re:'))
if self.eof_index >= 0:
ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
if self.timeout_index >= 0:
ss.append(
(self.timeout_index,
' %d: TIMEOUT' %
self.timeout_index))
ss.sort()
ss = zip(*ss)[1]
return '\n'.join(ss) | [
"def",
"__str__",
"(",
"self",
")",
":",
"ss",
"=",
"[",
"(",
"n",
",",
"' %d: re.compile(\"%s\")'",
"%",
"(",
"n",
",",
"str",
"(",
"s",
".",
"pattern",
")",
")",
")",
"for",
"n",
",",
"s",
"in",
"self",
".",
"_searches",
"]",
"ss",
".",
"a... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/pexpect.py#L1760-L1776 | |
JumpingYang001/webrtc | c03d6e965e1f54aeadd670e491eabe5fdb8db968 | tools_webrtc/presubmit_checks_lib/build_helpers.py | python | RunGnCheck | (root_dir=None) | return GN_ERROR_RE.findall(error) if error else [] | Runs `gn gen --check` with default args to detect mismatches between
#includes and dependencies in the BUILD.gn files, as well as general build
errors.
Returns a list of error summary strings. | Runs `gn gen --check` with default args to detect mismatches between
#includes and dependencies in the BUILD.gn files, as well as general build
errors. | [
"Runs",
"gn",
"gen",
"--",
"check",
"with",
"default",
"args",
"to",
"detect",
"mismatches",
"between",
"#includes",
"and",
"dependencies",
"in",
"the",
"BUILD",
".",
"gn",
"files",
"as",
"well",
"as",
"general",
"build",
"errors",
"."
] | def RunGnCheck(root_dir=None):
"""Runs `gn gen --check` with default args to detect mismatches between
#includes and dependencies in the BUILD.gn files, as well as general build
errors.
Returns a list of error summary strings.
"""
out_dir = tempfile.mkdtemp('gn')
try:
error = RunGnCommand(['gen', '--check', out_dir], root_dir)
finally:
shutil.rmtree(out_dir, ignore_errors=True)
return GN_ERROR_RE.findall(error) if error else [] | [
"def",
"RunGnCheck",
"(",
"root_dir",
"=",
"None",
")",
":",
"out_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'gn'",
")",
"try",
":",
"error",
"=",
"RunGnCommand",
"(",
"[",
"'gen'",
",",
"'--check'",
",",
"out_dir",
"]",
",",
"root_dir",
")",
"finall... | https://github.com/JumpingYang001/webrtc/blob/c03d6e965e1f54aeadd670e491eabe5fdb8db968/tools_webrtc/presubmit_checks_lib/build_helpers.py#L52-L64 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/http/cookiejar.py | python | DefaultCookiePolicy.set_blocked_domains | (self, blocked_domains) | Set the sequence of blocked domains. | Set the sequence of blocked domains. | [
"Set",
"the",
"sequence",
"of",
"blocked",
"domains",
"."
] | def set_blocked_domains(self, blocked_domains):
"""Set the sequence of blocked domains."""
self._blocked_domains = tuple(blocked_domains) | [
"def",
"set_blocked_domains",
"(",
"self",
",",
"blocked_domains",
")",
":",
"self",
".",
"_blocked_domains",
"=",
"tuple",
"(",
"blocked_domains",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/http/cookiejar.py#L915-L917 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/estimator/canned/head.py | python | _MultiClassHeadWithSoftmaxCrossEntropyLoss.create_estimator_spec | (
self, features, mode, logits, labels=None, train_op_fn=None) | return model_fn.EstimatorSpec(
mode=model_fn.ModeKeys.TRAIN,
predictions=predictions,
loss=training_loss,
train_op=train_op_fn(training_loss)) | See `Head`. | See `Head`. | [
"See",
"Head",
"."
] | def create_estimator_spec(
self, features, mode, logits, labels=None, train_op_fn=None):
"""See `Head`."""
with ops.name_scope(self._name, 'head'):
logits = _check_logits(logits, self.logits_dimension)
# Predict.
pred_keys = prediction_keys.PredictionKeys
with ops.name_scope(None, 'predictions', (logits,)):
# class_ids's shape is [batch_size]
class_ids = math_ops.argmax(logits, 1, name=pred_keys.CLASS_IDS)
class_ids = array_ops.expand_dims(class_ids, axis=(1,))
if self._label_vocabulary:
table = lookup_ops.index_to_string_table_from_tensor(
vocabulary_list=self._label_vocabulary,
name='class_string_lookup')
classes = table.lookup(class_ids)
else:
classes = string_ops.as_string(class_ids, name='str_classes')
probabilities = nn.softmax(logits, name=pred_keys.PROBABILITIES)
predictions = {
pred_keys.LOGITS: logits,
pred_keys.PROBABILITIES: probabilities,
# Expand to [batch_size, 1]
pred_keys.CLASS_IDS: class_ids,
pred_keys.CLASSES: classes,
}
if mode == model_fn.ModeKeys.PREDICT:
classifier_output = _classification_output(
scores=probabilities, n_classes=self._n_classes,
label_vocabulary=self._label_vocabulary)
return model_fn.EstimatorSpec(
mode=model_fn.ModeKeys.PREDICT,
predictions=predictions,
export_outputs={
_DEFAULT_SERVING_KEY: classifier_output,
_CLASSIFY_SERVING_KEY: classifier_output,
_PREDICT_SERVING_KEY: export_output.PredictOutput(predictions)
})
# Eval.
unweighted_loss, label_ids = self.create_loss(
features=features, mode=mode, logits=logits, labels=labels)
weights = _weights(features, self._weight_column)
training_loss = losses.compute_weighted_loss(
unweighted_loss, weights=weights, reduction=losses.Reduction.SUM)
if mode == model_fn.ModeKeys.EVAL:
return model_fn.EstimatorSpec(
mode=model_fn.ModeKeys.EVAL,
predictions=predictions,
loss=training_loss,
eval_metric_ops=self._eval_metric_ops(
labels=label_ids,
class_ids=class_ids,
unweighted_loss=unweighted_loss,
weights=weights))
# Train.
if train_op_fn is None:
raise ValueError('train_op_fn can not be None.')
with ops.name_scope(''):
summary.scalar(
_summary_key(self._name, metric_keys.MetricKeys.LOSS),
training_loss)
summary.scalar(
_summary_key(self._name, metric_keys.MetricKeys.LOSS_MEAN),
losses.compute_weighted_loss(
unweighted_loss, weights=weights,
reduction=losses.Reduction.MEAN))
return model_fn.EstimatorSpec(
mode=model_fn.ModeKeys.TRAIN,
predictions=predictions,
loss=training_loss,
train_op=train_op_fn(training_loss)) | [
"def",
"create_estimator_spec",
"(",
"self",
",",
"features",
",",
"mode",
",",
"logits",
",",
"labels",
"=",
"None",
",",
"train_op_fn",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"_name",
",",
"'head'",
")",
":",
"logi... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/estimator/canned/head.py#L463-L537 | |
google/shaka-packager | e1b0c7c45431327fd3ce193514a5407d07b39b22 | packager/third_party/protobuf/python/google/protobuf/internal/containers.py | python | RepeatedScalarFieldContainer.__eq__ | (self, other) | return other == self._values | Compares the current instance with another one. | Compares the current instance with another one. | [
"Compares",
"the",
"current",
"instance",
"with",
"another",
"one",
"."
] | def __eq__(self, other):
"""Compares the current instance with another one."""
if self is other:
return True
# Special case for the same type which should be common and fast.
if isinstance(other, self.__class__):
return other._values == self._values
# We are presumably comparing against some other sequence type.
return other == self._values | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
"is",
"other",
":",
"return",
"True",
"# Special case for the same type which should be common and fast.",
"if",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"o... | https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/containers.py#L330-L338 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/summary/impl/gcs.py | python | CheckIsSupported | () | Raises an OSError if the system isn't set up for Google Cloud Storage.
Raises:
OSError: If the system hasn't been set up so that TensorBoard can access
Google Cloud Storage. The error's message contains installation
instructions. | Raises an OSError if the system isn't set up for Google Cloud Storage. | [
"Raises",
"an",
"OSError",
"if",
"the",
"system",
"isn",
"t",
"set",
"up",
"for",
"Google",
"Cloud",
"Storage",
"."
] | def CheckIsSupported():
"""Raises an OSError if the system isn't set up for Google Cloud Storage.
Raises:
OSError: If the system hasn't been set up so that TensorBoard can access
Google Cloud Storage. The error's message contains installation
instructions.
"""
try:
subprocess.check_output(['gsutil', 'version'])
except OSError as e:
logging.error('Error while checking for gsutil: %s', e)
raise OSError(
'Unable to execute the gsutil binary, which is required for Google '
'Cloud Storage support. You can find installation instructions at '
'https://goo.gl/sST520') | [
"def",
"CheckIsSupported",
"(",
")",
":",
"try",
":",
"subprocess",
".",
"check_output",
"(",
"[",
"'gsutil'",
",",
"'version'",
"]",
")",
"except",
"OSError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"'Error while checking for gsutil: %s'",
",",
"e",
"... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/summary/impl/gcs.py#L117-L132 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/tools/miniterm.py | python | Transform.rx | (self, text) | return text | text received from serial port | text received from serial port | [
"text",
"received",
"from",
"serial",
"port"
] | def rx(self, text):
"""text received from serial port"""
return text | [
"def",
"rx",
"(",
"self",
",",
"text",
")",
":",
"return",
"text"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/tools/miniterm.py#L179-L181 | |
greenheartgames/greenworks | 3ea4ab490b56676de3f0a237c74bcfdb17323e60 | deps/cpplint/cpplint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L944-L946 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/_lsq/common.py | python | right_multiplied_operator | (J, d) | return LinearOperator(J.shape, matvec=matvec, matmat=matmat,
rmatvec=rmatvec) | Return J diag(d) as LinearOperator. | Return J diag(d) as LinearOperator. | [
"Return",
"J",
"diag",
"(",
"d",
")",
"as",
"LinearOperator",
"."
] | def right_multiplied_operator(J, d):
"""Return J diag(d) as LinearOperator."""
J = aslinearoperator(J)
def matvec(x):
return J.matvec(np.ravel(x) * d)
def matmat(X):
return J.matmat(X * d[:, np.newaxis])
def rmatvec(x):
return d * J.rmatvec(x)
return LinearOperator(J.shape, matvec=matvec, matmat=matmat,
rmatvec=rmatvec) | [
"def",
"right_multiplied_operator",
"(",
"J",
",",
"d",
")",
":",
"J",
"=",
"aslinearoperator",
"(",
"J",
")",
"def",
"matvec",
"(",
"x",
")",
":",
"return",
"J",
".",
"matvec",
"(",
"np",
".",
"ravel",
"(",
"x",
")",
"*",
"d",
")",
"def",
"matma... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_lsq/common.py#L634-L648 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/importlib/_bootstrap_external.py | python | FileFinder.path_hook | (cls, *loader_details) | return path_hook_for_FileFinder | A class method which returns a closure to use on sys.path_hook
which will return an instance using the specified loaders and the path
called on the closure.
If the path called on the closure is not a directory, ImportError is
raised. | A class method which returns a closure to use on sys.path_hook
which will return an instance using the specified loaders and the path
called on the closure. | [
"A",
"class",
"method",
"which",
"returns",
"a",
"closure",
"to",
"use",
"on",
"sys",
".",
"path_hook",
"which",
"will",
"return",
"an",
"instance",
"using",
"the",
"specified",
"loaders",
"and",
"the",
"path",
"called",
"on",
"the",
"closure",
"."
] | def path_hook(cls, *loader_details):
"""A class method which returns a closure to use on sys.path_hook
which will return an instance using the specified loaders and the path
called on the closure.
If the path called on the closure is not a directory, ImportError is
raised.
"""
def path_hook_for_FileFinder(path):
"""Path hook for importlib.machinery.FileFinder."""
if not _path_isdir(path):
raise ImportError('only directories are supported', path=path)
return cls(path, *loader_details)
return path_hook_for_FileFinder | [
"def",
"path_hook",
"(",
"cls",
",",
"*",
"loader_details",
")",
":",
"def",
"path_hook_for_FileFinder",
"(",
"path",
")",
":",
"\"\"\"Path hook for importlib.machinery.FileFinder.\"\"\"",
"if",
"not",
"_path_isdir",
"(",
"path",
")",
":",
"raise",
"ImportError",
"(... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/_bootstrap_external.py#L1588-L1603 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/generator.py | python | Generator.flatten | (self, msg, unixfrom=False) | Print the message object tree rooted at msg to the output file
specified when the Generator instance was created.
unixfrom is a flag that forces the printing of a Unix From_ delimiter
before the first object in the message tree. If the original message
has no From_ delimiter, a `standard' one is crafted. By default, this
is False to inhibit the printing of any From_ delimiter.
Note that for subobjects, no From_ line is printed. | Print the message object tree rooted at msg to the output file
specified when the Generator instance was created. | [
"Print",
"the",
"message",
"object",
"tree",
"rooted",
"at",
"msg",
"to",
"the",
"output",
"file",
"specified",
"when",
"the",
"Generator",
"instance",
"was",
"created",
"."
] | def flatten(self, msg, unixfrom=False):
"""Print the message object tree rooted at msg to the output file
specified when the Generator instance was created.
unixfrom is a flag that forces the printing of a Unix From_ delimiter
before the first object in the message tree. If the original message
has no From_ delimiter, a `standard' one is crafted. By default, this
is False to inhibit the printing of any From_ delimiter.
Note that for subobjects, no From_ line is printed.
"""
if unixfrom:
ufrom = msg.get_unixfrom()
if not ufrom:
ufrom = 'From nobody ' + time.ctime(time.time())
print >> self._fp, ufrom
self._write(msg) | [
"def",
"flatten",
"(",
"self",
",",
"msg",
",",
"unixfrom",
"=",
"False",
")",
":",
"if",
"unixfrom",
":",
"ufrom",
"=",
"msg",
".",
"get_unixfrom",
"(",
")",
"if",
"not",
"ufrom",
":",
"ufrom",
"=",
"'From nobody '",
"+",
"time",
".",
"ctime",
"(",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/generator.py#L67-L83 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/futures.py | python | TransferMeta.transfer_id | (self) | return self._transfer_id | The unique id of the transfer | The unique id of the transfer | [
"The",
"unique",
"id",
"of",
"the",
"transfer"
] | def transfer_id(self):
"""The unique id of the transfer"""
return self._transfer_id | [
"def",
"transfer_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_transfer_id"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/futures.py#L137-L139 | |
shogun-toolbox/shogun | 9b8d856971af5a295dd6ad70623ae45647a6334c | examples/meta/generator/parse.py | python | FastParser.p_int | (self, p) | int : INTLITERAL | int : INTLITERAL | [
"int",
":",
"INTLITERAL"
] | def p_int(self, p):
"int : INTLITERAL"
p[0] = {"IntLiteral": p[1]} | [
"def",
"p_int",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"{",
"\"IntLiteral\"",
":",
"p",
"[",
"1",
"]",
"}"
] | https://github.com/shogun-toolbox/shogun/blob/9b8d856971af5a295dd6ad70623ae45647a6334c/examples/meta/generator/parse.py#L268-L270 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/help.py | python | main | () | Pretty-print the bug information as JSON. | Pretty-print the bug information as JSON. | [
"Pretty",
"-",
"print",
"the",
"bug",
"information",
"as",
"JSON",
"."
] | def main():
"""Pretty-print the bug information as JSON."""
print(json.dumps(info(), sort_keys=True, indent=2)) | [
"def",
"main",
"(",
")",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"info",
"(",
")",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"2",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/help.py#L113-L115 | ||
manutdzou/KITTI_SSD | 5b620c2f291d36a0fe14489214f22a992f173f44 | tools/extra/extract_seconds.py | python | get_start_time | (line_iterable, year) | return start_datetime | Find start time from group of lines | Find start time from group of lines | [
"Find",
"start",
"time",
"from",
"group",
"of",
"lines"
] | def get_start_time(line_iterable, year):
"""Find start time from group of lines
"""
start_datetime = None
for line in line_iterable:
line = line.strip()
if line.find('Solving') != -1:
start_datetime = extract_datetime_from_line(line, year)
break
return start_datetime | [
"def",
"get_start_time",
"(",
"line_iterable",
",",
"year",
")",
":",
"start_datetime",
"=",
"None",
"for",
"line",
"in",
"line_iterable",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"find",
"(",
"'Solving'",
")",
"!=",
"-",
"1... | https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/tools/extra/extract_seconds.py#L31-L41 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewListCtrl.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=DV_ROW_LINES,
Validator validator=DefaultValidator) -> DataViewListCtrl | __init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=DV_ROW_LINES,
Validator validator=DefaultValidator) -> DataViewListCtrl | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"DV_ROW_LINES",
"Validator",
"validator",
"=",
"DefaultValidator",
")",
"-",
">",
"Data... | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=DV_ROW_LINES,
Validator validator=DefaultValidator) -> DataViewListCtrl
"""
_dataview.DataViewListCtrl_swiginit(self,_dataview.new_DataViewListCtrl(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_dataview",
".",
"DataViewListCtrl_swiginit",
"(",
"self",
",",
"_dataview",
".",
"new_DataViewListCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L2070-L2077 | ||
frankaemika/franka_ros | ed3d0025b45059322c436b22e43f79bceda418c7 | franka_example_controllers/scripts/dual_arm_interactive_marker.py | python | reset_marker_pose_blocking | () | This function resets the marker pose to current "middle pose" of left and right arm EEs.
:return: None | This function resets the marker pose to current "middle pose" of left and right arm EEs.
:return: None | [
"This",
"function",
"resets",
"the",
"marker",
"pose",
"to",
"current",
"middle",
"pose",
"of",
"left",
"and",
"right",
"arm",
"EEs",
".",
":",
"return",
":",
"None"
] | def reset_marker_pose_blocking():
"""
This function resets the marker pose to current "middle pose" of left and right arm EEs.
:return: None
"""
global marker_pose
marker_pose = rospy.wait_for_message(
"dual_arm_cartesian_impedance_example_controller/centering_frame", PoseStamped) | [
"def",
"reset_marker_pose_blocking",
"(",
")",
":",
"global",
"marker_pose",
"marker_pose",
"=",
"rospy",
".",
"wait_for_message",
"(",
"\"dual_arm_cartesian_impedance_example_controller/centering_frame\"",
",",
"PoseStamped",
")"
] | https://github.com/frankaemika/franka_ros/blob/ed3d0025b45059322c436b22e43f79bceda418c7/franka_example_controllers/scripts/dual_arm_interactive_marker.py#L81-L89 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html.py | python | HtmlHelpWindow.GetSplitterWindow | (*args, **kwargs) | return _html.HtmlHelpWindow_GetSplitterWindow(*args, **kwargs) | GetSplitterWindow(self) -> SplitterWindow | GetSplitterWindow(self) -> SplitterWindow | [
"GetSplitterWindow",
"(",
"self",
")",
"-",
">",
"SplitterWindow"
] | def GetSplitterWindow(*args, **kwargs):
"""GetSplitterWindow(self) -> SplitterWindow"""
return _html.HtmlHelpWindow_GetSplitterWindow(*args, **kwargs) | [
"def",
"GetSplitterWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlHelpWindow_GetSplitterWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1646-L1648 | |
RLBot/RLBot | 34332b12cf158b3ef8dbf174ae67c53683368a9d | src/legacy/python/legacy_gui/rlbot_legacy_gui/qt_root.py | python | RLBotQTGui.load_selected_bot | (self) | Loads all the values belonging to the new selected agent into the bot_config_groupbox
:return: | Loads all the values belonging to the new selected agent into the bot_config_groupbox
:return: | [
"Loads",
"all",
"the",
"values",
"belonging",
"to",
"the",
"new",
"selected",
"agent",
"into",
"the",
"bot_config_groupbox",
":",
"return",
":"
] | def load_selected_bot(self):
"""
Loads all the values belonging to the new selected agent into the bot_config_groupbox
:return:
"""
# prevent processing from itself (clearing the other one processes this)
if not self.sender().selectedItems():
return
blue = True if self.sender() is self.blue_listwidget else False
if blue: # deselect the other listbox
self.orange_listwidget.clearSelection()
else:
self.blue_listwidget.clearSelection()
item_name = self.sender().selectedItems()[0].text()
agent = self.bot_names_to_agent_dict[item_name]
if agent is None: # something went wrong if agent is None
return
self.current_bot = agent
self.bot_config_groupbox.setEnabled(True) # Make sure that you can edit the bot
# enable [-] for right listwidget
if blue:
self.blue_minus_toolbutton.setDisabled(False)
self.orange_minus_toolbutton.setDisabled(True)
else:
self.orange_minus_toolbutton.setDisabled(False)
self.blue_minus_toolbutton.setDisabled(True)
# load the bot parameters into the edit frame
agent_type = agent.get_participant_type()
known_types = ['human', 'psyonix', 'rlbot', 'party_member_bot']
assert agent_type in known_types, 'Bot has unknown type: %s' % agent_type
self.bot_type_combobox.setCurrentIndex(known_types.index(agent_type))
if blue:
self.blue_radiobutton.setChecked(True)
else:
self.orange_radiobutton.setChecked(True)
self.ign_lineedit.setText(agent.ingame_name)
loadout_index = index_of_config_path_in_combobox(
self.loadout_preset_combobox, agent.get_loadout_preset().config_path)
self.loadout_preset_combobox.setCurrentIndex(loadout_index or 0)
self.agent_preset_combobox.blockSignals(True)
self.agent_preset_combobox.setCurrentText(agent.get_agent_preset().get_name())
self.agent_preset_combobox.blockSignals(False)
self.bot_level_slider.setValue(int(agent.get_bot_skill() * 100)) | [
"def",
"load_selected_bot",
"(",
"self",
")",
":",
"# prevent processing from itself (clearing the other one processes this)",
"if",
"not",
"self",
".",
"sender",
"(",
")",
".",
"selectedItems",
"(",
")",
":",
"return",
"blue",
"=",
"True",
"if",
"self",
".",
"sen... | https://github.com/RLBot/RLBot/blob/34332b12cf158b3ef8dbf174ae67c53683368a9d/src/legacy/python/legacy_gui/rlbot_legacy_gui/qt_root.py#L459-L510 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.