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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zerotier/libzt | 41eb9aebc80a5f1c816fa26a06cefde9de906676 | src/bindings/python/sockets.py | python | socket.if_nametoindex | (self, if_name) | libzt does not support this | libzt does not support this | [
"libzt",
"does",
"not",
"support",
"this"
] | def if_nametoindex(self, if_name):
"""libzt does not support this"""
raise NotImplementedError("if_nametoindex(): libzt does not name interfaces.") | [
"def",
"if_nametoindex",
"(",
"self",
",",
"if_name",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"if_nametoindex(): libzt does not name interfaces.\"",
")"
] | https://github.com/zerotier/libzt/blob/41eb9aebc80a5f1c816fa26a06cefde9de906676/src/bindings/python/sockets.py#L211-L213 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/datetime.py | python | time.__repr__ | (self) | return s | Convert to formal string, for repr(). | Convert to formal string, for repr(). | [
"Convert",
"to",
"formal",
"string",
"for",
"repr",
"()",
"."
] | def __repr__(self):
"""Convert to formal string, for repr()."""
if self._microsecond != 0:
s = ", %d, %d" % (self._second, self._microsecond)
elif self._second != 0:
s = ", %d" % self._second
else:
s = ""
s= "%s.%s(%d, %d%s)" % (self.__class__.__module__,
self.__class__.__qualname__,
self._hour, self._minute, s)
if self._tzinfo is not None:
assert s[-1:] == ")"
s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
if self._fold:
assert s[-1:] == ")"
s = s[:-1] + ", fold=1)"
return s | [
"def",
"__repr__",
"(",
"self",
")",
":",
"if",
"self",
".",
"_microsecond",
"!=",
"0",
":",
"s",
"=",
"\", %d, %d\"",
"%",
"(",
"self",
".",
"_second",
",",
"self",
".",
"_microsecond",
")",
"elif",
"self",
".",
"_second",
"!=",
"0",
":",
"s",
"=",
"\", %d\"",
"%",
"self",
".",
"_second",
"else",
":",
"s",
"=",
"\"\"",
"s",
"=",
"\"%s.%s(%d, %d%s)\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__module__",
",",
"self",
".",
"__class__",
".",
"__qualname__",
",",
"self",
".",
"_hour",
",",
"self",
".",
"_minute",
",",
"s",
")",
"if",
"self",
".",
"_tzinfo",
"is",
"not",
"None",
":",
"assert",
"s",
"[",
"-",
"1",
":",
"]",
"==",
"\")\"",
"s",
"=",
"s",
"[",
":",
"-",
"1",
"]",
"+",
"\", tzinfo=%r\"",
"%",
"self",
".",
"_tzinfo",
"+",
"\")\"",
"if",
"self",
".",
"_fold",
":",
"assert",
"s",
"[",
"-",
"1",
":",
"]",
"==",
"\")\"",
"s",
"=",
"s",
"[",
":",
"-",
"1",
"]",
"+",
"\", fold=1)\"",
"return",
"s"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/datetime.py#L1346-L1363 | |
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | boringssl/util/bot/vs_toolchain.py | python | _GetDesiredVsToolchainHashes | () | return ['4087e065abebdca6dbd0caca2910c6718d2ec67f'] | Load a list of SHA1s corresponding to the toolchains that we want installed
to build with. | Load a list of SHA1s corresponding to the toolchains that we want installed
to build with. | [
"Load",
"a",
"list",
"of",
"SHA1s",
"corresponding",
"to",
"the",
"toolchains",
"that",
"we",
"want",
"installed",
"to",
"build",
"with",
"."
] | def _GetDesiredVsToolchainHashes():
"""Load a list of SHA1s corresponding to the toolchains that we want installed
to build with."""
# Use Chromium's VS2013.
return ['4087e065abebdca6dbd0caca2910c6718d2ec67f'] | [
"def",
"_GetDesiredVsToolchainHashes",
"(",
")",
":",
"# Use Chromium's VS2013.",
"return",
"[",
"'4087e065abebdca6dbd0caca2910c6718d2ec67f'",
"]"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/boringssl/util/bot/vs_toolchain.py#L64-L68 | |
CaoWGG/TensorRT-YOLOv4 | 4d7c2edce99e8794a4cb4ea3540d51ce91158a36 | onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py | python | Cursor.is_anonymous | (self) | return conf.lib.clang_Cursor_isAnonymous(self) | Check if the record is anonymous. | Check if the record is anonymous. | [
"Check",
"if",
"the",
"record",
"is",
"anonymous",
"."
] | def is_anonymous(self):
"""
Check if the record is anonymous.
"""
if self.kind == CursorKind.FIELD_DECL:
return self.type.get_declaration().is_anonymous()
return conf.lib.clang_Cursor_isAnonymous(self) | [
"def",
"is_anonymous",
"(",
"self",
")",
":",
"if",
"self",
".",
"kind",
"==",
"CursorKind",
".",
"FIELD_DECL",
":",
"return",
"self",
".",
"type",
".",
"get_declaration",
"(",
")",
".",
"is_anonymous",
"(",
")",
"return",
"conf",
".",
"lib",
".",
"clang_Cursor_isAnonymous",
"(",
"self",
")"
] | https://github.com/CaoWGG/TensorRT-YOLOv4/blob/4d7c2edce99e8794a4cb4ea3540d51ce91158a36/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L1683-L1689 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/util/command_line.py | python | ArgumentHandlerMixIn.AddCommandLineArgs | (cls, parser) | Override to accept custom command-line arguments. | Override to accept custom command-line arguments. | [
"Override",
"to",
"accept",
"custom",
"command",
"-",
"line",
"arguments",
"."
] | def AddCommandLineArgs(cls, parser):
"""Override to accept custom command-line arguments.""" | [
"def",
"AddCommandLineArgs",
"(",
"cls",
",",
"parser",
")",
":"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/util/command_line.py#L21-L22 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | concatenate | (seq, axis=0, out=None) | return _npi.concatenate(*seq, axis=axis, out=out) | Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of _Symbols
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
Returns
-------
res : _Symbol
The concatenated array.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1., 2.],
[3., 4.],
[5., 6.]])
>>> np.concatenate((a, b), axis=None)
array([1., 2., 3., 4., 5., 6.])
>>> np.concatenate((a, b.T), axis=1)
array([[1., 2., 5.],
[3., 4., 6.]]) | Join a sequence of arrays along an existing axis. | [
"Join",
"a",
"sequence",
"of",
"arrays",
"along",
"an",
"existing",
"axis",
"."
] | def concatenate(seq, axis=0, out=None):
"""Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of _Symbols
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
Returns
-------
res : _Symbol
The concatenated array.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1., 2.],
[3., 4.],
[5., 6.]])
>>> np.concatenate((a, b), axis=None)
array([1., 2., 3., 4., 5., 6.])
>>> np.concatenate((a, b.T), axis=1)
array([[1., 2., 5.],
[3., 4., 6.]])
"""
return _npi.concatenate(*seq, axis=axis, out=out) | [
"def",
"concatenate",
"(",
"seq",
",",
"axis",
"=",
"0",
",",
"out",
"=",
"None",
")",
":",
"return",
"_npi",
".",
"concatenate",
"(",
"*",
"seq",
",",
"axis",
"=",
"axis",
",",
"out",
"=",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L4246-L4283 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/sparsity/keras/pruning_impl.py | python | Pruning._weight_assign_objs | (self) | return assign_objs | Gather the assign objs for assigning weights<=weights*mask.
The objs are ops for graph execution and tensors for eager
execution.
Returns:
group of objs for weight assignment. | Gather the assign objs for assigning weights<=weights*mask. | [
"Gather",
"the",
"assign",
"objs",
"for",
"assigning",
"weights<",
"=",
"weights",
"*",
"mask",
"."
] | def _weight_assign_objs(self):
"""Gather the assign objs for assigning weights<=weights*mask.
The objs are ops for graph execution and tensors for eager
execution.
Returns:
group of objs for weight assignment.
"""
def update_fn(distribution, values_and_vars):
# TODO(yunluli): Need this ReduceOp because the weight is created by the
# layer wrapped, so we don't have control of its aggregation policy. May
# be able to optimize this when distribution strategy supports easier
# update to mirrored variables in replica context.
reduced_values = distribution.extended.batch_reduce_to(
tf.distribute.ReduceOp.MEAN, values_and_vars)
var_list = [v for _, v in values_and_vars]
values_and_vars = zip(reduced_values, var_list)
def update_var(variable, reduced_value):
return tf_compat.assign(variable, reduced_value)
update_objs = []
for value, var in values_and_vars:
update_objs.append(
distribution.extended.update(var, update_var, args=(value,)))
return tf.group(update_objs)
assign_objs = []
if tf.distribute.get_replica_context():
values_and_vars = []
for weight, mask, _ in self._pruning_vars:
masked_weight = tf.math.multiply(weight, mask)
values_and_vars.append((masked_weight, weight))
if values_and_vars:
assign_objs.append(tf.distribute.get_replica_context().merge_call(
update_fn, args=(values_and_vars,)))
else:
for weight, mask, _ in self._pruning_vars:
masked_weight = tf.math.multiply(weight, mask)
assign_objs.append(tf_compat.assign(weight, masked_weight))
return assign_objs | [
"def",
"_weight_assign_objs",
"(",
"self",
")",
":",
"def",
"update_fn",
"(",
"distribution",
",",
"values_and_vars",
")",
":",
"# TODO(yunluli): Need this ReduceOp because the weight is created by the",
"# layer wrapped, so we don't have control of its aggregation policy. May",
"# be able to optimize this when distribution strategy supports easier",
"# update to mirrored variables in replica context.",
"reduced_values",
"=",
"distribution",
".",
"extended",
".",
"batch_reduce_to",
"(",
"tf",
".",
"distribute",
".",
"ReduceOp",
".",
"MEAN",
",",
"values_and_vars",
")",
"var_list",
"=",
"[",
"v",
"for",
"_",
",",
"v",
"in",
"values_and_vars",
"]",
"values_and_vars",
"=",
"zip",
"(",
"reduced_values",
",",
"var_list",
")",
"def",
"update_var",
"(",
"variable",
",",
"reduced_value",
")",
":",
"return",
"tf_compat",
".",
"assign",
"(",
"variable",
",",
"reduced_value",
")",
"update_objs",
"=",
"[",
"]",
"for",
"value",
",",
"var",
"in",
"values_and_vars",
":",
"update_objs",
".",
"append",
"(",
"distribution",
".",
"extended",
".",
"update",
"(",
"var",
",",
"update_var",
",",
"args",
"=",
"(",
"value",
",",
")",
")",
")",
"return",
"tf",
".",
"group",
"(",
"update_objs",
")",
"assign_objs",
"=",
"[",
"]",
"if",
"tf",
".",
"distribute",
".",
"get_replica_context",
"(",
")",
":",
"values_and_vars",
"=",
"[",
"]",
"for",
"weight",
",",
"mask",
",",
"_",
"in",
"self",
".",
"_pruning_vars",
":",
"masked_weight",
"=",
"tf",
".",
"math",
".",
"multiply",
"(",
"weight",
",",
"mask",
")",
"values_and_vars",
".",
"append",
"(",
"(",
"masked_weight",
",",
"weight",
")",
")",
"if",
"values_and_vars",
":",
"assign_objs",
".",
"append",
"(",
"tf",
".",
"distribute",
".",
"get_replica_context",
"(",
")",
".",
"merge_call",
"(",
"update_fn",
",",
"args",
"=",
"(",
"values_and_vars",
",",
")",
")",
")",
"else",
":",
"for",
"weight",
",",
"mask",
",",
"_",
"in",
"self",
".",
"_pruning_vars",
":",
"masked_weight",
"=",
"tf",
".",
"math",
".",
"multiply",
"(",
"weight",
",",
"mask",
")",
"assign_objs",
".",
"append",
"(",
"tf_compat",
".",
"assign",
"(",
"weight",
",",
"masked_weight",
")",
")",
"return",
"assign_objs"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/sparsity/keras/pruning_impl.py#L147-L192 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/retdec-3.2/scripts/type_extractor/type_extractor/arg_parser.py | python | get_arg_parser_for_merge_jsons | (doc) | return parser | Creates and returns argument parser. | Creates and returns argument parser. | [
"Creates",
"and",
"returns",
"argument",
"parser",
"."
] | def get_arg_parser_for_merge_jsons(doc):
"""Creates and returns argument parser."""
parser = argparse.ArgumentParser(
description=doc,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'-l', '--enable-logging', dest='enable_logging',
action='store_true', default=False,
help='enable emission of logging info'
)
parser.add_argument(
'-o', '--output', dest='output',
default='merge_output.json', help='choose output file'
)
parser.add_argument(
'--json-indent', dest='json_indent', action=GetJsonIndent,
default=4, help='choose indentation for json files'
)
parser.add_argument(
'--keep-unused-types', dest='keep_unused_types',
action='store_true', default=False,
help='type not used in any function is removed by default'
)
parser.add_argument(
'path', metavar='PATH', nargs='+',
help='path to json file or dir with json files'
)
return parser | [
"def",
"get_arg_parser_for_merge_jsons",
"(",
"doc",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"doc",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'-l'",
",",
"'--enable-logging'",
",",
"dest",
"=",
"'enable_logging'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'enable emission of logging info'",
")",
"parser",
".",
"add_argument",
"(",
"'-o'",
",",
"'--output'",
",",
"dest",
"=",
"'output'",
",",
"default",
"=",
"'merge_output.json'",
",",
"help",
"=",
"'choose output file'",
")",
"parser",
".",
"add_argument",
"(",
"'--json-indent'",
",",
"dest",
"=",
"'json_indent'",
",",
"action",
"=",
"GetJsonIndent",
",",
"default",
"=",
"4",
",",
"help",
"=",
"'choose indentation for json files'",
")",
"parser",
".",
"add_argument",
"(",
"'--keep-unused-types'",
",",
"dest",
"=",
"'keep_unused_types'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'type not used in any function is removed by default'",
")",
"parser",
".",
"add_argument",
"(",
"'path'",
",",
"metavar",
"=",
"'PATH'",
",",
"nargs",
"=",
"'+'",
",",
"help",
"=",
"'path to json file or dir with json files'",
")",
"return",
"parser"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/type_extractor/type_extractor/arg_parser.py#L59-L87 | |
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | src/visualizer/visualizer/core.py | python | Node.on_enter_notify_event | (self, view, target, event) | !
On Enter event handle.
@param self: class object.
@param view: view
@param target: target
@param event: event
@return none | !
On Enter event handle. | [
"!",
"On",
"Enter",
"event",
"handle",
"."
] | def on_enter_notify_event(self, view, target, event):
"""!
On Enter event handle.
@param self: class object.
@param view: view
@param target: target
@param event: event
@return none
"""
self.highlighted = True | [
"def",
"on_enter_notify_event",
"(",
"self",
",",
"view",
",",
"target",
",",
"event",
")",
":",
"self",
".",
"highlighted",
"=",
"True"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/src/visualizer/visualizer/core.py#L285-L295 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Job.py | python | Jobs.__init__ | (self, num, taskmaster) | Create 'num' jobs using the given taskmaster.
If 'num' is 1 or less, then a serial job will be used,
otherwise a parallel job with 'num' worker threads will
be used.
The 'num_jobs' attribute will be set to the actual number of jobs
allocated. If more than one job is requested but the Parallel
class can't do it, it gets reset to 1. Wrapping interfaces that
care should check the value of 'num_jobs' after initialization. | Create 'num' jobs using the given taskmaster. | [
"Create",
"num",
"jobs",
"using",
"the",
"given",
"taskmaster",
"."
] | def __init__(self, num, taskmaster):
"""
Create 'num' jobs using the given taskmaster.
If 'num' is 1 or less, then a serial job will be used,
otherwise a parallel job with 'num' worker threads will
be used.
The 'num_jobs' attribute will be set to the actual number of jobs
allocated. If more than one job is requested but the Parallel
class can't do it, it gets reset to 1. Wrapping interfaces that
care should check the value of 'num_jobs' after initialization.
"""
self.job = None
if num > 1:
stack_size = explicit_stack_size
if stack_size is None:
stack_size = default_stack_size
try:
self.job = Parallel(taskmaster, num, stack_size)
self.num_jobs = num
except NameError:
pass
if self.job is None:
self.job = Serial(taskmaster)
self.num_jobs = 1 | [
"def",
"__init__",
"(",
"self",
",",
"num",
",",
"taskmaster",
")",
":",
"self",
".",
"job",
"=",
"None",
"if",
"num",
">",
"1",
":",
"stack_size",
"=",
"explicit_stack_size",
"if",
"stack_size",
"is",
"None",
":",
"stack_size",
"=",
"default_stack_size",
"try",
":",
"self",
".",
"job",
"=",
"Parallel",
"(",
"taskmaster",
",",
"num",
",",
"stack_size",
")",
"self",
".",
"num_jobs",
"=",
"num",
"except",
"NameError",
":",
"pass",
"if",
"self",
".",
"job",
"is",
"None",
":",
"self",
".",
"job",
"=",
"Serial",
"(",
"taskmaster",
")",
"self",
".",
"num_jobs",
"=",
"1"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Job.py#L71-L98 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/utils/utils.py | python | _maybe_indices_to_slice | (indices: cp.ndarray) | return indices | Makes best effort to convert an array of indices into a python slice.
If the conversion is not possible, return input. `indices` are expected
to be valid. | Makes best effort to convert an array of indices into a python slice.
If the conversion is not possible, return input. `indices` are expected
to be valid. | [
"Makes",
"best",
"effort",
"to",
"convert",
"an",
"array",
"of",
"indices",
"into",
"a",
"python",
"slice",
".",
"If",
"the",
"conversion",
"is",
"not",
"possible",
"return",
"input",
".",
"indices",
"are",
"expected",
"to",
"be",
"valid",
"."
] | def _maybe_indices_to_slice(indices: cp.ndarray) -> Union[slice, cp.ndarray]:
"""Makes best effort to convert an array of indices into a python slice.
If the conversion is not possible, return input. `indices` are expected
to be valid.
"""
# TODO: improve efficiency by avoiding sync.
if len(indices) == 1:
x = indices[0].item()
return slice(x, x + 1)
if len(indices) == 2:
x1, x2 = indices[0].item(), indices[1].item()
return slice(x1, x2 + 1, x2 - x1)
start, step = indices[0].item(), (indices[1] - indices[0]).item()
stop = start + step * len(indices)
if (indices == cp.arange(start, stop, step)).all():
return slice(start, stop, step)
return indices | [
"def",
"_maybe_indices_to_slice",
"(",
"indices",
":",
"cp",
".",
"ndarray",
")",
"->",
"Union",
"[",
"slice",
",",
"cp",
".",
"ndarray",
"]",
":",
"# TODO: improve efficiency by avoiding sync.",
"if",
"len",
"(",
"indices",
")",
"==",
"1",
":",
"x",
"=",
"indices",
"[",
"0",
"]",
".",
"item",
"(",
")",
"return",
"slice",
"(",
"x",
",",
"x",
"+",
"1",
")",
"if",
"len",
"(",
"indices",
")",
"==",
"2",
":",
"x1",
",",
"x2",
"=",
"indices",
"[",
"0",
"]",
".",
"item",
"(",
")",
",",
"indices",
"[",
"1",
"]",
".",
"item",
"(",
")",
"return",
"slice",
"(",
"x1",
",",
"x2",
"+",
"1",
",",
"x2",
"-",
"x1",
")",
"start",
",",
"step",
"=",
"indices",
"[",
"0",
"]",
".",
"item",
"(",
")",
",",
"(",
"indices",
"[",
"1",
"]",
"-",
"indices",
"[",
"0",
"]",
")",
".",
"item",
"(",
")",
"stop",
"=",
"start",
"+",
"step",
"*",
"len",
"(",
"indices",
")",
"if",
"(",
"indices",
"==",
"cp",
".",
"arange",
"(",
"start",
",",
"stop",
",",
"step",
")",
")",
".",
"all",
"(",
")",
":",
"return",
"slice",
"(",
"start",
",",
"stop",
",",
"step",
")",
"return",
"indices"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/utils/utils.py#L495-L511 | |
lballabio/quantlib-old | 136336947ed4fea9ecc1da6edad188700e821739 | gensrc/gensrc/parameters/parameter.py | python | Value.printDebug | (self) | For debugging purposes, write the properties of this parameter to stdout. | For debugging purposes, write the properties of this parameter to stdout. | [
"For",
"debugging",
"purposes",
"write",
"the",
"properties",
"of",
"this",
"parameter",
"to",
"stdout",
"."
] | def printDebug(self):
"""For debugging purposes, write the properties of this parameter to stdout."""
print "type=" + str(type(self))
print "name=" + self.printValue(self.name_)
print "tensorRank=" + self.printValue(self.tensorRank_)
print "type=" + self.printValue(self.type_)
print "loop=" + self.printValue(self.loop_)
print "vecIter=" + self.printValue(self.vectorIterator_)
print "default=" + self.printValue(self.default_)
print "ignore=" + self.printValue(self.ignore_)
print "const=" + self.printValue(self.const_) | [
"def",
"printDebug",
"(",
"self",
")",
":",
"print",
"\"type=\"",
"+",
"str",
"(",
"type",
"(",
"self",
")",
")",
"print",
"\"name=\"",
"+",
"self",
".",
"printValue",
"(",
"self",
".",
"name_",
")",
"print",
"\"tensorRank=\"",
"+",
"self",
".",
"printValue",
"(",
"self",
".",
"tensorRank_",
")",
"print",
"\"type=\"",
"+",
"self",
".",
"printValue",
"(",
"self",
".",
"type_",
")",
"print",
"\"loop=\"",
"+",
"self",
".",
"printValue",
"(",
"self",
".",
"loop_",
")",
"print",
"\"vecIter=\"",
"+",
"self",
".",
"printValue",
"(",
"self",
".",
"vectorIterator_",
")",
"print",
"\"default=\"",
"+",
"self",
".",
"printValue",
"(",
"self",
".",
"default_",
")",
"print",
"\"ignore=\"",
"+",
"self",
".",
"printValue",
"(",
"self",
".",
"ignore_",
")",
"print",
"\"const=\"",
"+",
"self",
".",
"printValue",
"(",
"self",
".",
"const_",
")"
] | https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/parameters/parameter.py#L129-L139 | ||
google/mysql-protobuf | 467cda676afaa49e762c5c9164a43f6ad31a1fbf | protobuf/python/google/protobuf/message_factory.py | python | MessageFactory.GetPrototype | (self, descriptor) | return self._classes[descriptor.full_name] | Builds a proto2 message class based on the passed in descriptor.
Passing a descriptor with a fully qualified name matching a previous
invocation will cause the same class to be returned.
Args:
descriptor: The descriptor to build from.
Returns:
A class describing the passed in descriptor. | Builds a proto2 message class based on the passed in descriptor. | [
"Builds",
"a",
"proto2",
"message",
"class",
"based",
"on",
"the",
"passed",
"in",
"descriptor",
"."
] | def GetPrototype(self, descriptor):
"""Builds a proto2 message class based on the passed in descriptor.
Passing a descriptor with a fully qualified name matching a previous
invocation will cause the same class to be returned.
Args:
descriptor: The descriptor to build from.
Returns:
A class describing the passed in descriptor.
"""
if descriptor.full_name not in self._classes:
descriptor_name = descriptor.name
if sys.version_info[0] < 3: ##PY25
##!PY25 if str is bytes: # PY2
descriptor_name = descriptor.name.encode('ascii', 'ignore')
result_class = reflection.GeneratedProtocolMessageType(
descriptor_name,
(message.Message,),
{'DESCRIPTOR': descriptor, '__module__': None})
# If module not set, it wrongly points to the reflection.py module.
self._classes[descriptor.full_name] = result_class
for field in descriptor.fields:
if field.message_type:
self.GetPrototype(field.message_type)
for extension in result_class.DESCRIPTOR.extensions:
if extension.containing_type.full_name not in self._classes:
self.GetPrototype(extension.containing_type)
extended_class = self._classes[extension.containing_type.full_name]
extended_class.RegisterExtension(extension)
return self._classes[descriptor.full_name] | [
"def",
"GetPrototype",
"(",
"self",
",",
"descriptor",
")",
":",
"if",
"descriptor",
".",
"full_name",
"not",
"in",
"self",
".",
"_classes",
":",
"descriptor_name",
"=",
"descriptor",
".",
"name",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"##PY25",
"##!PY25 if str is bytes: # PY2",
"descriptor_name",
"=",
"descriptor",
".",
"name",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"result_class",
"=",
"reflection",
".",
"GeneratedProtocolMessageType",
"(",
"descriptor_name",
",",
"(",
"message",
".",
"Message",
",",
")",
",",
"{",
"'DESCRIPTOR'",
":",
"descriptor",
",",
"'__module__'",
":",
"None",
"}",
")",
"# If module not set, it wrongly points to the reflection.py module.",
"self",
".",
"_classes",
"[",
"descriptor",
".",
"full_name",
"]",
"=",
"result_class",
"for",
"field",
"in",
"descriptor",
".",
"fields",
":",
"if",
"field",
".",
"message_type",
":",
"self",
".",
"GetPrototype",
"(",
"field",
".",
"message_type",
")",
"for",
"extension",
"in",
"result_class",
".",
"DESCRIPTOR",
".",
"extensions",
":",
"if",
"extension",
".",
"containing_type",
".",
"full_name",
"not",
"in",
"self",
".",
"_classes",
":",
"self",
".",
"GetPrototype",
"(",
"extension",
".",
"containing_type",
")",
"extended_class",
"=",
"self",
".",
"_classes",
"[",
"extension",
".",
"containing_type",
".",
"full_name",
"]",
"extended_class",
".",
"RegisterExtension",
"(",
"extension",
")",
"return",
"self",
".",
"_classes",
"[",
"descriptor",
".",
"full_name",
"]"
] | https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/message_factory.py#L64-L95 | |
su2code/SU2 | 72b2fa977b64b9683a388920f05298a40d39e5c5 | SU2_PY/SU2_Nastran/pysu2_nastran.py | python | Solver.__temporalIteration | (self,time) | This method integrates in time the solution. | This method integrates in time the solution. | [
"This",
"method",
"integrates",
"in",
"time",
"the",
"solution",
"."
] | def __temporalIteration(self,time):
"""
This method integrates in time the solution.
"""
self.__reset(self.q)
self.__reset(self.qdot)
self.__reset(self.qddot)
self.__reset(self.a)
if not self.ImposedMotion:
eps = 1e-6
self.__SetLoads()
# Prediction step
self.a += (self.alpha_f)/(1-self.alpha_m)*self.qddot_n
self.a -= (self.alpha_m)/(1-self.alpha_m)*self.a_n
self.q = np.copy(self.q_n)
self.q += self.deltaT*self.qdot_n
self.q += (0.5-self.beta)*self.deltaT*self.deltaT*self.a_n
self.q += self.deltaT*self.deltaT*self.beta*self.a
self.qdot = np.copy(self.qdot_n)
self.qdot += (1-self.gamma)*self.deltaT*self.a_n
self.qdot += self.deltaT*self.gamma*self.a
# Correction step
res = self.__ComputeResidual()
while linalg.norm(res) >= eps:
St = self.__TangentOperator()
Deltaq = -1*(linalg.solve(St,res))
self.q += Deltaq
self.qdot += self.gammaPrime*Deltaq
self.qddot += self.betaPrime*Deltaq
res = self.__ComputeResidual()
self.a += (1-self.alpha_f)/(1-self.alpha_m)*self.qddot
else:
if self.ImposedMotionToSet:
if self.Config["RESTART_SOL"] == "NO":
# If yes we already set it in the __setRestart function
self.timeStartCoupling = time
iImposedFunc = 0
for imode in self.Config["IMPOSED_MODES"].keys():
for isuperposed in range(len(self.Config["IMPOSED_MODES"][imode])):
typeOfMotion = self.Config["IMPOSED_MODES"][imode][isuperposed]
parameters = self.Config["IMPOSED_PARAMETERS"][imode][isuperposed]
self.ImposedMotionFunction.append(ImposedMotionClass(self.timeStartCoupling, typeOfMotion, parameters, imode))
iImposedFunc += 1
self.ImposedMotionToSet = False
for iImposedFunc in range(len(self.ImposedMotionFunction)):
imode = self.ImposedMotionFunction[iImposedFunc].mode
self.q[imode] += self.ImposedMotionFunction[iImposedFunc].GetDispl(time)
self.qdot[imode] += self.ImposedMotionFunction[iImposedFunc].GetVel(time)
self.qddot[imode] += self.ImposedMotionFunction[iImposedFunc].GetAcc(time)
self.a = np.copy(self.qddot) | [
"def",
"__temporalIteration",
"(",
"self",
",",
"time",
")",
":",
"self",
".",
"__reset",
"(",
"self",
".",
"q",
")",
"self",
".",
"__reset",
"(",
"self",
".",
"qdot",
")",
"self",
".",
"__reset",
"(",
"self",
".",
"qddot",
")",
"self",
".",
"__reset",
"(",
"self",
".",
"a",
")",
"if",
"not",
"self",
".",
"ImposedMotion",
":",
"eps",
"=",
"1e-6",
"self",
".",
"__SetLoads",
"(",
")",
"# Prediction step",
"self",
".",
"a",
"+=",
"(",
"self",
".",
"alpha_f",
")",
"/",
"(",
"1",
"-",
"self",
".",
"alpha_m",
")",
"*",
"self",
".",
"qddot_n",
"self",
".",
"a",
"-=",
"(",
"self",
".",
"alpha_m",
")",
"/",
"(",
"1",
"-",
"self",
".",
"alpha_m",
")",
"*",
"self",
".",
"a_n",
"self",
".",
"q",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"q_n",
")",
"self",
".",
"q",
"+=",
"self",
".",
"deltaT",
"*",
"self",
".",
"qdot_n",
"self",
".",
"q",
"+=",
"(",
"0.5",
"-",
"self",
".",
"beta",
")",
"*",
"self",
".",
"deltaT",
"*",
"self",
".",
"deltaT",
"*",
"self",
".",
"a_n",
"self",
".",
"q",
"+=",
"self",
".",
"deltaT",
"*",
"self",
".",
"deltaT",
"*",
"self",
".",
"beta",
"*",
"self",
".",
"a",
"self",
".",
"qdot",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"qdot_n",
")",
"self",
".",
"qdot",
"+=",
"(",
"1",
"-",
"self",
".",
"gamma",
")",
"*",
"self",
".",
"deltaT",
"*",
"self",
".",
"a_n",
"self",
".",
"qdot",
"+=",
"self",
".",
"deltaT",
"*",
"self",
".",
"gamma",
"*",
"self",
".",
"a",
"# Correction step",
"res",
"=",
"self",
".",
"__ComputeResidual",
"(",
")",
"while",
"linalg",
".",
"norm",
"(",
"res",
")",
">=",
"eps",
":",
"St",
"=",
"self",
".",
"__TangentOperator",
"(",
")",
"Deltaq",
"=",
"-",
"1",
"*",
"(",
"linalg",
".",
"solve",
"(",
"St",
",",
"res",
")",
")",
"self",
".",
"q",
"+=",
"Deltaq",
"self",
".",
"qdot",
"+=",
"self",
".",
"gammaPrime",
"*",
"Deltaq",
"self",
".",
"qddot",
"+=",
"self",
".",
"betaPrime",
"*",
"Deltaq",
"res",
"=",
"self",
".",
"__ComputeResidual",
"(",
")",
"self",
".",
"a",
"+=",
"(",
"1",
"-",
"self",
".",
"alpha_f",
")",
"/",
"(",
"1",
"-",
"self",
".",
"alpha_m",
")",
"*",
"self",
".",
"qddot",
"else",
":",
"if",
"self",
".",
"ImposedMotionToSet",
":",
"if",
"self",
".",
"Config",
"[",
"\"RESTART_SOL\"",
"]",
"==",
"\"NO\"",
":",
"# If yes we already set it in the __setRestart function",
"self",
".",
"timeStartCoupling",
"=",
"time",
"iImposedFunc",
"=",
"0",
"for",
"imode",
"in",
"self",
".",
"Config",
"[",
"\"IMPOSED_MODES\"",
"]",
".",
"keys",
"(",
")",
":",
"for",
"isuperposed",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"Config",
"[",
"\"IMPOSED_MODES\"",
"]",
"[",
"imode",
"]",
")",
")",
":",
"typeOfMotion",
"=",
"self",
".",
"Config",
"[",
"\"IMPOSED_MODES\"",
"]",
"[",
"imode",
"]",
"[",
"isuperposed",
"]",
"parameters",
"=",
"self",
".",
"Config",
"[",
"\"IMPOSED_PARAMETERS\"",
"]",
"[",
"imode",
"]",
"[",
"isuperposed",
"]",
"self",
".",
"ImposedMotionFunction",
".",
"append",
"(",
"ImposedMotionClass",
"(",
"self",
".",
"timeStartCoupling",
",",
"typeOfMotion",
",",
"parameters",
",",
"imode",
")",
")",
"iImposedFunc",
"+=",
"1",
"self",
".",
"ImposedMotionToSet",
"=",
"False",
"for",
"iImposedFunc",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"ImposedMotionFunction",
")",
")",
":",
"imode",
"=",
"self",
".",
"ImposedMotionFunction",
"[",
"iImposedFunc",
"]",
".",
"mode",
"self",
".",
"q",
"[",
"imode",
"]",
"+=",
"self",
".",
"ImposedMotionFunction",
"[",
"iImposedFunc",
"]",
".",
"GetDispl",
"(",
"time",
")",
"self",
".",
"qdot",
"[",
"imode",
"]",
"+=",
"self",
".",
"ImposedMotionFunction",
"[",
"iImposedFunc",
"]",
".",
"GetVel",
"(",
"time",
")",
"self",
".",
"qddot",
"[",
"imode",
"]",
"+=",
"self",
".",
"ImposedMotionFunction",
"[",
"iImposedFunc",
"]",
".",
"GetAcc",
"(",
"time",
")",
"self",
".",
"a",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"qddot",
")"
] | https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2_Nastran/pysu2_nastran.py#L815-L874 | ||
codilime/veles | e65de5a7c268129acffcdb03034efd8d256d025c | python/veles/data/bindata.py | python | BinData.__repr__ | (self) | return 'BinData.from_spaced_hex({}, \'{}\')'.format(self._width, self) | Returns ``"BinData(self.width, str(self))"``. | Returns ``"BinData(self.width, str(self))"``. | [
"Returns",
"BinData",
"(",
"self",
".",
"width",
"str",
"(",
"self",
"))",
"."
] | def __repr__(self):
"""
Returns ``"BinData(self.width, str(self))"``.
"""
return 'BinData.from_spaced_hex({}, \'{}\')'.format(self._width, self) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'BinData.from_spaced_hex({}, \\'{}\\')'",
".",
"format",
"(",
"self",
".",
"_width",
",",
"self",
")"
] | https://github.com/codilime/veles/blob/e65de5a7c268129acffcdb03034efd8d256d025c/python/veles/data/bindata.py#L232-L236 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py | python | Pdb.do_condition | (self, arg) | condition bpnumber [condition]
Set a new condition for the breakpoint, an expression which
must evaluate to true before the breakpoint is honored. If
condition is absent, any existing condition is removed; i.e.,
the breakpoint is made unconditional. | condition bpnumber [condition]
Set a new condition for the breakpoint, an expression which
must evaluate to true before the breakpoint is honored. If
condition is absent, any existing condition is removed; i.e.,
the breakpoint is made unconditional. | [
"condition",
"bpnumber",
"[",
"condition",
"]",
"Set",
"a",
"new",
"condition",
"for",
"the",
"breakpoint",
"an",
"expression",
"which",
"must",
"evaluate",
"to",
"true",
"before",
"the",
"breakpoint",
"is",
"honored",
".",
"If",
"condition",
"is",
"absent",
"any",
"existing",
"condition",
"is",
"removed",
";",
"i",
".",
"e",
".",
"the",
"breakpoint",
"is",
"made",
"unconditional",
"."
] | def do_condition(self, arg):
"""condition bpnumber [condition]
Set a new condition for the breakpoint, an expression which
must evaluate to true before the breakpoint is honored. If
condition is absent, any existing condition is removed; i.e.,
the breakpoint is made unconditional.
"""
args = arg.split(' ', 1)
try:
cond = args[1]
except IndexError:
cond = None
try:
bp = self.get_bpbynumber(args[0].strip())
except IndexError:
self.error('Breakpoint number expected')
except ValueError as err:
self.error(err)
else:
bp.cond = cond
if not cond:
self.message('Breakpoint %d is now unconditional.' % bp.number)
else:
self.message('New condition set for breakpoint %d.' % bp.number) | [
"def",
"do_condition",
"(",
"self",
",",
"arg",
")",
":",
"args",
"=",
"arg",
".",
"split",
"(",
"' '",
",",
"1",
")",
"try",
":",
"cond",
"=",
"args",
"[",
"1",
"]",
"except",
"IndexError",
":",
"cond",
"=",
"None",
"try",
":",
"bp",
"=",
"self",
".",
"get_bpbynumber",
"(",
"args",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
"except",
"IndexError",
":",
"self",
".",
"error",
"(",
"'Breakpoint number expected'",
")",
"except",
"ValueError",
"as",
"err",
":",
"self",
".",
"error",
"(",
"err",
")",
"else",
":",
"bp",
".",
"cond",
"=",
"cond",
"if",
"not",
"cond",
":",
"self",
".",
"message",
"(",
"'Breakpoint %d is now unconditional.'",
"%",
"bp",
".",
"number",
")",
"else",
":",
"self",
".",
"message",
"(",
"'New condition set for breakpoint %d.'",
"%",
"bp",
".",
"number",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py#L799-L822 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/generators.py | python | find | (id) | return __generators.get (id, None) | Finds the generator with id. Returns None if not found. | Finds the generator with id. Returns None if not found. | [
"Finds",
"the",
"generator",
"with",
"id",
".",
"Returns",
"None",
"if",
"not",
"found",
"."
] | def find (id):
""" Finds the generator with id. Returns None if not found.
"""
assert isinstance(id, basestring)
return __generators.get (id, None) | [
"def",
"find",
"(",
"id",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"return",
"__generators",
".",
"get",
"(",
"id",
",",
"None",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/generators.py#L651-L655 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | Simulator.getContactForces | (self, aid, bid) | return _robotsim.Simulator_getContactForces(self, aid, bid) | getContactForces(Simulator self, int aid, int bid)
Returns the list of contact forces on object a at the last time step. | getContactForces(Simulator self, int aid, int bid) | [
"getContactForces",
"(",
"Simulator",
"self",
"int",
"aid",
"int",
"bid",
")"
] | def getContactForces(self, aid, bid):
"""
getContactForces(Simulator self, int aid, int bid)
Returns the list of contact forces on object a at the last time step.
"""
return _robotsim.Simulator_getContactForces(self, aid, bid) | [
"def",
"getContactForces",
"(",
"self",
",",
"aid",
",",
"bid",
")",
":",
"return",
"_robotsim",
".",
"Simulator_getContactForces",
"(",
"self",
",",
"aid",
",",
"bid",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L8409-L8418 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/mixture/base.py | python | BaseMixture.predict_proba | (self, X) | return np.exp(log_resp) | Predict posterior probability of data per each component.
Parameters
----------
X : array-like, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
Returns
-------
resp : array, shape (n_samples, n_components)
Returns the probability of the sample for each Gaussian
(state) in the model. | Predict posterior probability of data per each component. | [
"Predict",
"posterior",
"probability",
"of",
"data",
"per",
"each",
"component",
"."
] | def predict_proba(self, X):
"""Predict posterior probability of data per each component.
Parameters
----------
X : array-like, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
Returns
-------
resp : array, shape (n_samples, n_components)
Returns the probability of the sample for each Gaussian
(state) in the model.
"""
self._check_is_fitted()
X = _check_X(X, None, self.means_.shape[1])
_, log_resp = self._estimate_log_prob_resp(X)
return np.exp(log_resp) | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"_check_is_fitted",
"(",
")",
"X",
"=",
"_check_X",
"(",
"X",
",",
"None",
",",
"self",
".",
"means_",
".",
"shape",
"[",
"1",
"]",
")",
"_",
",",
"log_resp",
"=",
"self",
".",
"_estimate_log_prob_resp",
"(",
"X",
")",
"return",
"np",
".",
"exp",
"(",
"log_resp",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/base.py#L342-L360 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythplugins/mytharchive/mythburn/scripts/mythburn.py | python | getCPUCount | () | return cpucount | return the number of CPUs | return the number of CPUs | [
"return",
"the",
"number",
"of",
"CPUs"
] | def getCPUCount():
"""return the number of CPUs"""
# /proc/cpuinfo
cpustat = codecs.open("/proc/cpuinfo", 'r', 'utf-8')
cpudata = cpustat.readlines()
cpustat.close()
cpucount = 0
for line in cpudata:
tokens = line.split()
if len(tokens) > 0:
if tokens[0] == "processor":
cpucount += 1
if cpucount == 0:
cpucount = 1
write("Found %d CPUs" % cpucount)
return cpucount | [
"def",
"getCPUCount",
"(",
")",
":",
"# /proc/cpuinfo",
"cpustat",
"=",
"codecs",
".",
"open",
"(",
"\"/proc/cpuinfo\"",
",",
"'r'",
",",
"'utf-8'",
")",
"cpudata",
"=",
"cpustat",
".",
"readlines",
"(",
")",
"cpustat",
".",
"close",
"(",
")",
"cpucount",
"=",
"0",
"for",
"line",
"in",
"cpudata",
":",
"tokens",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"0",
":",
"if",
"tokens",
"[",
"0",
"]",
"==",
"\"processor\"",
":",
"cpucount",
"+=",
"1",
"if",
"cpucount",
"==",
"0",
":",
"cpucount",
"=",
"1",
"write",
"(",
"\"Found %d CPUs\"",
"%",
"cpucount",
")",
"return",
"cpucount"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythplugins/mytharchive/mythburn/scripts/mythburn.py#L362-L381 | |
TimoSaemann/caffe-segnet-cudnn5 | abcf30dca449245e101bf4ced519f716177f0885 | scripts/cpp_lint.py | python | FindEndOfExpressionInLine | (line, startpos, depth, startchar, endchar) | return (-1, depth) | Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching endchar: (index just after matching endchar, 0)
Otherwise: (-1, new depth at end of this line) | Find the position just after the matching endchar. | [
"Find",
"the",
"position",
"just",
"after",
"the",
"matching",
"endchar",
"."
] | def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
"""Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching endchar: (index just after matching endchar, 0)
Otherwise: (-1, new depth at end of this line)
"""
for i in xrange(startpos, len(line)):
if line[i] == startchar:
depth += 1
elif line[i] == endchar:
depth -= 1
if depth == 0:
return (i + 1, 0)
return (-1, depth) | [
"def",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"startpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"startpos",
",",
"len",
"(",
"line",
")",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"startchar",
":",
"depth",
"+=",
"1",
"elif",
"line",
"[",
"i",
"]",
"==",
"endchar",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"return",
"(",
"i",
"+",
"1",
",",
"0",
")",
"return",
"(",
"-",
"1",
",",
"depth",
")"
] | https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L1230-L1251 | |
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | python/dolfinx/fem/problem.py | python | NonlinearProblem.L | (self) | return self._L | Get the compiled linear form (the residual) | Get the compiled linear form (the residual) | [
"Get",
"the",
"compiled",
"linear",
"form",
"(",
"the",
"residual",
")"
] | def L(self) -> FormMetaClass:
"""Get the compiled linear form (the residual)"""
return self._L | [
"def",
"L",
"(",
"self",
")",
"->",
"FormMetaClass",
":",
"return",
"self",
".",
"_L"
] | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/fem/problem.py#L200-L202 | |
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/data/parameterdicts.py | python | _has_str_elems | (obj) | return all([isinstance(elem, str) for elem in obj]) | Returns True if all elements of iterable are str. | Returns True if all elements of iterable are str. | [
"Returns",
"True",
"if",
"all",
"elements",
"of",
"iterable",
"are",
"str",
"."
] | def _has_str_elems(obj):
"""Returns True if all elements of iterable are str."""
return all([isinstance(elem, str) for elem in obj]) | [
"def",
"_has_str_elems",
"(",
"obj",
")",
":",
"return",
"all",
"(",
"[",
"isinstance",
"(",
"elem",
",",
"str",
")",
"for",
"elem",
"in",
"obj",
"]",
")"
] | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/data/parameterdicts.py#L24-L26 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | VSIFReadL | (*args) | return _gdal.VSIFReadL(*args) | r"""VSIFReadL(unsigned int nMembSize, unsigned int nMembCount, VSILFILE fp) -> unsigned int | r"""VSIFReadL(unsigned int nMembSize, unsigned int nMembCount, VSILFILE fp) -> unsigned int | [
"r",
"VSIFReadL",
"(",
"unsigned",
"int",
"nMembSize",
"unsigned",
"int",
"nMembCount",
"VSILFILE",
"fp",
")",
"-",
">",
"unsigned",
"int"
] | def VSIFReadL(*args):
r"""VSIFReadL(unsigned int nMembSize, unsigned int nMembCount, VSILFILE fp) -> unsigned int"""
return _gdal.VSIFReadL(*args) | [
"def",
"VSIFReadL",
"(",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"VSIFReadL",
"(",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L165-L167 | |
commaai/openpilot | 4416c21b1e738ab7d04147c5ae52b5135e0cdb40 | pyextra/acados_template/acados_ocp.py | python | AcadosOcpConstraints.Jsbx | (self) | return self.__idxsbx | :math:`J_{sbx}` - matrix coefficient for soft bounds on x
at stages (1 to N-1);
Translated internally into :py:attr:`idxsbx`. | :math:`J_{sbx}` - matrix coefficient for soft bounds on x
at stages (1 to N-1);
Translated internally into :py:attr:`idxsbx`. | [
":",
"math",
":",
"J_",
"{",
"sbx",
"}",
"-",
"matrix",
"coefficient",
"for",
"soft",
"bounds",
"on",
"x",
"at",
"stages",
"(",
"1",
"to",
"N",
"-",
"1",
")",
";",
"Translated",
"internally",
"into",
":",
"py",
":",
"attr",
":",
"idxsbx",
"."
] | def Jsbx(self):
""":math:`J_{sbx}` - matrix coefficient for soft bounds on x
at stages (1 to N-1);
Translated internally into :py:attr:`idxsbx`."""
print_J_to_idx_note()
return self.__idxsbx | [
"def",
"Jsbx",
"(",
"self",
")",
":",
"print_J_to_idx_note",
"(",
")",
"return",
"self",
".",
"__idxsbx"
] | https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/pyextra/acados_template/acados_ocp.py#L1334-L1339 | |
hifiberry/hifiberry-os | 88c05213fb3e6230645cb4bf8eb8fceda8bd07d4 | buildroot/package/audiocontrol2/src/mpris.py | python | MPRISController.main_loop | (self) | Main loop:
- monitors state of all players
- pauses players if a new player starts palyback | Main loop:
- monitors state of all players
- pauses players if a new player starts palyback | [
"Main",
"loop",
":",
"-",
"monitors",
"state",
"of",
"all",
"players",
"-",
"pauses",
"players",
"if",
"a",
"new",
"player",
"starts",
"palyback"
] | def main_loop(self):
"""
Main loop:
- monitors state of all players
- pauses players if a new player starts palyback
"""
finished = False
md = Metadata()
active_players = set()
while not(finished):
new_player_started = None
for p in self.retrievePlayers():
if p not in self.state_table:
self.state_table[p] = PlayerState()
try:
state = self.retrieveState(p).lower()
except:
logging.info("Got no state from " + p)
state = "unknown"
self.state_table[p].state = state
# Check if playback started on a player that wasn't
# playing before
if state == PLAYING:
if (p not in active_players):
new_player_started = p
active_players.add(p)
md_old = self.state_table[p].metadata
md = self.retrieveMeta(p)
self.state_table[p].metadata = md
if md is not None:
if not(md.sameSong(md_old)):
self.metadata_notify(md)
else:
if p in active_players:
active_players.remove(p)
if new_player_started is not None:
if self.auto_pause:
logging.info(
"new player started, pausing other active players")
self.pause_inactive(new_player_started)
else:
logging.debug("auto-pause disabled")
time.sleep(0.2) | [
"def",
"main_loop",
"(",
"self",
")",
":",
"finished",
"=",
"False",
"md",
"=",
"Metadata",
"(",
")",
"active_players",
"=",
"set",
"(",
")",
"while",
"not",
"(",
"finished",
")",
":",
"new_player_started",
"=",
"None",
"for",
"p",
"in",
"self",
".",
"retrievePlayers",
"(",
")",
":",
"if",
"p",
"not",
"in",
"self",
".",
"state_table",
":",
"self",
".",
"state_table",
"[",
"p",
"]",
"=",
"PlayerState",
"(",
")",
"try",
":",
"state",
"=",
"self",
".",
"retrieveState",
"(",
"p",
")",
".",
"lower",
"(",
")",
"except",
":",
"logging",
".",
"info",
"(",
"\"Got no state from \"",
"+",
"p",
")",
"state",
"=",
"\"unknown\"",
"self",
".",
"state_table",
"[",
"p",
"]",
".",
"state",
"=",
"state",
"# Check if playback started on a player that wasn't",
"# playing before",
"if",
"state",
"==",
"PLAYING",
":",
"if",
"(",
"p",
"not",
"in",
"active_players",
")",
":",
"new_player_started",
"=",
"p",
"active_players",
".",
"add",
"(",
"p",
")",
"md_old",
"=",
"self",
".",
"state_table",
"[",
"p",
"]",
".",
"metadata",
"md",
"=",
"self",
".",
"retrieveMeta",
"(",
"p",
")",
"self",
".",
"state_table",
"[",
"p",
"]",
".",
"metadata",
"=",
"md",
"if",
"md",
"is",
"not",
"None",
":",
"if",
"not",
"(",
"md",
".",
"sameSong",
"(",
"md_old",
")",
")",
":",
"self",
".",
"metadata_notify",
"(",
"md",
")",
"else",
":",
"if",
"p",
"in",
"active_players",
":",
"active_players",
".",
"remove",
"(",
"p",
")",
"if",
"new_player_started",
"is",
"not",
"None",
":",
"if",
"self",
".",
"auto_pause",
":",
"logging",
".",
"info",
"(",
"\"new player started, pausing other active players\"",
")",
"self",
".",
"pause_inactive",
"(",
"new_player_started",
")",
"else",
":",
"logging",
".",
"debug",
"(",
"\"auto-pause disabled\"",
")",
"time",
".",
"sleep",
"(",
"0.2",
")"
] | https://github.com/hifiberry/hifiberry-os/blob/88c05213fb3e6230645cb4bf8eb8fceda8bd07d4/buildroot/package/audiocontrol2/src/mpris.py#L188-L239 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/elastic/agent/server/api.py | python | WorkerState.is_running | (state: "WorkerState") | return state in {WorkerState.HEALTHY, WorkerState.UNHEALTHY} | Returns:
True if the worker state represents workers still running
(e.g. that the process exists but not necessarily healthy). | Returns:
True if the worker state represents workers still running
(e.g. that the process exists but not necessarily healthy). | [
"Returns",
":",
"True",
"if",
"the",
"worker",
"state",
"represents",
"workers",
"still",
"running",
"(",
"e",
".",
"g",
".",
"that",
"the",
"process",
"exists",
"but",
"not",
"necessarily",
"healthy",
")",
"."
] | def is_running(state: "WorkerState") -> bool:
"""
Returns:
True if the worker state represents workers still running
(e.g. that the process exists but not necessarily healthy).
"""
return state in {WorkerState.HEALTHY, WorkerState.UNHEALTHY} | [
"def",
"is_running",
"(",
"state",
":",
"\"WorkerState\"",
")",
"->",
"bool",
":",
"return",
"state",
"in",
"{",
"WorkerState",
".",
"HEALTHY",
",",
"WorkerState",
".",
"UNHEALTHY",
"}"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/agent/server/api.py#L229-L235 | |
kismetwireless/kismet | a7c0dc270c960fb1f58bd9cec4601c201885fd4e | capture_sdr_rtladsb/KismetCaptureRtladsb/kismetexternal/__init__.py | python | ExternalInterface.add_task | (self, task, args = []) | Create a task from the provided async function, associating it
with the main loop and returning the task record. The task will
be automatically cancelled when the external interface exits
:return: asyncio task | Create a task from the provided async function, associating it
with the main loop and returning the task record. The task will
be automatically cancelled when the external interface exits | [
"Create",
"a",
"task",
"from",
"the",
"provided",
"async",
"function",
"associating",
"it",
"with",
"the",
"main",
"loop",
"and",
"returning",
"the",
"task",
"record",
".",
"The",
"task",
"will",
"be",
"automatically",
"cancelled",
"when",
"the",
"external",
"interface",
"exits"
] | def add_task(self, task, args = []):
"""
Create a task from the provided async function, associating it
with the main loop and returning the task record. The task will
be automatically cancelled when the external interface exits
:return: asyncio task
"""
try:
t = self.loop.create_task(task(*args))
self.additional_tasks.append(t)
return t
except Exception as e:
print("Failed to add asyncio task:", e)
traceback.print_exc(file=sys.stderr)
self.kill() | [
"def",
"add_task",
"(",
"self",
",",
"task",
",",
"args",
"=",
"[",
"]",
")",
":",
"try",
":",
"t",
"=",
"self",
".",
"loop",
".",
"create_task",
"(",
"task",
"(",
"*",
"args",
")",
")",
"self",
".",
"additional_tasks",
".",
"append",
"(",
"t",
")",
"return",
"t",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Failed to add asyncio task:\"",
",",
"e",
")",
"traceback",
".",
"print_exc",
"(",
"file",
"=",
"sys",
".",
"stderr",
")",
"self",
".",
"kill",
"(",
")"
] | https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtladsb/KismetCaptureRtladsb/kismetexternal/__init__.py#L411-L426 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py | python | Text.tag_delete | (self, *tagNames) | Delete all tags in TAGNAMES. | Delete all tags in TAGNAMES. | [
"Delete",
"all",
"tags",
"in",
"TAGNAMES",
"."
] | def tag_delete(self, *tagNames):
"""Delete all tags in TAGNAMES."""
self.tk.call((self._w, 'tag', 'delete') + tagNames) | [
"def",
"tag_delete",
"(",
"self",
",",
"*",
"tagNames",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'tag'",
",",
"'delete'",
")",
"+",
"tagNames",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L3130-L3132 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py | python | Series.__array__ | (self, dtype=None) | return np.asarray(self.array, dtype) | Return the values as a NumPy array.
Users should not call this directly. Rather, it is invoked by
:func:`numpy.array` and :func:`numpy.asarray`.
Parameters
----------
dtype : str or numpy.dtype, optional
The dtype to use for the resulting NumPy array. By default,
the dtype is inferred from the data.
Returns
-------
numpy.ndarray
The values in the series converted to a :class:`numpy.ndarary`
with the specified `dtype`.
See Also
--------
array : Create a new array from data.
Series.array : Zero-copy view to the array backing the Series.
Series.to_numpy : Series method for similar behavior.
Examples
--------
>>> ser = pd.Series([1, 2, 3])
>>> np.asarray(ser)
array([1, 2, 3])
For timezone-aware data, the timezones may be retained with
``dtype='object'``
>>> tzser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
>>> np.asarray(tzser, dtype="object")
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')],
dtype=object)
Or the values may be localized to UTC and the tzinfo discarded with
``dtype='datetime64[ns]'``
>>> np.asarray(tzser, dtype="datetime64[ns]") # doctest: +ELLIPSIS
array(['1999-12-31T23:00:00.000000000', ...],
dtype='datetime64[ns]') | Return the values as a NumPy array. | [
"Return",
"the",
"values",
"as",
"a",
"NumPy",
"array",
"."
] | def __array__(self, dtype=None) -> np.ndarray:
"""
Return the values as a NumPy array.
Users should not call this directly. Rather, it is invoked by
:func:`numpy.array` and :func:`numpy.asarray`.
Parameters
----------
dtype : str or numpy.dtype, optional
The dtype to use for the resulting NumPy array. By default,
the dtype is inferred from the data.
Returns
-------
numpy.ndarray
The values in the series converted to a :class:`numpy.ndarary`
with the specified `dtype`.
See Also
--------
array : Create a new array from data.
Series.array : Zero-copy view to the array backing the Series.
Series.to_numpy : Series method for similar behavior.
Examples
--------
>>> ser = pd.Series([1, 2, 3])
>>> np.asarray(ser)
array([1, 2, 3])
For timezone-aware data, the timezones may be retained with
``dtype='object'``
>>> tzser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
>>> np.asarray(tzser, dtype="object")
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')],
dtype=object)
Or the values may be localized to UTC and the tzinfo discarded with
``dtype='datetime64[ns]'``
>>> np.asarray(tzser, dtype="datetime64[ns]") # doctest: +ELLIPSIS
array(['1999-12-31T23:00:00.000000000', ...],
dtype='datetime64[ns]')
"""
return np.asarray(self.array, dtype) | [
"def",
"__array__",
"(",
"self",
",",
"dtype",
"=",
"None",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"np",
".",
"asarray",
"(",
"self",
".",
"array",
",",
"dtype",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py#L707-L754 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Main/glue/vboxapi.py | python | PlatformBase.getSessionObject | (self) | return None | Get a session object that can be used for opening machine sessions.
The oIVBox parameter is an getVirtualBox() return value, i.e. an
IVirtualBox reference.
See also openMachineSession. | Get a session object that can be used for opening machine sessions. | [
"Get",
"a",
"session",
"object",
"that",
"can",
"be",
"used",
"for",
"opening",
"machine",
"sessions",
"."
] | def getSessionObject(self):
"""
Get a session object that can be used for opening machine sessions.
The oIVBox parameter is an getVirtualBox() return value, i.e. an
IVirtualBox reference.
See also openMachineSession.
"""
return None | [
"def",
"getSessionObject",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Main/glue/vboxapi.py#L212-L221 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | _cnfmerge | (cnfs) | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def _cnfmerge(cnfs):
"""Internal function."""
if type(cnfs) is DictionaryType:
return cnfs
elif type(cnfs) in (NoneType, StringType):
return cnfs
else:
cnf = {}
for c in _flatten(cnfs):
try:
cnf.update(c)
except (AttributeError, TypeError), msg:
print "_cnfmerge: fallback due to:", msg
for k, v in c.items():
cnf[k] = v
return cnf | [
"def",
"_cnfmerge",
"(",
"cnfs",
")",
":",
"if",
"type",
"(",
"cnfs",
")",
"is",
"DictionaryType",
":",
"return",
"cnfs",
"elif",
"type",
"(",
"cnfs",
")",
"in",
"(",
"NoneType",
",",
"StringType",
")",
":",
"return",
"cnfs",
"else",
":",
"cnf",
"=",
"{",
"}",
"for",
"c",
"in",
"_flatten",
"(",
"cnfs",
")",
":",
"try",
":",
"cnf",
".",
"update",
"(",
"c",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
",",
"msg",
":",
"print",
"\"_cnfmerge: fallback due to:\"",
",",
"msg",
"for",
"k",
",",
"v",
"in",
"c",
".",
"items",
"(",
")",
":",
"cnf",
"[",
"k",
"]",
"=",
"v",
"return",
"cnf"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L106-L121 | ||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/ansic/cparse.py | python | p_initializer_1 | (t) | initializer : assignment_expression | initializer : assignment_expression | [
"initializer",
":",
"assignment_expression"
] | def p_initializer_1(t):
'initializer : assignment_expression'
pass | [
"def",
"p_initializer_1",
"(",
"t",
")",
":",
"pass"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L364-L366 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | StatusBar.GetFieldRect | (*args, **kwargs) | return _windows_.StatusBar_GetFieldRect(*args, **kwargs) | GetFieldRect(self, int i) -> Rect | GetFieldRect(self, int i) -> Rect | [
"GetFieldRect",
"(",
"self",
"int",
"i",
")",
"-",
">",
"Rect"
] | def GetFieldRect(*args, **kwargs):
"""GetFieldRect(self, int i) -> Rect"""
return _windows_.StatusBar_GetFieldRect(*args, **kwargs) | [
"def",
"GetFieldRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"StatusBar_GetFieldRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L1279-L1281 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/_collections.py | python | HTTPHeaderDict.itermerged | (self) | Iterate over all headers, merging duplicate ones together. | Iterate over all headers, merging duplicate ones together. | [
"Iterate",
"over",
"all",
"headers",
"merging",
"duplicate",
"ones",
"together",
"."
] | def itermerged(self):
"""Iterate over all headers, merging duplicate ones together."""
for key in self:
val = _dict_getitem(self, key)
yield val[0], ', '.join(val[1:]) | [
"def",
"itermerged",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"val",
"=",
"_dict_getitem",
"(",
"self",
",",
"key",
")",
"yield",
"val",
"[",
"0",
"]",
",",
"', '",
".",
"join",
"(",
"val",
"[",
"1",
":",
"]",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/_collections.py#L297-L301 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | DateTime.MakeFromTimezone | (*args, **kwargs) | return _misc_.DateTime_MakeFromTimezone(*args, **kwargs) | MakeFromTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime | MakeFromTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime | [
"MakeFromTimezone",
"(",
"self",
"wxDateTime",
"::",
"TimeZone",
"tz",
"bool",
"noDST",
"=",
"False",
")",
"-",
">",
"DateTime"
] | def MakeFromTimezone(*args, **kwargs):
"""MakeFromTimezone(self, wxDateTime::TimeZone tz, bool noDST=False) -> DateTime"""
return _misc_.DateTime_MakeFromTimezone(*args, **kwargs) | [
"def",
"MakeFromTimezone",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_MakeFromTimezone",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3934-L3936 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/freeorion_tools/_freeorion_tools.py | python | tech_is_complete | (tech) | return fo.getEmpire().techResearched(tech) | Return if tech is complete. | Return if tech is complete. | [
"Return",
"if",
"tech",
"is",
"complete",
"."
] | def tech_is_complete(tech):
"""
Return if tech is complete.
"""
return fo.getEmpire().techResearched(tech) | [
"def",
"tech_is_complete",
"(",
"tech",
")",
":",
"return",
"fo",
".",
"getEmpire",
"(",
")",
".",
"techResearched",
"(",
"tech",
")"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/freeorion_tools/_freeorion_tools.py#L50-L54 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/v7.9.317/third_party/jinja2/utils.py | python | object_type_repr | (obj) | return '%s object' % name | Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`). | Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`). | [
"Returns",
"the",
"name",
"of",
"the",
"object",
"s",
"type",
".",
"For",
"some",
"recognized",
"singletons",
"the",
"name",
"of",
"the",
"object",
"is",
"returned",
"instead",
".",
"(",
"For",
"example",
"for",
"None",
"and",
"Ellipsis",
")",
"."
] | def object_type_repr(obj):
"""Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
"""
if obj is None:
return 'None'
elif obj is Ellipsis:
return 'Ellipsis'
# __builtin__ in 2.x, builtins in 3.x
if obj.__class__.__module__ in ('__builtin__', 'builtins'):
name = obj.__class__.__name__
else:
name = obj.__class__.__module__ + '.' + obj.__class__.__name__
return '%s object' % name | [
"def",
"object_type_repr",
"(",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"'None'",
"elif",
"obj",
"is",
"Ellipsis",
":",
"return",
"'Ellipsis'",
"# __builtin__ in 2.x, builtins in 3.x",
"if",
"obj",
".",
"__class__",
".",
"__module__",
"in",
"(",
"'__builtin__'",
",",
"'builtins'",
")",
":",
"name",
"=",
"obj",
".",
"__class__",
".",
"__name__",
"else",
":",
"name",
"=",
"obj",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__class__",
".",
"__name__",
"return",
"'%s object'",
"%",
"name"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/utils.py#L160-L174 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/__init__.py | python | AutoScaleConnection.suspend_processes | (self, as_group, scaling_processes=None) | return self.get_status('SuspendProcesses', params) | Suspends Auto Scaling processes for an Auto Scaling group.
:type as_group: string
:param as_group: The auto scaling group to suspend processes on.
:type scaling_processes: list
:param scaling_processes: Processes you want to suspend. If omitted,
all processes will be suspended. | Suspends Auto Scaling processes for an Auto Scaling group. | [
"Suspends",
"Auto",
"Scaling",
"processes",
"for",
"an",
"Auto",
"Scaling",
"group",
"."
] | def suspend_processes(self, as_group, scaling_processes=None):
"""
Suspends Auto Scaling processes for an Auto Scaling group.
:type as_group: string
:param as_group: The auto scaling group to suspend processes on.
:type scaling_processes: list
:param scaling_processes: Processes you want to suspend. If omitted,
all processes will be suspended.
"""
params = {'AutoScalingGroupName': as_group}
if scaling_processes:
self.build_list_params(params, scaling_processes,
'ScalingProcesses')
return self.get_status('SuspendProcesses', params) | [
"def",
"suspend_processes",
"(",
"self",
",",
"as_group",
",",
"scaling_processes",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'AutoScalingGroupName'",
":",
"as_group",
"}",
"if",
"scaling_processes",
":",
"self",
".",
"build_list_params",
"(",
"params",
",",
"scaling_processes",
",",
"'ScalingProcesses'",
")",
"return",
"self",
".",
"get_status",
"(",
"'SuspendProcesses'",
",",
"params",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/autoscale/__init__.py#L584-L599 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/mindrecord/tools/cifar10_to_mr.py | python | Cifar10ToMR.transform | (self, fields=None) | return t.res | Encapsulate the run function to exit normally
Args:
fields (list[str], optional): A list of index fields. Default: None.
Returns:
MSRStatus, whether cifar10 is successfully transformed to MindRecord. | Encapsulate the run function to exit normally | [
"Encapsulate",
"the",
"run",
"function",
"to",
"exit",
"normally"
] | def transform(self, fields=None):
"""
Encapsulate the run function to exit normally
Args:
fields (list[str], optional): A list of index fields. Default: None.
Returns:
MSRStatus, whether cifar10 is successfully transformed to MindRecord.
"""
t = ExceptionThread(target=self.run, kwargs={'fields': fields})
t.daemon = True
t.start()
t.join()
if t.exitcode != 0:
raise t.exception
return t.res | [
"def",
"transform",
"(",
"self",
",",
"fields",
"=",
"None",
")",
":",
"t",
"=",
"ExceptionThread",
"(",
"target",
"=",
"self",
".",
"run",
",",
"kwargs",
"=",
"{",
"'fields'",
":",
"fields",
"}",
")",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")",
"t",
".",
"join",
"(",
")",
"if",
"t",
".",
"exitcode",
"!=",
"0",
":",
"raise",
"t",
".",
"exception",
"return",
"t",
".",
"res"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/tools/cifar10_to_mr.py#L110-L127 | |
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/cpp_wrappers/log_likelihood.py | python | multistart_hyperparameter_optimization | (
log_likelihood_optimizer,
num_multistarts,
randomness=None,
max_num_threads=DEFAULT_MAX_NUM_THREADS,
status=None,
) | return numpy.array(hyperparameters_opt) | r"""Select the hyperparameters that maximize the specified log likelihood measure of model fit (over the historical data) within the specified domain.
.. Note:: The following comments are copied to
:mod:`moe.optimal_learning.python.python_version.log_likelihood.multistart_hyperparameter_optimization`.
See :class:`moe.optimal_learning.python.cpp_wrappers.log_likelihood.GaussianProcessLogMarginalLikelihood` and
:class:`moe.optimal_learning.python.cpp_wrappers.log_likelihood.GaussianProcessLeaveOneOutLogLikelihood`
for an overview of some example log likelihood-like measures.
Optimizers are: null ('dumb' search), gradient descent, newton
Newton is the suggested optimizer.
'dumb' search means this will just evaluate the objective log likelihood measure at num_multistarts 'points'
(hyperparameters) in the domain, uniformly sampled using latin hypercube sampling.
The hyperparameter_optimizer_parameters input specifies the desired optimization technique as well as parameters controlling
its behavior (see :mod:`moe.optimal_learning.python.cpp_wrappers.optimization`).
See gpp_python_common.cpp for C++ enum declarations laying out the options for objective and optimizer types.
Currently, during optimization, we recommend that the coordinates of the initial guesses not differ from the
coordinates of the optima by more than about 1 order of magnitude. This is a very (VERY!) rough guideline for
sizing the domain and gd_parameters.num_multistarts; i.e., be wary of sets of initial guesses that cover the space too sparsely.
Note that the domain here must be specified in LOG-10 SPACE!
Solution is guaranteed to lie within the region specified by "domain"; note that this may not be a
true optima (i.e., the gradient may be substantially nonzero).
.. WARNING:: this function fails if NO improvement can be found! In that case,
the output will always be the first randomly chosen point. status will report failure.
:param ei_optimizer: object that optimizes (e.g., gradient descent, newton) log likelihood over a domain
:type ei_optimizer: cpp_wrappers.optimization.*Optimizer object
:param num_multistarts: number of times to multistart ``ei_optimizer`` (UNUSED, data is in log_likelihood_optimizer.optimizer_parameters)
:type num_multistarts: int > 0
:param randomness: RNGs used by C++ to generate initial guesses
:type randomness: RandomnessSourceContainer (C++ object; e.g., from C_GP.RandomnessSourceContainer())
:param max_num_threads: maximum number of threads to use, >= 1
:type max_num_threads: int > 0
:param status: (output) status messages from C++ (e.g., reporting on optimizer success, etc.)
:type status: dict
:return: hyperparameters that maximize the specified log likelihood measure within the specified domain
:rtype: array of float64 with shape (log_likelihood_optimizer.objective_function.num_hyperparameters) | r"""Select the hyperparameters that maximize the specified log likelihood measure of model fit (over the historical data) within the specified domain. | [
"r",
"Select",
"the",
"hyperparameters",
"that",
"maximize",
"the",
"specified",
"log",
"likelihood",
"measure",
"of",
"model",
"fit",
"(",
"over",
"the",
"historical",
"data",
")",
"within",
"the",
"specified",
"domain",
"."
] | def multistart_hyperparameter_optimization(
log_likelihood_optimizer,
num_multistarts,
randomness=None,
max_num_threads=DEFAULT_MAX_NUM_THREADS,
status=None,
):
r"""Select the hyperparameters that maximize the specified log likelihood measure of model fit (over the historical data) within the specified domain.
.. Note:: The following comments are copied to
:mod:`moe.optimal_learning.python.python_version.log_likelihood.multistart_hyperparameter_optimization`.
See :class:`moe.optimal_learning.python.cpp_wrappers.log_likelihood.GaussianProcessLogMarginalLikelihood` and
:class:`moe.optimal_learning.python.cpp_wrappers.log_likelihood.GaussianProcessLeaveOneOutLogLikelihood`
for an overview of some example log likelihood-like measures.
Optimizers are: null ('dumb' search), gradient descent, newton
Newton is the suggested optimizer.
'dumb' search means this will just evaluate the objective log likelihood measure at num_multistarts 'points'
(hyperparameters) in the domain, uniformly sampled using latin hypercube sampling.
The hyperparameter_optimizer_parameters input specifies the desired optimization technique as well as parameters controlling
its behavior (see :mod:`moe.optimal_learning.python.cpp_wrappers.optimization`).
See gpp_python_common.cpp for C++ enum declarations laying out the options for objective and optimizer types.
Currently, during optimization, we recommend that the coordinates of the initial guesses not differ from the
coordinates of the optima by more than about 1 order of magnitude. This is a very (VERY!) rough guideline for
sizing the domain and gd_parameters.num_multistarts; i.e., be wary of sets of initial guesses that cover the space too sparsely.
Note that the domain here must be specified in LOG-10 SPACE!
Solution is guaranteed to lie within the region specified by "domain"; note that this may not be a
true optima (i.e., the gradient may be substantially nonzero).
.. WARNING:: this function fails if NO improvement can be found! In that case,
the output will always be the first randomly chosen point. status will report failure.
:param ei_optimizer: object that optimizes (e.g., gradient descent, newton) log likelihood over a domain
:type ei_optimizer: cpp_wrappers.optimization.*Optimizer object
:param num_multistarts: number of times to multistart ``ei_optimizer`` (UNUSED, data is in log_likelihood_optimizer.optimizer_parameters)
:type num_multistarts: int > 0
:param randomness: RNGs used by C++ to generate initial guesses
:type randomness: RandomnessSourceContainer (C++ object; e.g., from C_GP.RandomnessSourceContainer())
:param max_num_threads: maximum number of threads to use, >= 1
:type max_num_threads: int > 0
:param status: (output) status messages from C++ (e.g., reporting on optimizer success, etc.)
:type status: dict
:return: hyperparameters that maximize the specified log likelihood measure within the specified domain
:rtype: array of float64 with shape (log_likelihood_optimizer.objective_function.num_hyperparameters)
"""
# Create enough randomness sources if none are specified.
if randomness is None:
randomness = C_GP.RandomnessSourceContainer(max_num_threads)
# Set seed based on less repeatable factors (e.g,. time)
randomness.SetRandomizedUniformGeneratorSeed(0)
randomness.SetRandomizedNormalRNGSeed(0)
# status must be an initialized dict for the call to C++.
if status is None:
status = {}
# C++ expects the domain in log10 space and in list form
domain_bounds_log10 = numpy.log10(log_likelihood_optimizer.domain._domain_bounds)
hyperparameters_opt = C_GP.multistart_hyperparameter_optimization(
log_likelihood_optimizer.optimizer_parameters,
cpp_utils.cppify(domain_bounds_log10),
cpp_utils.cppify(log_likelihood_optimizer.objective_function._points_sampled),
cpp_utils.cppify(log_likelihood_optimizer.objective_function._points_sampled_value),
log_likelihood_optimizer.objective_function.dim,
log_likelihood_optimizer.objective_function._num_sampled,
cpp_utils.cppify_hyperparameters(log_likelihood_optimizer.objective_function.hyperparameters),
cpp_utils.cppify(log_likelihood_optimizer.objective_function._points_sampled_noise_variance),
max_num_threads,
randomness,
status,
)
return numpy.array(hyperparameters_opt) | [
"def",
"multistart_hyperparameter_optimization",
"(",
"log_likelihood_optimizer",
",",
"num_multistarts",
",",
"randomness",
"=",
"None",
",",
"max_num_threads",
"=",
"DEFAULT_MAX_NUM_THREADS",
",",
"status",
"=",
"None",
",",
")",
":",
"# Create enough randomness sources if none are specified.",
"if",
"randomness",
"is",
"None",
":",
"randomness",
"=",
"C_GP",
".",
"RandomnessSourceContainer",
"(",
"max_num_threads",
")",
"# Set seed based on less repeatable factors (e.g,. time)",
"randomness",
".",
"SetRandomizedUniformGeneratorSeed",
"(",
"0",
")",
"randomness",
".",
"SetRandomizedNormalRNGSeed",
"(",
"0",
")",
"# status must be an initialized dict for the call to C++.",
"if",
"status",
"is",
"None",
":",
"status",
"=",
"{",
"}",
"# C++ expects the domain in log10 space and in list form",
"domain_bounds_log10",
"=",
"numpy",
".",
"log10",
"(",
"log_likelihood_optimizer",
".",
"domain",
".",
"_domain_bounds",
")",
"hyperparameters_opt",
"=",
"C_GP",
".",
"multistart_hyperparameter_optimization",
"(",
"log_likelihood_optimizer",
".",
"optimizer_parameters",
",",
"cpp_utils",
".",
"cppify",
"(",
"domain_bounds_log10",
")",
",",
"cpp_utils",
".",
"cppify",
"(",
"log_likelihood_optimizer",
".",
"objective_function",
".",
"_points_sampled",
")",
",",
"cpp_utils",
".",
"cppify",
"(",
"log_likelihood_optimizer",
".",
"objective_function",
".",
"_points_sampled_value",
")",
",",
"log_likelihood_optimizer",
".",
"objective_function",
".",
"dim",
",",
"log_likelihood_optimizer",
".",
"objective_function",
".",
"_num_sampled",
",",
"cpp_utils",
".",
"cppify_hyperparameters",
"(",
"log_likelihood_optimizer",
".",
"objective_function",
".",
"hyperparameters",
")",
",",
"cpp_utils",
".",
"cppify",
"(",
"log_likelihood_optimizer",
".",
"objective_function",
".",
"_points_sampled_noise_variance",
")",
",",
"max_num_threads",
",",
"randomness",
",",
"status",
",",
")",
"return",
"numpy",
".",
"array",
"(",
"hyperparameters_opt",
")"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/cpp_wrappers/log_likelihood.py#L64-L143 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py | python | IdleUserConfParser.RemoveEmptySections | (self) | remove any sections that have no options | remove any sections that have no options | [
"remove",
"any",
"sections",
"that",
"have",
"no",
"options"
] | def RemoveEmptySections(self):
"""
remove any sections that have no options
"""
for section in self.sections():
if not self.GetOptionList(section):
self.remove_section(section) | [
"def",
"RemoveEmptySections",
"(",
"self",
")",
":",
"for",
"section",
"in",
"self",
".",
"sections",
"(",
")",
":",
"if",
"not",
"self",
".",
"GetOptionList",
"(",
"section",
")",
":",
"self",
".",
"remove_section",
"(",
"section",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py#L83-L89 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros/rosmake/src/rosmake/engine.py | python | Printer.__init__ | (self) | Create singleton instance | Create singleton instance | [
"Create",
"singleton",
"instance"
] | def __init__(self):
""" Create singleton instance """
# Check whether we already have an instance
if Printer.__instance is None:
# Create and remember instance
Printer.__instance = Printer.__impl()
# Store instance reference as the only member in the handle
self.__dict__['_Printer__instance'] = Printer.__instance | [
"def",
"__init__",
"(",
"self",
")",
":",
"# Check whether we already have an instance",
"if",
"Printer",
".",
"__instance",
"is",
"None",
":",
"# Create and remember instance",
"Printer",
".",
"__instance",
"=",
"Printer",
".",
"__impl",
"(",
")",
"# Store instance reference as the only member in the handle",
"self",
".",
"__dict__",
"[",
"'_Printer__instance'",
"]",
"=",
"Printer",
".",
"__instance"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/rosmake/src/rosmake/engine.py#L99-L107 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/parso/py2/parso/python/tree.py | python | ImportName._dotted_as_names | (self) | Generator of (list(path), alias) where alias may be None. | Generator of (list(path), alias) where alias may be None. | [
"Generator",
"of",
"(",
"list",
"(",
"path",
")",
"alias",
")",
"where",
"alias",
"may",
"be",
"None",
"."
] | def _dotted_as_names(self):
"""Generator of (list(path), alias) where alias may be None."""
dotted_as_names = self.children[1]
if dotted_as_names.type == 'dotted_as_names':
as_names = dotted_as_names.children[::2]
else:
as_names = [dotted_as_names]
for as_name in as_names:
if as_name.type == 'dotted_as_name':
alias = as_name.children[2]
as_name = as_name.children[0]
else:
alias = None
if as_name.type == 'name':
yield [as_name], alias
else:
# dotted_names
yield as_name.children[::2], alias | [
"def",
"_dotted_as_names",
"(",
"self",
")",
":",
"dotted_as_names",
"=",
"self",
".",
"children",
"[",
"1",
"]",
"if",
"dotted_as_names",
".",
"type",
"==",
"'dotted_as_names'",
":",
"as_names",
"=",
"dotted_as_names",
".",
"children",
"[",
":",
":",
"2",
"]",
"else",
":",
"as_names",
"=",
"[",
"dotted_as_names",
"]",
"for",
"as_name",
"in",
"as_names",
":",
"if",
"as_name",
".",
"type",
"==",
"'dotted_as_name'",
":",
"alias",
"=",
"as_name",
".",
"children",
"[",
"2",
"]",
"as_name",
"=",
"as_name",
".",
"children",
"[",
"0",
"]",
"else",
":",
"alias",
"=",
"None",
"if",
"as_name",
".",
"type",
"==",
"'name'",
":",
"yield",
"[",
"as_name",
"]",
",",
"alias",
"else",
":",
"# dotted_names",
"yield",
"as_name",
".",
"children",
"[",
":",
":",
"2",
"]",
",",
"alias"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/parso/py2/parso/python/tree.py#L942-L960 | ||
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32comext/axdebug/gateways.py | python | DebugDocumentText.GetContextOfPosition | (self, charPos, maxChars) | Params are integers.
Return value must be PyIDebugDocumentContext object | Params are integers.
Return value must be PyIDebugDocumentContext object | [
"Params",
"are",
"integers",
".",
"Return",
"value",
"must",
"be",
"PyIDebugDocumentContext",
"object"
] | def GetContextOfPosition(self, charPos, maxChars):
"""Params are integers.
Return value must be PyIDebugDocumentContext object
"""
print(self)
RaiseNotImpl("GetContextOfPosition") | [
"def",
"GetContextOfPosition",
"(",
"self",
",",
"charPos",
",",
"maxChars",
")",
":",
"print",
"(",
"self",
")",
"RaiseNotImpl",
"(",
"\"GetContextOfPosition\"",
")"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32comext/axdebug/gateways.py#L212-L217 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/database.py | python | DistributionPath.get_distributions | (self) | Provides an iterator that looks for distributions and returns
:class:`InstalledDistribution` or
:class:`EggInfoDistribution` instances for each one of them.
:rtype: iterator of :class:`InstalledDistribution` and
:class:`EggInfoDistribution` instances | [] | def get_distributions(self):
"""
Provides an iterator that looks for distributions and returns
:class:`InstalledDistribution` or
:class:`EggInfoDistribution` instances for each one of them.
:rtype: iterator of :class:`InstalledDistribution` and
:class:`EggInfoDistribution` instances
"""
if not self._cache_enabled:
for dist in self._yield_distributions():
yield dist
else:
self._generate_cache()
for dist in self._cache.path.values():
yield dist
if self._include_egg:
for dist in self._cache_egg.path.values():
yield dist | [
"def",
"get_distributions",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_cache_enabled",
":",
"for",
"dist",
"in",
"self",
".",
"_yield_distributions",
"(",
")",
":",
"yield",
"dist",
"else",
":",
"self",
".",
"_generate_cache",
"(",
")",
"for",
"dist",
"in",
"self",
".",
"_cache",
".",
"path",
".",
"values",
"(",
")",
":",
"yield",
"dist",
"if",
"self",
".",
"_include_egg",
":",
"for",
"dist",
"in",
"self",
".",
"_cache_egg",
".",
"path",
".",
"values",
"(",
")",
":",
"yield",
"dist"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/database.py#L399-L439 | |||
KhronosGroup/Vulkan-Headers | b32da5329b50e3cb96229aaecba9ded032fe29cc | registry/vkconventions.py | python | VulkanConventions.is_nextpointer_member | (self, paramtype, paramname) | return paramtype == 'void' and paramname == self.nextpointer_member_name | Determine if member type and name match the next pointer chain member. | Determine if member type and name match the next pointer chain member. | [
"Determine",
"if",
"member",
"type",
"and",
"name",
"match",
"the",
"next",
"pointer",
"chain",
"member",
"."
] | def is_nextpointer_member(self, paramtype, paramname):
"""Determine if member type and name match the next pointer chain member."""
return paramtype == 'void' and paramname == self.nextpointer_member_name | [
"def",
"is_nextpointer_member",
"(",
"self",
",",
"paramtype",
",",
"paramname",
")",
":",
"return",
"paramtype",
"==",
"'void'",
"and",
"paramname",
"==",
"self",
".",
"nextpointer_member_name"
] | https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/vkconventions.py#L85-L87 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/client/timeline.py | python | _TensorTracker.create_time | (self) | return self._create_time | Timestamp when this tensor was created (long integer). | Timestamp when this tensor was created (long integer). | [
"Timestamp",
"when",
"this",
"tensor",
"was",
"created",
"(",
"long",
"integer",
")",
"."
] | def create_time(self):
"""Timestamp when this tensor was created (long integer)."""
return self._create_time | [
"def",
"create_time",
"(",
"self",
")",
":",
"return",
"self",
".",
"_create_time"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/timeline.py#L304-L306 | |
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/containers.py | python | RepeatedScalarFieldContainer.__setitem__ | (self, key, value) | Sets the item on the specified position. | Sets the item on the specified position. | [
"Sets",
"the",
"item",
"on",
"the",
"specified",
"position",
"."
] | def __setitem__(self, key, value):
"""Sets the item on the specified position."""
if isinstance(key, slice): # PY3
if key.step is not None:
raise ValueError('Extended slices not supported')
self.__setslice__(key.start, key.stop, value)
else:
self._values[key] = self._type_checker.CheckValue(value)
self._message_listener.Modified() | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"slice",
")",
":",
"# PY3",
"if",
"key",
".",
"step",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Extended slices not supported'",
")",
"self",
".",
"__setslice__",
"(",
"key",
".",
"start",
",",
"key",
".",
"stop",
",",
"value",
")",
"else",
":",
"self",
".",
"_values",
"[",
"key",
"]",
"=",
"self",
".",
"_type_checker",
".",
"CheckValue",
"(",
"value",
")",
"self",
".",
"_message_listener",
".",
"Modified",
"(",
")"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/containers.py#L166-L174 | ||
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/well_known_types.py | python | ListValue.__getitem__ | (self, index) | return _GetStructValue(self.values.__getitem__(index)) | Retrieves item by the specified index. | Retrieves item by the specified index. | [
"Retrieves",
"item",
"by",
"the",
"specified",
"index",
"."
] | def __getitem__(self, index):
"""Retrieves item by the specified index."""
return _GetStructValue(self.values.__getitem__(index)) | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"return",
"_GetStructValue",
"(",
"self",
".",
"values",
".",
"__getitem__",
"(",
"index",
")",
")"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/well_known_types.py#L821-L823 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/MetaSearch/plugin.py | python | MetaSearchPlugin.unload | (self) | teardown | teardown | [
"teardown"
] | def unload(self):
"""teardown"""
# remove the plugin menu item and icon
self.iface.removePluginWebMenu(self.web_menu, self.action_run)
self.iface.removePluginWebMenu(self.web_menu, self.action_help)
self.iface.removeWebToolBarIcon(self.action_run) | [
"def",
"unload",
"(",
"self",
")",
":",
"# remove the plugin menu item and icon",
"self",
".",
"iface",
".",
"removePluginWebMenu",
"(",
"self",
".",
"web_menu",
",",
"self",
".",
"action_run",
")",
"self",
".",
"iface",
".",
"removePluginWebMenu",
"(",
"self",
".",
"web_menu",
",",
"self",
".",
"action_help",
")",
"self",
".",
"iface",
".",
"removeWebToolBarIcon",
"(",
"self",
".",
"action_run",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/MetaSearch/plugin.py#L85-L91 | ||
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/python/caffe/net_spec.py | python | to_proto | (*tops) | return net | Generate a NetParameter that contains all layers needed to compute
all arguments. | Generate a NetParameter that contains all layers needed to compute
all arguments. | [
"Generate",
"a",
"NetParameter",
"that",
"contains",
"all",
"layers",
"needed",
"to",
"compute",
"all",
"arguments",
"."
] | def to_proto(*tops):
"""Generate a NetParameter that contains all layers needed to compute
all arguments."""
layers = OrderedDict()
autonames = Counter()
for top in tops:
top.fn._to_proto(layers, {}, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net | [
"def",
"to_proto",
"(",
"*",
"tops",
")",
":",
"layers",
"=",
"OrderedDict",
"(",
")",
"autonames",
"=",
"Counter",
"(",
")",
"for",
"top",
"in",
"tops",
":",
"top",
".",
"fn",
".",
"_to_proto",
"(",
"layers",
",",
"{",
"}",
",",
"autonames",
")",
"net",
"=",
"caffe_pb2",
".",
"NetParameter",
"(",
")",
"net",
".",
"layer",
".",
"extend",
"(",
"layers",
".",
"values",
"(",
")",
")",
"return",
"net"
] | https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/python/caffe/net_spec.py#L43-L53 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/xrc.py | python | XmlResource.InitAllHandlers | (*args, **kwargs) | return _xrc.XmlResource_InitAllHandlers(*args, **kwargs) | InitAllHandlers(self) | InitAllHandlers(self) | [
"InitAllHandlers",
"(",
"self",
")"
] | def InitAllHandlers(*args, **kwargs):
"""InitAllHandlers(self)"""
return _xrc.XmlResource_InitAllHandlers(*args, **kwargs) | [
"def",
"InitAllHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlResource_InitAllHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/xrc.py#L98-L100 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/__init__.py | python | Process.oneshot | (self) | Utility context manager which considerably speeds up the
retrieval of multiple process information at the same time.
Internally different process info (e.g. name, ppid, uids,
gids, ...) may be fetched by using the same routine, but
only one information is returned and the others are discarded.
When using this context manager the internal routine is
executed once (in the example below on name()) and the
other info are cached.
The cache is cleared when exiting the context manager block.
The advice is to use this every time you retrieve more than
one information about the process. If you're lucky, you'll
get a hell of a speedup.
>>> import psutil
>>> p = psutil.Process()
>>> with p.oneshot():
... p.name() # collect multiple info
... p.cpu_times() # return cached value
... p.cpu_percent() # return cached value
... p.create_time() # return cached value
...
>>> | Utility context manager which considerably speeds up the
retrieval of multiple process information at the same time. | [
"Utility",
"context",
"manager",
"which",
"considerably",
"speeds",
"up",
"the",
"retrieval",
"of",
"multiple",
"process",
"information",
"at",
"the",
"same",
"time",
"."
] | def oneshot(self):
"""Utility context manager which considerably speeds up the
retrieval of multiple process information at the same time.
Internally different process info (e.g. name, ppid, uids,
gids, ...) may be fetched by using the same routine, but
only one information is returned and the others are discarded.
When using this context manager the internal routine is
executed once (in the example below on name()) and the
other info are cached.
The cache is cleared when exiting the context manager block.
The advice is to use this every time you retrieve more than
one information about the process. If you're lucky, you'll
get a hell of a speedup.
>>> import psutil
>>> p = psutil.Process()
>>> with p.oneshot():
... p.name() # collect multiple info
... p.cpu_times() # return cached value
... p.cpu_percent() # return cached value
... p.create_time() # return cached value
...
>>>
"""
with self._lock:
if hasattr(self, "_cache"):
# NOOP: this covers the use case where the user enters the
# context twice:
#
# >>> with p.oneshot():
# ... with p.oneshot():
# ...
#
# Also, since as_dict() internally uses oneshot()
# I expect that the code below will be a pretty common
# "mistake" that the user will make, so let's guard
# against that:
#
# >>> with p.oneshot():
# ... p.as_dict()
# ...
yield
else:
try:
# cached in case cpu_percent() is used
self.cpu_times.cache_activate(self)
# cached in case memory_percent() is used
self.memory_info.cache_activate(self)
# cached in case parent() is used
self.ppid.cache_activate(self)
# cached in case username() is used
if POSIX:
self.uids.cache_activate(self)
# specific implementation cache
self._proc.oneshot_enter()
yield
finally:
self.cpu_times.cache_deactivate(self)
self.memory_info.cache_deactivate(self)
self.ppid.cache_deactivate(self)
if POSIX:
self.uids.cache_deactivate(self)
self._proc.oneshot_exit() | [
"def",
"oneshot",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_cache\"",
")",
":",
"# NOOP: this covers the use case where the user enters the",
"# context twice:",
"#",
"# >>> with p.oneshot():",
"# ... with p.oneshot():",
"# ...",
"#",
"# Also, since as_dict() internally uses oneshot()",
"# I expect that the code below will be a pretty common",
"# \"mistake\" that the user will make, so let's guard",
"# against that:",
"#",
"# >>> with p.oneshot():",
"# ... p.as_dict()",
"# ...",
"yield",
"else",
":",
"try",
":",
"# cached in case cpu_percent() is used",
"self",
".",
"cpu_times",
".",
"cache_activate",
"(",
"self",
")",
"# cached in case memory_percent() is used",
"self",
".",
"memory_info",
".",
"cache_activate",
"(",
"self",
")",
"# cached in case parent() is used",
"self",
".",
"ppid",
".",
"cache_activate",
"(",
"self",
")",
"# cached in case username() is used",
"if",
"POSIX",
":",
"self",
".",
"uids",
".",
"cache_activate",
"(",
"self",
")",
"# specific implementation cache",
"self",
".",
"_proc",
".",
"oneshot_enter",
"(",
")",
"yield",
"finally",
":",
"self",
".",
"cpu_times",
".",
"cache_deactivate",
"(",
"self",
")",
"self",
".",
"memory_info",
".",
"cache_deactivate",
"(",
"self",
")",
"self",
".",
"ppid",
".",
"cache_deactivate",
"(",
"self",
")",
"if",
"POSIX",
":",
"self",
".",
"uids",
".",
"cache_deactivate",
"(",
"self",
")",
"self",
".",
"_proc",
".",
"oneshot_exit",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/__init__.py#L441-L505 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/core/defchararray.py | python | istitle | (a) | return _vec_string(a, bool_, 'istitle') | Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise.
Call `str.istitle` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array_like of str or unicode
Returns
-------
out : ndarray
Output array of bools
See also
--------
str.istitle | Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise. | [
"Returns",
"true",
"for",
"each",
"element",
"if",
"the",
"element",
"is",
"a",
"titlecased",
"string",
"and",
"there",
"is",
"at",
"least",
"one",
"character",
"false",
"otherwise",
"."
] | def istitle(a):
"""
Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise.
Call `str.istitle` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array_like of str or unicode
Returns
-------
out : ndarray
Output array of bools
See also
--------
str.istitle
"""
return _vec_string(a, bool_, 'istitle') | [
"def",
"istitle",
"(",
"a",
")",
":",
"return",
"_vec_string",
"(",
"a",
",",
"bool_",
",",
"'istitle'",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/core/defchararray.py#L820-L842 | |
assimp/assimp | 97c7e084c2f7f8c9355ea42f73605890481bddc5 | port/PyAssimp/scripts/transformations.py | python | random_quaternion | (rand=None) | return numpy.array((numpy.sin(t1)*r1,
numpy.cos(t1)*r1,
numpy.sin(t2)*r2,
numpy.cos(t2)*r2), dtype=numpy.float64) | Return uniform random unit quaternion.
rand: array like or None
Three independent random variables that are uniformly distributed
between 0 and 1.
>>> q = random_quaternion()
>>> numpy.allclose(1.0, vector_norm(q))
True
>>> q = random_quaternion(numpy.random.random(3))
>>> q.shape
(4,) | Return uniform random unit quaternion. | [
"Return",
"uniform",
"random",
"unit",
"quaternion",
"."
] | def random_quaternion(rand=None):
"""Return uniform random unit quaternion.
rand: array like or None
Three independent random variables that are uniformly distributed
between 0 and 1.
>>> q = random_quaternion()
>>> numpy.allclose(1.0, vector_norm(q))
True
>>> q = random_quaternion(numpy.random.random(3))
>>> q.shape
(4,)
"""
if rand is None:
rand = numpy.random.rand(3)
else:
assert len(rand) == 3
r1 = numpy.sqrt(1.0 - rand[0])
r2 = numpy.sqrt(rand[0])
pi2 = math.pi * 2.0
t1 = pi2 * rand[1]
t2 = pi2 * rand[2]
return numpy.array((numpy.sin(t1)*r1,
numpy.cos(t1)*r1,
numpy.sin(t2)*r2,
numpy.cos(t2)*r2), dtype=numpy.float64) | [
"def",
"random_quaternion",
"(",
"rand",
"=",
"None",
")",
":",
"if",
"rand",
"is",
"None",
":",
"rand",
"=",
"numpy",
".",
"random",
".",
"rand",
"(",
"3",
")",
"else",
":",
"assert",
"len",
"(",
"rand",
")",
"==",
"3",
"r1",
"=",
"numpy",
".",
"sqrt",
"(",
"1.0",
"-",
"rand",
"[",
"0",
"]",
")",
"r2",
"=",
"numpy",
".",
"sqrt",
"(",
"rand",
"[",
"0",
"]",
")",
"pi2",
"=",
"math",
".",
"pi",
"*",
"2.0",
"t1",
"=",
"pi2",
"*",
"rand",
"[",
"1",
"]",
"t2",
"=",
"pi2",
"*",
"rand",
"[",
"2",
"]",
"return",
"numpy",
".",
"array",
"(",
"(",
"numpy",
".",
"sin",
"(",
"t1",
")",
"*",
"r1",
",",
"numpy",
".",
"cos",
"(",
"t1",
")",
"*",
"r1",
",",
"numpy",
".",
"sin",
"(",
"t2",
")",
"*",
"r2",
",",
"numpy",
".",
"cos",
"(",
"t2",
")",
"*",
"r2",
")",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")"
] | https://github.com/assimp/assimp/blob/97c7e084c2f7f8c9355ea42f73605890481bddc5/port/PyAssimp/scripts/transformations.py#L1311-L1338 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/story/story.py | python | Story.__init__ | (self, shared_state_class, name='', labels=None,
is_local=False, make_javascript_deterministic=True,
grouping_keys=None) | Args:
make_javascript_deterministic: Whether JavaScript performed on
the page is made deterministic across multiple runs. This
requires that the web content is served via Web Page Replay
to take effect. This setting does not affect stories containing no web
content or where the HTTP MIME type is not text/html.See also:
_InjectScripts method in third_party/web-page-replay/httpclient.py. | Args:
make_javascript_deterministic: Whether JavaScript performed on
the page is made deterministic across multiple runs. This
requires that the web content is served via Web Page Replay
to take effect. This setting does not affect stories containing no web
content or where the HTTP MIME type is not text/html.See also:
_InjectScripts method in third_party/web-page-replay/httpclient.py. | [
"Args",
":",
"make_javascript_deterministic",
":",
"Whether",
"JavaScript",
"performed",
"on",
"the",
"page",
"is",
"made",
"deterministic",
"across",
"multiple",
"runs",
".",
"This",
"requires",
"that",
"the",
"web",
"content",
"is",
"served",
"via",
"Web",
"Page",
"Replay",
"to",
"take",
"effect",
".",
"This",
"setting",
"does",
"not",
"affect",
"stories",
"containing",
"no",
"web",
"content",
"or",
"where",
"the",
"HTTP",
"MIME",
"type",
"is",
"not",
"text",
"/",
"html",
".",
"See",
"also",
":",
"_InjectScripts",
"method",
"in",
"third_party",
"/",
"web",
"-",
"page",
"-",
"replay",
"/",
"httpclient",
".",
"py",
"."
] | def __init__(self, shared_state_class, name='', labels=None,
is_local=False, make_javascript_deterministic=True,
grouping_keys=None):
"""
Args:
make_javascript_deterministic: Whether JavaScript performed on
the page is made deterministic across multiple runs. This
requires that the web content is served via Web Page Replay
to take effect. This setting does not affect stories containing no web
content or where the HTTP MIME type is not text/html.See also:
_InjectScripts method in third_party/web-page-replay/httpclient.py.
"""
assert issubclass(shared_state_class,
shared_state_module.SharedState)
self._shared_state_class = shared_state_class
self._name = name
global _next_story_id
self._id = _next_story_id
_next_story_id += 1
if labels is None:
labels = set([])
elif isinstance(labels, list):
labels = set(labels)
else:
assert isinstance(labels, set)
self._labels = labels
self._is_local = is_local
self._make_javascript_deterministic = make_javascript_deterministic
if grouping_keys is None:
grouping_keys = {}
else:
assert isinstance(grouping_keys, dict)
self._grouping_keys = grouping_keys | [
"def",
"__init__",
"(",
"self",
",",
"shared_state_class",
",",
"name",
"=",
"''",
",",
"labels",
"=",
"None",
",",
"is_local",
"=",
"False",
",",
"make_javascript_deterministic",
"=",
"True",
",",
"grouping_keys",
"=",
"None",
")",
":",
"assert",
"issubclass",
"(",
"shared_state_class",
",",
"shared_state_module",
".",
"SharedState",
")",
"self",
".",
"_shared_state_class",
"=",
"shared_state_class",
"self",
".",
"_name",
"=",
"name",
"global",
"_next_story_id",
"self",
".",
"_id",
"=",
"_next_story_id",
"_next_story_id",
"+=",
"1",
"if",
"labels",
"is",
"None",
":",
"labels",
"=",
"set",
"(",
"[",
"]",
")",
"elif",
"isinstance",
"(",
"labels",
",",
"list",
")",
":",
"labels",
"=",
"set",
"(",
"labels",
")",
"else",
":",
"assert",
"isinstance",
"(",
"labels",
",",
"set",
")",
"self",
".",
"_labels",
"=",
"labels",
"self",
".",
"_is_local",
"=",
"is_local",
"self",
".",
"_make_javascript_deterministic",
"=",
"make_javascript_deterministic",
"if",
"grouping_keys",
"is",
"None",
":",
"grouping_keys",
"=",
"{",
"}",
"else",
":",
"assert",
"isinstance",
"(",
"grouping_keys",
",",
"dict",
")",
"self",
".",
"_grouping_keys",
"=",
"grouping_keys"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/story/story.py#L31-L63 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/mooseutils/gitutils.py | python | git_remotes | (working_dir=None) | return lookup | Return URL to name remotes. | Return URL to name remotes. | [
"Return",
"URL",
"to",
"name",
"remotes",
"."
] | def git_remotes(working_dir=None):
"""
Return URL to name remotes.
"""
if working_dir is None: working_dir = os.getcwd()
lookup = dict()
for remote in mooseutils.check_output(['git', 'remote', '-v'], encoding='utf-8', cwd=working_dir).strip(' \n').split('\n'):
name, addr = remote.split(maxsplit=1)
lookup[addr] = name
return lookup | [
"def",
"git_remotes",
"(",
"working_dir",
"=",
"None",
")",
":",
"if",
"working_dir",
"is",
"None",
":",
"working_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"lookup",
"=",
"dict",
"(",
")",
"for",
"remote",
"in",
"mooseutils",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'remote'",
",",
"'-v'",
"]",
",",
"encoding",
"=",
"'utf-8'",
",",
"cwd",
"=",
"working_dir",
")",
".",
"strip",
"(",
"' \\n'",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"name",
",",
"addr",
"=",
"remote",
".",
"split",
"(",
"maxsplit",
"=",
"1",
")",
"lookup",
"[",
"addr",
"]",
"=",
"name",
"return",
"lookup"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mooseutils/gitutils.py#L211-L220 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | TestFontEncoding | (*args, **kwargs) | return _gdi_.TestFontEncoding(*args, **kwargs) | TestFontEncoding(NativeEncodingInfo info) -> bool | TestFontEncoding(NativeEncodingInfo info) -> bool | [
"TestFontEncoding",
"(",
"NativeEncodingInfo",
"info",
")",
"-",
">",
"bool"
] | def TestFontEncoding(*args, **kwargs):
"""TestFontEncoding(NativeEncodingInfo info) -> bool"""
return _gdi_.TestFontEncoding(*args, **kwargs) | [
"def",
"TestFontEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"TestFontEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L2093-L2095 | |
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | linked_list/library/circular_linked_list.py | python | CircularLinkedList.insert_head | (self, data) | inserts node at the start of linked list | inserts node at the start of linked list | [
"inserts",
"node",
"at",
"the",
"start",
"of",
"linked",
"list"
] | def insert_head(self, data):
""" inserts node at the start of linked list """
if self.head is None:
self.head = Node(data)
self.head.next = self.head
return
new_node = Node(data)
current = self.head
while current.next is not self.head:
current = current.next
current.next = new_node
new_node.next = self.head
self.head = new_node | [
"def",
"insert_head",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"head",
"is",
"None",
":",
"self",
".",
"head",
"=",
"Node",
"(",
"data",
")",
"self",
".",
"head",
".",
"next",
"=",
"self",
".",
"head",
"return",
"new_node",
"=",
"Node",
"(",
"data",
")",
"current",
"=",
"self",
".",
"head",
"while",
"current",
".",
"next",
"is",
"not",
"self",
".",
"head",
":",
"current",
"=",
"current",
".",
"next",
"current",
".",
"next",
"=",
"new_node",
"new_node",
".",
"next",
"=",
"self",
".",
"head",
"self",
".",
"head",
"=",
"new_node"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/linked_list/library/circular_linked_list.py#L35-L48 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/holiday.py | python | next_workday | (dt) | return dt | returns next weekday used for observances | returns next weekday used for observances | [
"returns",
"next",
"weekday",
"used",
"for",
"observances"
] | def next_workday(dt):
"""
returns next weekday used for observances
"""
dt += timedelta(days=1)
while dt.weekday() > 4:
# Mon-Fri are 0-4
dt += timedelta(days=1)
return dt | [
"def",
"next_workday",
"(",
"dt",
")",
":",
"dt",
"+=",
"timedelta",
"(",
"days",
"=",
"1",
")",
"while",
"dt",
".",
"weekday",
"(",
")",
">",
"4",
":",
"# Mon-Fri are 0-4",
"dt",
"+=",
"timedelta",
"(",
"days",
"=",
"1",
")",
"return",
"dt"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/holiday.py#L87-L95 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/command/config.py | python | config.check_type_size | (self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None) | return low | Check size of a given type. | Check size of a given type. | [
"Check",
"size",
"of",
"a",
"given",
"type",
"."
] | def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None):
"""Check size of a given type."""
self._check_compiler()
# First check the type can be compiled
body = textwrap.dedent(r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];
test_array [0] = 0
;
return 0;
}
""")
self._compile(body % {'type': type_name},
headers, include_dirs, 'c')
self._clean()
if expected:
body = textwrap.dedent(r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)];
test_array [0] = 0
;
return 0;
}
""")
for size in expected:
try:
self._compile(body % {'type': type_name, 'size': size},
headers, include_dirs, 'c')
self._clean()
return size
except CompileError:
pass
# this fails to *compile* if size > sizeof(type)
body = textwrap.dedent(r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)];
test_array [0] = 0
;
return 0;
}
""")
# The principle is simple: we first find low and high bounds of size
# for the type, where low/high are looked up on a log scale. Then, we
# do a binary search to find the exact size between low and high
low = 0
mid = 0
while True:
try:
self._compile(body % {'type': type_name, 'size': mid},
headers, include_dirs, 'c')
self._clean()
break
except CompileError:
#log.info("failure to test for bound %d" % mid)
low = mid + 1
mid = 2 * mid + 1
high = mid
# Binary search:
while low != high:
mid = (high - low) // 2 + low
try:
self._compile(body % {'type': type_name, 'size': mid},
headers, include_dirs, 'c')
self._clean()
high = mid
except CompileError:
low = mid + 1
return low | [
"def",
"check_type_size",
"(",
"self",
",",
"type_name",
",",
"headers",
"=",
"None",
",",
"include_dirs",
"=",
"None",
",",
"library_dirs",
"=",
"None",
",",
"expected",
"=",
"None",
")",
":",
"self",
".",
"_check_compiler",
"(",
")",
"# First check the type can be compiled",
"body",
"=",
"textwrap",
".",
"dedent",
"(",
"r\"\"\"\n typedef %(type)s npy_check_sizeof_type;\n int main (void)\n {\n static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];\n test_array [0] = 0\n\n ;\n return 0;\n }\n \"\"\"",
")",
"self",
".",
"_compile",
"(",
"body",
"%",
"{",
"'type'",
":",
"type_name",
"}",
",",
"headers",
",",
"include_dirs",
",",
"'c'",
")",
"self",
".",
"_clean",
"(",
")",
"if",
"expected",
":",
"body",
"=",
"textwrap",
".",
"dedent",
"(",
"r\"\"\"\n typedef %(type)s npy_check_sizeof_type;\n int main (void)\n {\n static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)];\n test_array [0] = 0\n\n ;\n return 0;\n }\n \"\"\"",
")",
"for",
"size",
"in",
"expected",
":",
"try",
":",
"self",
".",
"_compile",
"(",
"body",
"%",
"{",
"'type'",
":",
"type_name",
",",
"'size'",
":",
"size",
"}",
",",
"headers",
",",
"include_dirs",
",",
"'c'",
")",
"self",
".",
"_clean",
"(",
")",
"return",
"size",
"except",
"CompileError",
":",
"pass",
"# this fails to *compile* if size > sizeof(type)",
"body",
"=",
"textwrap",
".",
"dedent",
"(",
"r\"\"\"\n typedef %(type)s npy_check_sizeof_type;\n int main (void)\n {\n static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)];\n test_array [0] = 0\n\n ;\n return 0;\n }\n \"\"\"",
")",
"# The principle is simple: we first find low and high bounds of size",
"# for the type, where low/high are looked up on a log scale. Then, we",
"# do a binary search to find the exact size between low and high",
"low",
"=",
"0",
"mid",
"=",
"0",
"while",
"True",
":",
"try",
":",
"self",
".",
"_compile",
"(",
"body",
"%",
"{",
"'type'",
":",
"type_name",
",",
"'size'",
":",
"mid",
"}",
",",
"headers",
",",
"include_dirs",
",",
"'c'",
")",
"self",
".",
"_clean",
"(",
")",
"break",
"except",
"CompileError",
":",
"#log.info(\"failure to test for bound %d\" % mid)",
"low",
"=",
"mid",
"+",
"1",
"mid",
"=",
"2",
"*",
"mid",
"+",
"1",
"high",
"=",
"mid",
"# Binary search:",
"while",
"low",
"!=",
"high",
":",
"mid",
"=",
"(",
"high",
"-",
"low",
")",
"//",
"2",
"+",
"low",
"try",
":",
"self",
".",
"_compile",
"(",
"body",
"%",
"{",
"'type'",
":",
"type_name",
",",
"'size'",
":",
"mid",
"}",
",",
"headers",
",",
"include_dirs",
",",
"'c'",
")",
"self",
".",
"_clean",
"(",
")",
"high",
"=",
"mid",
"except",
"CompileError",
":",
"low",
"=",
"mid",
"+",
"1",
"return",
"low"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/command/config.py#L234-L315 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | Grid.SetRowMinimalHeight | (*args, **kwargs) | return _grid.Grid_SetRowMinimalHeight(*args, **kwargs) | SetRowMinimalHeight(self, int row, int width) | SetRowMinimalHeight(self, int row, int width) | [
"SetRowMinimalHeight",
"(",
"self",
"int",
"row",
"int",
"width",
")"
] | def SetRowMinimalHeight(*args, **kwargs):
"""SetRowMinimalHeight(self, int row, int width)"""
return _grid.Grid_SetRowMinimalHeight(*args, **kwargs) | [
"def",
"SetRowMinimalHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_SetRowMinimalHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1914-L1916 | |
homenc/HElib | f0e3e010009c592cd411ba96baa8376eb485247a | misc/algen/algen.py | python | parseRange | (rangeStr) | return values | Parses the ranges and numbers given to it.
Args:
rangeStr: a string e.g. '2-5,7,10-11'
Returns:
A list of values to try out.
Usage:
>>> parseRange('2-5,7,10-11')
[2, 3, 4, 5, 7, 10, 11] | Parses the ranges and numbers given to it. | [
"Parses",
"the",
"ranges",
"and",
"numbers",
"given",
"to",
"it",
"."
] | def parseRange(rangeStr):
"""
Parses the ranges and numbers given to it.
Args:
rangeStr: a string e.g. '2-5,7,10-11'
Returns:
A list of values to try out.
Usage:
>>> parseRange('2-5,7,10-11')
[2, 3, 4, 5, 7, 10, 11]
"""
rangeList = rangeStr.split(',')
# Group1 regex for range
# Group2 start number
# Group3 end number
# Group4 OR regex for single number
# Group5 end number
regex = re.compile(r'^((\d+)\s*-\s*(\d+))|(\s*(\d+)\s*)$')
try:
matches = [ regex.fullmatch(r).groups() for r in rangeList ]
except AttributeError:
raise argparse.ArgumentTypeError(\
"Wrong syntax for range given '%s'. Correct example '2-5,7' " % rangeStr)
def buildRanges(match):
matchRange, startRange, endRange, matchSingle, endSingle = match
if matchRange != None:
if int(endRange) < int(startRange):
raise argparse.ArgumentTypeError(\
"Range going from high to low '%s'" % matchRange)
else:
return range(int(startRange), int(endRange)+1)
elif matchSingle != None:
return range(int(endSingle), int(endSingle)+1)
else:
raise ValueError(\
"Something went wrong generating a range with match '%s'"%(match, ) )
# Transform into a list of range objects
ranges = list(map(buildRanges, matches))
# Set Comprehension - guarantee uniqueness
values = { x for r in ranges for x in r }
# Convert to sorted list
values = sorted(list(values))
return values | [
"def",
"parseRange",
"(",
"rangeStr",
")",
":",
"rangeList",
"=",
"rangeStr",
".",
"split",
"(",
"','",
")",
"# Group1 regex for range",
"# Group2 start number",
"# Group3 end number",
"# Group4 OR regex for single number",
"# Group5 end number",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'^((\\d+)\\s*-\\s*(\\d+))|(\\s*(\\d+)\\s*)$'",
")",
"try",
":",
"matches",
"=",
"[",
"regex",
".",
"fullmatch",
"(",
"r",
")",
".",
"groups",
"(",
")",
"for",
"r",
"in",
"rangeList",
"]",
"except",
"AttributeError",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"Wrong syntax for range given '%s'. Correct example '2-5,7' \"",
"%",
"rangeStr",
")",
"def",
"buildRanges",
"(",
"match",
")",
":",
"matchRange",
",",
"startRange",
",",
"endRange",
",",
"matchSingle",
",",
"endSingle",
"=",
"match",
"if",
"matchRange",
"!=",
"None",
":",
"if",
"int",
"(",
"endRange",
")",
"<",
"int",
"(",
"startRange",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"Range going from high to low '%s'\"",
"%",
"matchRange",
")",
"else",
":",
"return",
"range",
"(",
"int",
"(",
"startRange",
")",
",",
"int",
"(",
"endRange",
")",
"+",
"1",
")",
"elif",
"matchSingle",
"!=",
"None",
":",
"return",
"range",
"(",
"int",
"(",
"endSingle",
")",
",",
"int",
"(",
"endSingle",
")",
"+",
"1",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Something went wrong generating a range with match '%s'\"",
"%",
"(",
"match",
",",
")",
")",
"# Transform into a list of range objects",
"ranges",
"=",
"list",
"(",
"map",
"(",
"buildRanges",
",",
"matches",
")",
")",
"# Set Comprehension - guarantee uniqueness",
"values",
"=",
"{",
"x",
"for",
"r",
"in",
"ranges",
"for",
"x",
"in",
"r",
"}",
"# Convert to sorted list",
"values",
"=",
"sorted",
"(",
"list",
"(",
"values",
")",
")",
"return",
"values"
] | https://github.com/homenc/HElib/blob/f0e3e010009c592cd411ba96baa8376eb485247a/misc/algen/algen.py#L20-L70 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py | python | SpawnBase.__iter__ | (self) | return iter(self.readline, self.string_type()) | This is to support iterators over a file-like object. | This is to support iterators over a file-like object. | [
"This",
"is",
"to",
"support",
"iterators",
"over",
"a",
"file",
"-",
"like",
"object",
"."
] | def __iter__(self):
'''This is to support iterators over a file-like object.
'''
return iter(self.readline, self.string_type()) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"readline",
",",
"self",
".",
"string_type",
"(",
")",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L480-L483 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/scimath.py | python | arcsin | (x) | return nx.arcsin(x) | Compute the inverse sine of x.
Return the "principal value" (for a description of this, see
`numpy.arcsin`) of the inverse sine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex principle value is
returned.
Parameters
----------
x : array_like or scalar
The value(s) whose arcsin is (are) required.
Returns
-------
out : ndarray or scalar
The inverse sine(s) of the `x` value(s). If `x` was a scalar, so
is `out`, otherwise an array object is returned.
See Also
--------
numpy.arcsin
Notes
-----
For an arcsin() that returns ``NAN`` when real `x` is not in the
interval ``[-1,1]``, use `numpy.arcsin`.
Examples
--------
>>> np.set_printoptions(precision=4)
>>> np.emath.arcsin(0)
0.0
>>> np.emath.arcsin([0,1])
array([0. , 1.5708]) | Compute the inverse sine of x. | [
"Compute",
"the",
"inverse",
"sine",
"of",
"x",
"."
] | def arcsin(x):
"""
Compute the inverse sine of x.
Return the "principal value" (for a description of this, see
`numpy.arcsin`) of the inverse sine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex principle value is
returned.
Parameters
----------
x : array_like or scalar
The value(s) whose arcsin is (are) required.
Returns
-------
out : ndarray or scalar
The inverse sine(s) of the `x` value(s). If `x` was a scalar, so
is `out`, otherwise an array object is returned.
See Also
--------
numpy.arcsin
Notes
-----
For an arcsin() that returns ``NAN`` when real `x` is not in the
interval ``[-1,1]``, use `numpy.arcsin`.
Examples
--------
>>> np.set_printoptions(precision=4)
>>> np.emath.arcsin(0)
0.0
>>> np.emath.arcsin([0,1])
array([0. , 1.5708])
"""
x = _fix_real_abs_gt_1(x)
return nx.arcsin(x) | [
"def",
"arcsin",
"(",
"x",
")",
":",
"x",
"=",
"_fix_real_abs_gt_1",
"(",
"x",
")",
"return",
"nx",
".",
"arcsin",
"(",
"x",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/scimath.py#L510-L552 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | PyApp.GetTraits | (*args, **kwargs) | return _core_.PyApp_GetTraits(*args, **kwargs) | GetTraits(self) -> wxAppTraits
Return (and create if necessary) the app traits object to which we
delegate for everything which either should be configurable by the
user (then he can change the default behaviour simply by overriding
CreateTraits() and returning his own traits object) or which is
GUI/console dependent as then wx.AppTraits allows us to abstract the
differences behind the common facade.
:todo: Add support for overriding CreateAppTraits in wxPython. | GetTraits(self) -> wxAppTraits | [
"GetTraits",
"(",
"self",
")",
"-",
">",
"wxAppTraits"
] | def GetTraits(*args, **kwargs):
"""
GetTraits(self) -> wxAppTraits
Return (and create if necessary) the app traits object to which we
delegate for everything which either should be configurable by the
user (then he can change the default behaviour simply by overriding
CreateTraits() and returning his own traits object) or which is
GUI/console dependent as then wx.AppTraits allows us to abstract the
differences behind the common facade.
:todo: Add support for overriding CreateAppTraits in wxPython.
"""
return _core_.PyApp_GetTraits(*args, **kwargs) | [
"def",
"GetTraits",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"PyApp_GetTraits",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L7804-L7817 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py | python | Parfor.get_shape_classes | (self, var, typemap=None) | return res | get the shape classes for a given variable.
If a typemap is specified then use it for type resolution | get the shape classes for a given variable.
If a typemap is specified then use it for type resolution | [
"get",
"the",
"shape",
"classes",
"for",
"a",
"given",
"variable",
".",
"If",
"a",
"typemap",
"is",
"specified",
"then",
"use",
"it",
"for",
"type",
"resolution"
] | def get_shape_classes(self, var, typemap=None):
"""get the shape classes for a given variable.
If a typemap is specified then use it for type resolution
"""
# We get shape classes from the equivalence set but that
# keeps its own typemap at a time prior to lowering. So
# if something is added during lowering then we can pass
# in a type map to use. We temporarily replace the
# equivalence set typemap, do the work and then restore
# the original on the way out.
if typemap is not None:
save_typemap = self.equiv_set.typemap
self.equiv_set.typemap = typemap
res = self.equiv_set.get_shape_classes(var)
if typemap is not None:
self.equiv_set.typemap = save_typemap
return res | [
"def",
"get_shape_classes",
"(",
"self",
",",
"var",
",",
"typemap",
"=",
"None",
")",
":",
"# We get shape classes from the equivalence set but that",
"# keeps its own typemap at a time prior to lowering. So",
"# if something is added during lowering then we can pass",
"# in a type map to use. We temporarily replace the",
"# equivalence set typemap, do the work and then restore",
"# the original on the way out.",
"if",
"typemap",
"is",
"not",
"None",
":",
"save_typemap",
"=",
"self",
".",
"equiv_set",
".",
"typemap",
"self",
".",
"equiv_set",
".",
"typemap",
"=",
"typemap",
"res",
"=",
"self",
".",
"equiv_set",
".",
"get_shape_classes",
"(",
"var",
")",
"if",
"typemap",
"is",
"not",
"None",
":",
"self",
".",
"equiv_set",
".",
"typemap",
"=",
"save_typemap",
"return",
"res"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py#L583-L599 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | RendererNative.GetHeaderButtonMargin | (*args, **kwargs) | return _gdi_.RendererNative_GetHeaderButtonMargin(*args, **kwargs) | GetHeaderButtonMargin(self, Window win) -> int | GetHeaderButtonMargin(self, Window win) -> int | [
"GetHeaderButtonMargin",
"(",
"self",
"Window",
"win",
")",
"-",
">",
"int"
] | def GetHeaderButtonMargin(*args, **kwargs):
"""GetHeaderButtonMargin(self, Window win) -> int"""
return _gdi_.RendererNative_GetHeaderButtonMargin(*args, **kwargs) | [
"def",
"GetHeaderButtonMargin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"RendererNative_GetHeaderButtonMargin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L7275-L7277 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py | python | XMLReader.parse | (self, source) | Parse an XML document from a system identifier or an InputSource. | Parse an XML document from a system identifier or an InputSource. | [
"Parse",
"an",
"XML",
"document",
"from",
"a",
"system",
"identifier",
"or",
"an",
"InputSource",
"."
] | def parse(self, source):
"Parse an XML document from a system identifier or an InputSource."
raise NotImplementedError("This method must be implemented!") | [
"def",
"parse",
"(",
"self",
",",
"source",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"This method must be implemented!\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py#L30-L32 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/lists.py | python | ListsHandler.get_paragraph_list_info | (self, iter_start_orig) | return None | Returns a dictionary indicating List Element Number, List Level and List Element Start Offset | Returns a dictionary indicating List Element Number, List Level and List Element Start Offset | [
"Returns",
"a",
"dictionary",
"indicating",
"List",
"Element",
"Number",
"List",
"Level",
"and",
"List",
"Element",
"Start",
"Offset"
] | def get_paragraph_list_info(self, iter_start_orig):
"""Returns a dictionary indicating List Element Number, List Level and List Element Start Offset"""
buffer_start = False
iter_start = iter_start_orig.copy()
# let's search for the paragraph start
if iter_start.get_char() == cons.CHAR_NEWLINE:
if not iter_start.backward_char(): buffer_start = True # if we are exactly on the paragraph end
if not buffer_start:
while iter_start:
if iter_start.get_char() == cons.CHAR_NEWLINE: break # we got the previous paragraph start
elif not iter_start.backward_char():
buffer_start = True
break # we reached the buffer start
if not buffer_start: iter_start.forward_char()
# get the number of the paragraph starting with iter_start
number_n_level = self.list_get_number_n_level(iter_start)
curr_level = number_n_level["level"]
if number_n_level["num"] != None:
return {"num":number_n_level["num"],
"level":curr_level,
"aux":number_n_level["aux"],
"startoffs":iter_start.get_offset()}
#print number_n_level
if not buffer_start and curr_level > 0:
# may be a list paragraph but after a shift+return
iter_start.backward_char()
list_info = self.get_paragraph_list_info(iter_start)
#print list_info
if list_info:
if (list_info["num"] != None and list_info["level"] == (curr_level-1))\
or (list_info["num"] == None and list_info["level"] == curr_level):
return list_info
return None | [
"def",
"get_paragraph_list_info",
"(",
"self",
",",
"iter_start_orig",
")",
":",
"buffer_start",
"=",
"False",
"iter_start",
"=",
"iter_start_orig",
".",
"copy",
"(",
")",
"# let's search for the paragraph start",
"if",
"iter_start",
".",
"get_char",
"(",
")",
"==",
"cons",
".",
"CHAR_NEWLINE",
":",
"if",
"not",
"iter_start",
".",
"backward_char",
"(",
")",
":",
"buffer_start",
"=",
"True",
"# if we are exactly on the paragraph end",
"if",
"not",
"buffer_start",
":",
"while",
"iter_start",
":",
"if",
"iter_start",
".",
"get_char",
"(",
")",
"==",
"cons",
".",
"CHAR_NEWLINE",
":",
"break",
"# we got the previous paragraph start",
"elif",
"not",
"iter_start",
".",
"backward_char",
"(",
")",
":",
"buffer_start",
"=",
"True",
"break",
"# we reached the buffer start",
"if",
"not",
"buffer_start",
":",
"iter_start",
".",
"forward_char",
"(",
")",
"# get the number of the paragraph starting with iter_start",
"number_n_level",
"=",
"self",
".",
"list_get_number_n_level",
"(",
"iter_start",
")",
"curr_level",
"=",
"number_n_level",
"[",
"\"level\"",
"]",
"if",
"number_n_level",
"[",
"\"num\"",
"]",
"!=",
"None",
":",
"return",
"{",
"\"num\"",
":",
"number_n_level",
"[",
"\"num\"",
"]",
",",
"\"level\"",
":",
"curr_level",
",",
"\"aux\"",
":",
"number_n_level",
"[",
"\"aux\"",
"]",
",",
"\"startoffs\"",
":",
"iter_start",
".",
"get_offset",
"(",
")",
"}",
"#print number_n_level",
"if",
"not",
"buffer_start",
"and",
"curr_level",
">",
"0",
":",
"# may be a list paragraph but after a shift+return",
"iter_start",
".",
"backward_char",
"(",
")",
"list_info",
"=",
"self",
".",
"get_paragraph_list_info",
"(",
"iter_start",
")",
"#print list_info",
"if",
"list_info",
":",
"if",
"(",
"list_info",
"[",
"\"num\"",
"]",
"!=",
"None",
"and",
"list_info",
"[",
"\"level\"",
"]",
"==",
"(",
"curr_level",
"-",
"1",
")",
")",
"or",
"(",
"list_info",
"[",
"\"num\"",
"]",
"==",
"None",
"and",
"list_info",
"[",
"\"level\"",
"]",
"==",
"curr_level",
")",
":",
"return",
"list_info",
"return",
"None"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/lists.py#L229-L261 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/tix.py | python | Grid.delete_column | (self, from_, to=None) | Delete columns between from_ and to inclusive.
If to is not provided, delete only column at from_ | Delete columns between from_ and to inclusive.
If to is not provided, delete only column at from_ | [
"Delete",
"columns",
"between",
"from_",
"and",
"to",
"inclusive",
".",
"If",
"to",
"is",
"not",
"provided",
"delete",
"only",
"column",
"at",
"from_"
] | def delete_column(self, from_, to=None):
"""Delete columns between from_ and to inclusive.
If to is not provided, delete only column at from_"""
if to is None:
self.tk.call(self, 'delete', 'column', from_)
else:
self.tk.call(self, 'delete', 'column', from_, to) | [
"def",
"delete_column",
"(",
"self",
",",
"from_",
",",
"to",
"=",
"None",
")",
":",
"if",
"to",
"is",
"None",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'delete'",
",",
"'column'",
",",
"from_",
")",
"else",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'delete'",
",",
"'column'",
",",
"from_",
",",
"to",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/tix.py#L1817-L1823 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/graph_editor/edit.py | python | detach_outputs | (sgv, control_outputs=None) | return sgv_, output_placeholders | Detach the outputa of a subgraph view.
Args:
sgv: the subgraph view to be detached. This argument is converted to a
subgraph using the same rules as the function subgraph.make_view.
control_outputs: a util.ControlOutputs instance or None. If not None the
control outputs are also detached.
Returns:
A new subgraph view of the detached subgraph.
Note that sgv is also modified in place.
Raises:
StandardError: if sgv cannot be converted to a SubGraphView using
the same rules than the function subgraph.make_view. | Detach the outputa of a subgraph view. | [
"Detach",
"the",
"outputa",
"of",
"a",
"subgraph",
"view",
"."
] | def detach_outputs(sgv, control_outputs=None):
"""Detach the outputa of a subgraph view.
Args:
sgv: the subgraph view to be detached. This argument is converted to a
subgraph using the same rules as the function subgraph.make_view.
control_outputs: a util.ControlOutputs instance or None. If not None the
control outputs are also detached.
Returns:
A new subgraph view of the detached subgraph.
Note that sgv is also modified in place.
Raises:
StandardError: if sgv cannot be converted to a SubGraphView using
the same rules than the function subgraph.make_view.
"""
sgv = subgraph.make_view(sgv)
# only select outputs with consumers
sgv_ = sgv.remap_outputs([output_id
for output_id, output_t in enumerate(sgv.outputs)
if output_t.consumers()])
# create consumer subgraph and remap
consumers_sgv = subgraph.SubGraphView(sgv_.consumers())
consumers_sgv = consumers_sgv.remap_inputs(
[input_id for input_id, input_t in enumerate(consumers_sgv.inputs)
if input_t in sgv_.outputs])
with sgv_.graph.as_default():
output_placeholders = [
util.make_placeholder_from_tensor(input_t)
for input_t in consumers_sgv.inputs
]
reroute.swap_outputs(sgv_, output_placeholders)
if control_outputs is not None:
detach_control_outputs(sgv_, control_outputs)
return sgv_, output_placeholders | [
"def",
"detach_outputs",
"(",
"sgv",
",",
"control_outputs",
"=",
"None",
")",
":",
"sgv",
"=",
"subgraph",
".",
"make_view",
"(",
"sgv",
")",
"# only select outputs with consumers",
"sgv_",
"=",
"sgv",
".",
"remap_outputs",
"(",
"[",
"output_id",
"for",
"output_id",
",",
"output_t",
"in",
"enumerate",
"(",
"sgv",
".",
"outputs",
")",
"if",
"output_t",
".",
"consumers",
"(",
")",
"]",
")",
"# create consumer subgraph and remap",
"consumers_sgv",
"=",
"subgraph",
".",
"SubGraphView",
"(",
"sgv_",
".",
"consumers",
"(",
")",
")",
"consumers_sgv",
"=",
"consumers_sgv",
".",
"remap_inputs",
"(",
"[",
"input_id",
"for",
"input_id",
",",
"input_t",
"in",
"enumerate",
"(",
"consumers_sgv",
".",
"inputs",
")",
"if",
"input_t",
"in",
"sgv_",
".",
"outputs",
"]",
")",
"with",
"sgv_",
".",
"graph",
".",
"as_default",
"(",
")",
":",
"output_placeholders",
"=",
"[",
"util",
".",
"make_placeholder_from_tensor",
"(",
"input_t",
")",
"for",
"input_t",
"in",
"consumers_sgv",
".",
"inputs",
"]",
"reroute",
".",
"swap_outputs",
"(",
"sgv_",
",",
"output_placeholders",
")",
"if",
"control_outputs",
"is",
"not",
"None",
":",
"detach_control_outputs",
"(",
"sgv_",
",",
"control_outputs",
")",
"return",
"sgv_",
",",
"output_placeholders"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/edit.py#L90-L125 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/records.py | python | find_duplicate | (list) | return dup | Find duplication in a list, return a list of duplicated elements | Find duplication in a list, return a list of duplicated elements | [
"Find",
"duplication",
"in",
"a",
"list",
"return",
"a",
"list",
"of",
"duplicated",
"elements"
] | def find_duplicate(list):
"""Find duplication in a list, return a list of duplicated elements"""
dup = []
for i in range(len(list)):
if (list[i] in list[i + 1:]):
if (list[i] not in dup):
dup.append(list[i])
return dup | [
"def",
"find_duplicate",
"(",
"list",
")",
":",
"dup",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"list",
")",
")",
":",
"if",
"(",
"list",
"[",
"i",
"]",
"in",
"list",
"[",
"i",
"+",
"1",
":",
"]",
")",
":",
"if",
"(",
"list",
"[",
"i",
"]",
"not",
"in",
"dup",
")",
":",
"dup",
".",
"append",
"(",
"list",
"[",
"i",
"]",
")",
"return",
"dup"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/records.py#L76-L83 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | ppapi/generators/idl_parser.py | python | IDLParser.p_enum_list | (self, p) | enum_list : modifiers SYMBOL '=' expression enum_cont
| modifiers SYMBOL enum_cont | enum_list : modifiers SYMBOL '=' expression enum_cont
| modifiers SYMBOL enum_cont | [
"enum_list",
":",
"modifiers",
"SYMBOL",
"=",
"expression",
"enum_cont",
"|",
"modifiers",
"SYMBOL",
"enum_cont"
] | def p_enum_list(self, p):
"""enum_list : modifiers SYMBOL '=' expression enum_cont
| modifiers SYMBOL enum_cont"""
if len(p) > 4:
val = self.BuildAttribute('VALUE', p[4])
enum = self.BuildNamed('EnumItem', p, 2, ListFromConcat(val, p[1]))
p[0] = ListFromConcat(enum, p[5])
else:
enum = self.BuildNamed('EnumItem', p, 2, p[1])
p[0] = ListFromConcat(enum, p[3])
if self.parse_debug: DumpReduction('enum_list', p) | [
"def",
"p_enum_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
">",
"4",
":",
"val",
"=",
"self",
".",
"BuildAttribute",
"(",
"'VALUE'",
",",
"p",
"[",
"4",
"]",
")",
"enum",
"=",
"self",
".",
"BuildNamed",
"(",
"'EnumItem'",
",",
"p",
",",
"2",
",",
"ListFromConcat",
"(",
"val",
",",
"p",
"[",
"1",
"]",
")",
")",
"p",
"[",
"0",
"]",
"=",
"ListFromConcat",
"(",
"enum",
",",
"p",
"[",
"5",
"]",
")",
"else",
":",
"enum",
"=",
"self",
".",
"BuildNamed",
"(",
"'EnumItem'",
",",
"p",
",",
"2",
",",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"ListFromConcat",
"(",
"enum",
",",
"p",
"[",
"3",
"]",
")",
"if",
"self",
".",
"parse_debug",
":",
"DumpReduction",
"(",
"'enum_list'",
",",
"p",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/ppapi/generators/idl_parser.py#L675-L685 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | withClass | (classname, namespace='') | return withAttribute(**{classattr: classname}) | Simplified version of :class:`withAttribute` when
matching on a div class - made difficult because ``class`` is
a reserved word in Python.
Example::
html = '''
<div>
Some text
<div class="grid">1 4 0 1 0</div>
<div class="graph">1,3 2,3 1,1</div>
<div>this <div> has no class</div>
</div>
'''
div,div_end = makeHTMLTags("div")
div_grid = div().setParseAction(withClass("grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1 | Simplified version of :class:`withAttribute` when
matching on a div class - made difficult because ``class`` is
a reserved word in Python. | [
"Simplified",
"version",
"of",
":",
"class",
":",
"withAttribute",
"when",
"matching",
"on",
"a",
"div",
"class",
"-",
"made",
"difficult",
"because",
"class",
"is",
"a",
"reserved",
"word",
"in",
"Python",
"."
] | def withClass(classname, namespace=''):
"""Simplified version of :class:`withAttribute` when
matching on a div class - made difficult because ``class`` is
a reserved word in Python.
Example::
html = '''
<div>
Some text
<div class="grid">1 4 0 1 0</div>
<div class="graph">1,3 2,3 1,1</div>
<div>this <div> has no class</div>
</div>
'''
div,div_end = makeHTMLTags("div")
div_grid = div().setParseAction(withClass("grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
"""
classattr = "%s:class" % namespace if namespace else "class"
return withAttribute(**{classattr: classname}) | [
"def",
"withClass",
"(",
"classname",
",",
"namespace",
"=",
"''",
")",
":",
"classattr",
"=",
"\"%s:class\"",
"%",
"namespace",
"if",
"namespace",
"else",
"\"class\"",
"return",
"withAttribute",
"(",
"*",
"*",
"{",
"classattr",
":",
"classname",
"}",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L5946-L5982 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/request_track.py | python | CachingPolicy.PolicyAtDate | (self, timestamp) | return self.VALIDATION_SYNC | Returns the caching policy at an aribitrary timestamp.
Args:
timestamp: (float) Seconds since Epoch.
Returns:
A policy in POLICIES. | Returns the caching policy at an aribitrary timestamp. | [
"Returns",
"the",
"caching",
"policy",
"at",
"an",
"aribitrary",
"timestamp",
"."
] | def PolicyAtDate(self, timestamp):
"""Returns the caching policy at an aribitrary timestamp.
Args:
timestamp: (float) Seconds since Epoch.
Returns:
A policy in POLICIES.
"""
# Note: the implementation is largely transcribed from
# net/http/http_response_headers.cc, itself following RFC 2616.
if not self.IsCacheable():
return self.FETCH
freshness = self.GetFreshnessLifetimes()
if freshness[0] == 0 and freshness[1] == 0:
return self.VALIDATION_SYNC
age = self._GetCurrentAge(timestamp)
if freshness[0] > age:
return self.VALIDATION_NONE
if (freshness[0] + freshness[1]) > age:
return self.VALIDATION_ASYNC
return self.VALIDATION_SYNC | [
"def",
"PolicyAtDate",
"(",
"self",
",",
"timestamp",
")",
":",
"# Note: the implementation is largely transcribed from",
"# net/http/http_response_headers.cc, itself following RFC 2616.",
"if",
"not",
"self",
".",
"IsCacheable",
"(",
")",
":",
"return",
"self",
".",
"FETCH",
"freshness",
"=",
"self",
".",
"GetFreshnessLifetimes",
"(",
")",
"if",
"freshness",
"[",
"0",
"]",
"==",
"0",
"and",
"freshness",
"[",
"1",
"]",
"==",
"0",
":",
"return",
"self",
".",
"VALIDATION_SYNC",
"age",
"=",
"self",
".",
"_GetCurrentAge",
"(",
"timestamp",
")",
"if",
"freshness",
"[",
"0",
"]",
">",
"age",
":",
"return",
"self",
".",
"VALIDATION_NONE",
"if",
"(",
"freshness",
"[",
"0",
"]",
"+",
"freshness",
"[",
"1",
"]",
")",
">",
"age",
":",
"return",
"self",
".",
"VALIDATION_ASYNC",
"return",
"self",
".",
"VALIDATION_SYNC"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/request_track.py#L460-L481 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/groupby/groupby.py | python | _Grouping.values | (self) | return self._obj.__class__._from_data(value_columns) | Return value columns as a frame.
Note that in aggregation, value columns can be arbitrarily
specified. While this method returns all non-key columns from `obj` as
a frame.
This is mainly used in transform-like operations. | Return value columns as a frame. | [
"Return",
"value",
"columns",
"as",
"a",
"frame",
"."
] | def values(self):
"""Return value columns as a frame.
Note that in aggregation, value columns can be arbitrarily
specified. While this method returns all non-key columns from `obj` as
a frame.
This is mainly used in transform-like operations.
"""
# If the key columns are in `obj`, filter them out
value_column_names = [
x for x in self._obj._data.names if x not in self._named_columns
]
value_columns = self._obj._data.select_by_label(value_column_names)
return self._obj.__class__._from_data(value_columns) | [
"def",
"values",
"(",
"self",
")",
":",
"# If the key columns are in `obj`, filter them out",
"value_column_names",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"_obj",
".",
"_data",
".",
"names",
"if",
"x",
"not",
"in",
"self",
".",
"_named_columns",
"]",
"value_columns",
"=",
"self",
".",
"_obj",
".",
"_data",
".",
"select_by_label",
"(",
"value_column_names",
")",
"return",
"self",
".",
"_obj",
".",
"__class__",
".",
"_from_data",
"(",
"value_columns",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/groupby/groupby.py#L1537-L1551 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/dataview.py | python | DataViewTreeCtrl.AppendItem | (*args, **kwargs) | return _dataview.DataViewTreeCtrl_AppendItem(*args, **kwargs) | AppendItem(self, DataViewItem parent, String text, int icon=-1, wxClientData data=None) -> DataViewItem | AppendItem(self, DataViewItem parent, String text, int icon=-1, wxClientData data=None) -> DataViewItem | [
"AppendItem",
"(",
"self",
"DataViewItem",
"parent",
"String",
"text",
"int",
"icon",
"=",
"-",
"1",
"wxClientData",
"data",
"=",
"None",
")",
"-",
">",
"DataViewItem"
] | def AppendItem(*args, **kwargs):
"""AppendItem(self, DataViewItem parent, String text, int icon=-1, wxClientData data=None) -> DataViewItem"""
return _dataview.DataViewTreeCtrl_AppendItem(*args, **kwargs) | [
"def",
"AppendItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewTreeCtrl_AppendItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L2489-L2491 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemPlayerAccount/AWS/resource-manager-code/pa_service_api.py | python | __get_default_resource_group | () | return 'CloudGemPlayerAccount' | Get the resource group name for player account | Get the resource group name for player account | [
"Get",
"the",
"resource",
"group",
"name",
"for",
"player",
"account"
] | def __get_default_resource_group() -> str:
"""Get the resource group name for player account"""
return 'CloudGemPlayerAccount' | [
"def",
"__get_default_resource_group",
"(",
")",
"->",
"str",
":",
"return",
"'CloudGemPlayerAccount'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemPlayerAccount/AWS/resource-manager-code/pa_service_api.py#L33-L35 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/topics.py | python | _SubscriberImpl.add_callback | (self, cb, cb_args) | Register a callback to be invoked whenever a new message is received
@param cb: callback function to invoke with message data
instance, i.e. fn(data). If callback args is set, they will
be passed in as the second argument.
@type cb: fn(msg, cb_args)
@param cb_cargs: additional arguments to pass to callback
@type cb_cargs: Any | Register a callback to be invoked whenever a new message is received | [
"Register",
"a",
"callback",
"to",
"be",
"invoked",
"whenever",
"a",
"new",
"message",
"is",
"received"
] | def add_callback(self, cb, cb_args):
"""
Register a callback to be invoked whenever a new message is received
@param cb: callback function to invoke with message data
instance, i.e. fn(data). If callback args is set, they will
be passed in as the second argument.
@type cb: fn(msg, cb_args)
@param cb_cargs: additional arguments to pass to callback
@type cb_cargs: Any
"""
if self.closed:
raise ROSException("subscriber [%s] has been closed"%(self.resolved_name))
with self.c_lock:
# we lock in order to serialize calls to add_callback, but
# we copy self.callbacks so we can it
new_callbacks = self.callbacks[:]
new_callbacks.append((cb, cb_args))
self.callbacks = new_callbacks
# #1852: invoke callback with any latched messages
for c in self.connections:
if c.latch is not None:
self._invoke_callback(c.latch, cb, cb_args) | [
"def",
"add_callback",
"(",
"self",
",",
"cb",
",",
"cb_args",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ROSException",
"(",
"\"subscriber [%s] has been closed\"",
"%",
"(",
"self",
".",
"resolved_name",
")",
")",
"with",
"self",
".",
"c_lock",
":",
"# we lock in order to serialize calls to add_callback, but",
"# we copy self.callbacks so we can it",
"new_callbacks",
"=",
"self",
".",
"callbacks",
"[",
":",
"]",
"new_callbacks",
".",
"append",
"(",
"(",
"cb",
",",
"cb_args",
")",
")",
"self",
".",
"callbacks",
"=",
"new_callbacks",
"# #1852: invoke callback with any latched messages",
"for",
"c",
"in",
"self",
".",
"connections",
":",
"if",
"c",
".",
"latch",
"is",
"not",
"None",
":",
"self",
".",
"_invoke_callback",
"(",
"c",
".",
"latch",
",",
"cb",
",",
"cb_args",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/topics.py#L687-L709 | ||
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/engine/forces.py | python | ForceField.run | (self) | Dummy queueing method. | Dummy queueing method. | [
"Dummy",
"queueing",
"method",
"."
] | def run(self):
"""Dummy queueing method."""
pass | [
"def",
"run",
"(",
"self",
")",
":",
"pass"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/forces.py#L143-L146 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/Draw/SimilarityMaps.py | python | GetAPFingerprint | (mol, atomId=-1, fpType='normal', nBits=2048, minLength=1, maxLength=30,
nBitsPerEntry=4, **kwargs) | return apDict[fpType](mol, nBits, minLength, maxLength, nBitsPerEntry, [atomId], **kwargs) | Calculates the atom pairs fingerprint with the torsions of atomId removed.
Parameters:
mol -- the molecule of interest
atomId -- the atom to remove the pairs for (if -1, no pair is removed)
fpType -- the type of AP fingerprint ('normal', 'hashed', 'bv')
nBits -- the size of the bit vector (only for fpType='bv')
minLength -- the minimum path length for an atom pair
maxLength -- the maxmimum path length for an atom pair
nBitsPerEntry -- the number of bits available for each pair | Calculates the atom pairs fingerprint with the torsions of atomId removed. | [
"Calculates",
"the",
"atom",
"pairs",
"fingerprint",
"with",
"the",
"torsions",
"of",
"atomId",
"removed",
"."
] | def GetAPFingerprint(mol, atomId=-1, fpType='normal', nBits=2048, minLength=1, maxLength=30,
nBitsPerEntry=4, **kwargs):
"""
Calculates the atom pairs fingerprint with the torsions of atomId removed.
Parameters:
mol -- the molecule of interest
atomId -- the atom to remove the pairs for (if -1, no pair is removed)
fpType -- the type of AP fingerprint ('normal', 'hashed', 'bv')
nBits -- the size of the bit vector (only for fpType='bv')
minLength -- the minimum path length for an atom pair
maxLength -- the maxmimum path length for an atom pair
nBitsPerEntry -- the number of bits available for each pair
"""
if fpType not in ['normal', 'hashed', 'bv']:
raise ValueError("Unknown Atom pairs fingerprint type")
if atomId < 0:
return apDict[fpType](mol, nBits, minLength, maxLength, nBitsPerEntry, 0, **kwargs)
if atomId >= mol.GetNumAtoms():
raise ValueError("atom index greater than number of atoms")
return apDict[fpType](mol, nBits, minLength, maxLength, nBitsPerEntry, [atomId], **kwargs) | [
"def",
"GetAPFingerprint",
"(",
"mol",
",",
"atomId",
"=",
"-",
"1",
",",
"fpType",
"=",
"'normal'",
",",
"nBits",
"=",
"2048",
",",
"minLength",
"=",
"1",
",",
"maxLength",
"=",
"30",
",",
"nBitsPerEntry",
"=",
"4",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"fpType",
"not",
"in",
"[",
"'normal'",
",",
"'hashed'",
",",
"'bv'",
"]",
":",
"raise",
"ValueError",
"(",
"\"Unknown Atom pairs fingerprint type\"",
")",
"if",
"atomId",
"<",
"0",
":",
"return",
"apDict",
"[",
"fpType",
"]",
"(",
"mol",
",",
"nBits",
",",
"minLength",
",",
"maxLength",
",",
"nBitsPerEntry",
",",
"0",
",",
"*",
"*",
"kwargs",
")",
"if",
"atomId",
">=",
"mol",
".",
"GetNumAtoms",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"atom index greater than number of atoms\"",
")",
"return",
"apDict",
"[",
"fpType",
"]",
"(",
"mol",
",",
"nBits",
",",
"minLength",
",",
"maxLength",
",",
"nBitsPerEntry",
",",
"[",
"atomId",
"]",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/Draw/SimilarityMaps.py#L284-L304 | |
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py | python | Dir.sconsign | (self) | return _sconsign_map[self._func_sconsign](self) | Return the .sconsign file info for this directory. | Return the .sconsign file info for this directory. | [
"Return",
"the",
".",
"sconsign",
"file",
"info",
"for",
"this",
"directory",
"."
] | def sconsign(self):
"""Return the .sconsign file info for this directory. """
return _sconsign_map[self._func_sconsign](self) | [
"def",
"sconsign",
"(",
"self",
")",
":",
"return",
"_sconsign_map",
"[",
"self",
".",
"_func_sconsign",
"]",
"(",
"self",
")"
] | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py#L1866-L1868 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/window.py | python | _GroupByMixin._apply | (self, func, name, window=None, center=None,
check_minp=None, **kwargs) | return self._groupby.apply(f) | Dispatch to apply; we are stripping all of the _apply kwargs and
performing the original function call on the grouped object. | Dispatch to apply; we are stripping all of the _apply kwargs and
performing the original function call on the grouped object. | [
"Dispatch",
"to",
"apply",
";",
"we",
"are",
"stripping",
"all",
"of",
"the",
"_apply",
"kwargs",
"and",
"performing",
"the",
"original",
"function",
"call",
"on",
"the",
"grouped",
"object",
"."
] | def _apply(self, func, name, window=None, center=None,
check_minp=None, **kwargs):
"""
Dispatch to apply; we are stripping all of the _apply kwargs and
performing the original function call on the grouped object.
"""
def f(x, name=name, *args):
x = self._shallow_copy(x)
if isinstance(name, compat.string_types):
return getattr(x, name)(*args, **kwargs)
return x.apply(name, *args, **kwargs)
return self._groupby.apply(f) | [
"def",
"_apply",
"(",
"self",
",",
"func",
",",
"name",
",",
"window",
"=",
"None",
",",
"center",
"=",
"None",
",",
"check_minp",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"f",
"(",
"x",
",",
"name",
"=",
"name",
",",
"*",
"args",
")",
":",
"x",
"=",
"self",
".",
"_shallow_copy",
"(",
"x",
")",
"if",
"isinstance",
"(",
"name",
",",
"compat",
".",
"string_types",
")",
":",
"return",
"getattr",
"(",
"x",
",",
"name",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"x",
".",
"apply",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_groupby",
".",
"apply",
"(",
"f",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/window.py#L785-L800 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | BitmapDataObject.SetBitmap | (*args, **kwargs) | return _misc_.BitmapDataObject_SetBitmap(*args, **kwargs) | SetBitmap(self, Bitmap bitmap)
Sets the bitmap associated with the data object. This method is called
when the data object receives data. Usually there will be no reason to
override this function. | SetBitmap(self, Bitmap bitmap) | [
"SetBitmap",
"(",
"self",
"Bitmap",
"bitmap",
")"
] | def SetBitmap(*args, **kwargs):
"""
SetBitmap(self, Bitmap bitmap)
Sets the bitmap associated with the data object. This method is called
when the data object receives data. Usually there will be no reason to
override this function.
"""
return _misc_.BitmapDataObject_SetBitmap(*args, **kwargs) | [
"def",
"SetBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"BitmapDataObject_SetBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L5285-L5293 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/tools/build/src/tools/stage.py | python | InstallTargetClass.update_location | (self, ps) | return ps | If <location> is not set, sets it based on the project data. | If <location> is not set, sets it based on the project data. | [
"If",
"<location",
">",
"is",
"not",
"set",
"sets",
"it",
"based",
"on",
"the",
"project",
"data",
"."
] | def update_location(self, ps):
"""If <location> is not set, sets it based on the project data."""
loc = ps.get('location')
if not loc:
loc = os.path.join(self.project().get('location'), self.name())
ps = ps.add_raw(["<location>" + loc])
return ps | [
"def",
"update_location",
"(",
"self",
",",
"ps",
")",
":",
"loc",
"=",
"ps",
".",
"get",
"(",
"'location'",
")",
"if",
"not",
"loc",
":",
"loc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project",
"(",
")",
".",
"get",
"(",
"'location'",
")",
",",
"self",
".",
"name",
"(",
")",
")",
"ps",
"=",
"ps",
".",
"add_raw",
"(",
"[",
"\"<location>\"",
"+",
"loc",
"]",
")",
"return",
"ps"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/tools/stage.py#L41-L49 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/messages.py | python | _DefinitionClass.__setattr__ | (cls, name, value) | Overridden so that cannot set variables on definition classes after init.
Setting attributes on a class must work during the period of initialization
to set the enumation value class variables and build the name/number maps.
Once __init__ has set the __initialized flag to True prohibits setting any
more values on the class. The class is in effect frozen.
Args:
name: Name of value to set.
value: Value to set. | Overridden so that cannot set variables on definition classes after init. | [
"Overridden",
"so",
"that",
"cannot",
"set",
"variables",
"on",
"definition",
"classes",
"after",
"init",
"."
] | def __setattr__(cls, name, value):
"""Overridden so that cannot set variables on definition classes after init.
Setting attributes on a class must work during the period of initialization
to set the enumation value class variables and build the name/number maps.
Once __init__ has set the __initialized flag to True prohibits setting any
more values on the class. The class is in effect frozen.
Args:
name: Name of value to set.
value: Value to set.
"""
if cls.__initialized and name not in _POST_INIT_ATTRIBUTE_NAMES:
raise AttributeError('May not change values: %s' % name)
else:
type.__setattr__(cls, name, value) | [
"def",
"__setattr__",
"(",
"cls",
",",
"name",
",",
"value",
")",
":",
"if",
"cls",
".",
"__initialized",
"and",
"name",
"not",
"in",
"_POST_INIT_ATTRIBUTE_NAMES",
":",
"raise",
"AttributeError",
"(",
"'May not change values: %s'",
"%",
"name",
")",
"else",
":",
"type",
".",
"__setattr__",
"(",
"cls",
",",
"name",
",",
"value",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/messages.py#L206-L221 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py | python | SubstitutionEnvironment.RemoveMethod | (self, function) | Removes the specified function's MethodWrapper from the
added_methods list, so we don't re-bind it when making a clone. | Removes the specified function's MethodWrapper from the
added_methods list, so we don't re-bind it when making a clone. | [
"Removes",
"the",
"specified",
"function",
"s",
"MethodWrapper",
"from",
"the",
"added_methods",
"list",
"so",
"we",
"don",
"t",
"re",
"-",
"bind",
"it",
"when",
"making",
"a",
"clone",
"."
] | def RemoveMethod(self, function):
"""
Removes the specified function's MethodWrapper from the
added_methods list, so we don't re-bind it when making a clone.
"""
self.added_methods = [dm for dm in self.added_methods if dm.method is not function] | [
"def",
"RemoveMethod",
"(",
"self",
",",
"function",
")",
":",
"self",
".",
"added_methods",
"=",
"[",
"dm",
"for",
"dm",
"in",
"self",
".",
"added_methods",
"if",
"dm",
".",
"method",
"is",
"not",
"function",
"]"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py#L601-L606 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/cluster/k_means_.py | python | _mini_batch_step | (X, x_squared_norms, centers, counts,
old_center_buffer, compute_squared_diff,
distances, random_reassign=False,
random_state=None, reassignment_ratio=.01,
verbose=False) | return inertia, squared_diff | Incremental update of the centers for the Minibatch K-Means algorithm.
Parameters
----------
X : array, shape (n_samples, n_features)
The original data array.
x_squared_norms : array, shape (n_samples,)
Squared euclidean norm of each data point.
centers : array, shape (k, n_features)
The cluster centers. This array is MODIFIED IN PLACE
counts : array, shape (k,)
The vector in which we keep track of the numbers of elements in a
cluster. This array is MODIFIED IN PLACE
distances : array, dtype float, shape (n_samples), optional
If not None, should be a pre-allocated array that will be used to store
the distances of each sample to its closest center.
May not be None when random_reassign is True.
random_state : integer or numpy.RandomState, optional
The generator used to initialize the centers. If an integer is
given, it fixes the seed. Defaults to the global numpy random
number generator.
random_reassign : boolean, optional
If True, centers with very low counts are randomly reassigned
to observations.
reassignment_ratio : float, optional
Control the fraction of the maximum number of counts for a
center to be reassigned. A higher value means that low count
centers are more likely to be reassigned, which means that the
model will take longer to converge, but should converge in a
better clustering.
verbose : bool, optional, default False
Controls the verbosity.
compute_squared_diff : bool
If set to False, the squared diff computation is skipped.
old_center_buffer : int
Copy of old centers for monitoring convergence.
Returns
-------
inertia : float
Sum of distances of samples to their closest cluster center.
squared_diff : numpy array, shape (n_clusters,)
Squared distances between previous and updated cluster centers. | Incremental update of the centers for the Minibatch K-Means algorithm. | [
"Incremental",
"update",
"of",
"the",
"centers",
"for",
"the",
"Minibatch",
"K",
"-",
"Means",
"algorithm",
"."
] | def _mini_batch_step(X, x_squared_norms, centers, counts,
old_center_buffer, compute_squared_diff,
distances, random_reassign=False,
random_state=None, reassignment_ratio=.01,
verbose=False):
"""Incremental update of the centers for the Minibatch K-Means algorithm.
Parameters
----------
X : array, shape (n_samples, n_features)
The original data array.
x_squared_norms : array, shape (n_samples,)
Squared euclidean norm of each data point.
centers : array, shape (k, n_features)
The cluster centers. This array is MODIFIED IN PLACE
counts : array, shape (k,)
The vector in which we keep track of the numbers of elements in a
cluster. This array is MODIFIED IN PLACE
distances : array, dtype float, shape (n_samples), optional
If not None, should be a pre-allocated array that will be used to store
the distances of each sample to its closest center.
May not be None when random_reassign is True.
random_state : integer or numpy.RandomState, optional
The generator used to initialize the centers. If an integer is
given, it fixes the seed. Defaults to the global numpy random
number generator.
random_reassign : boolean, optional
If True, centers with very low counts are randomly reassigned
to observations.
reassignment_ratio : float, optional
Control the fraction of the maximum number of counts for a
center to be reassigned. A higher value means that low count
centers are more likely to be reassigned, which means that the
model will take longer to converge, but should converge in a
better clustering.
verbose : bool, optional, default False
Controls the verbosity.
compute_squared_diff : bool
If set to False, the squared diff computation is skipped.
old_center_buffer : int
Copy of old centers for monitoring convergence.
Returns
-------
inertia : float
Sum of distances of samples to their closest cluster center.
squared_diff : numpy array, shape (n_clusters,)
Squared distances between previous and updated cluster centers.
"""
# Perform label assignment to nearest centers
nearest_center, inertia = _labels_inertia(X, x_squared_norms, centers,
distances=distances)
if random_reassign and reassignment_ratio > 0:
random_state = check_random_state(random_state)
# Reassign clusters that have very low counts
to_reassign = counts < reassignment_ratio * counts.max()
# pick at most .5 * batch_size samples as new centers
if to_reassign.sum() > .5 * X.shape[0]:
indices_dont_reassign = np.argsort(counts)[int(.5 * X.shape[0]):]
to_reassign[indices_dont_reassign] = False
n_reassigns = to_reassign.sum()
if n_reassigns:
# Pick new clusters amongst observations with uniform probability
new_centers = choice(X.shape[0], replace=False, size=n_reassigns,
random_state=random_state)
if verbose:
print("[MiniBatchKMeans] Reassigning %i cluster centers."
% n_reassigns)
if sp.issparse(X) and not sp.issparse(centers):
assign_rows_csr(X,
astype(new_centers, np.intp),
astype(np.where(to_reassign)[0], np.intp),
centers)
else:
centers[to_reassign] = X[new_centers]
# reset counts of reassigned centers, but don't reset them too small
# to avoid instant reassignment. This is a pretty dirty hack as it
# also modifies the learning rates.
counts[to_reassign] = np.min(counts[~to_reassign])
# implementation for the sparse CSR representation completely written in
# cython
if sp.issparse(X):
return inertia, _k_means._mini_batch_update_csr(
X, x_squared_norms, centers, counts, nearest_center,
old_center_buffer, compute_squared_diff)
# dense variant in mostly numpy (not as memory efficient though)
k = centers.shape[0]
squared_diff = 0.0
for center_idx in range(k):
# find points from minibatch that are assigned to this center
center_mask = nearest_center == center_idx
count = center_mask.sum()
if count > 0:
if compute_squared_diff:
old_center_buffer[:] = centers[center_idx]
# inplace remove previous count scaling
centers[center_idx] *= counts[center_idx]
# inplace sum with new points members of this cluster
centers[center_idx] += np.sum(X[center_mask], axis=0)
# update the count statistics for this center
counts[center_idx] += count
# inplace rescale to compute mean of all points (old and new)
# Note: numpy >= 1.10 does not support '/=' for the following
# expression for a mixture of int and float (see numpy issue #6464)
centers[center_idx] = centers[center_idx] / counts[center_idx]
# update the squared diff if necessary
if compute_squared_diff:
diff = centers[center_idx].ravel() - old_center_buffer.ravel()
squared_diff += np.dot(diff, diff)
return inertia, squared_diff | [
"def",
"_mini_batch_step",
"(",
"X",
",",
"x_squared_norms",
",",
"centers",
",",
"counts",
",",
"old_center_buffer",
",",
"compute_squared_diff",
",",
"distances",
",",
"random_reassign",
"=",
"False",
",",
"random_state",
"=",
"None",
",",
"reassignment_ratio",
"=",
".01",
",",
"verbose",
"=",
"False",
")",
":",
"# Perform label assignment to nearest centers",
"nearest_center",
",",
"inertia",
"=",
"_labels_inertia",
"(",
"X",
",",
"x_squared_norms",
",",
"centers",
",",
"distances",
"=",
"distances",
")",
"if",
"random_reassign",
"and",
"reassignment_ratio",
">",
"0",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"# Reassign clusters that have very low counts",
"to_reassign",
"=",
"counts",
"<",
"reassignment_ratio",
"*",
"counts",
".",
"max",
"(",
")",
"# pick at most .5 * batch_size samples as new centers",
"if",
"to_reassign",
".",
"sum",
"(",
")",
">",
".5",
"*",
"X",
".",
"shape",
"[",
"0",
"]",
":",
"indices_dont_reassign",
"=",
"np",
".",
"argsort",
"(",
"counts",
")",
"[",
"int",
"(",
".5",
"*",
"X",
".",
"shape",
"[",
"0",
"]",
")",
":",
"]",
"to_reassign",
"[",
"indices_dont_reassign",
"]",
"=",
"False",
"n_reassigns",
"=",
"to_reassign",
".",
"sum",
"(",
")",
"if",
"n_reassigns",
":",
"# Pick new clusters amongst observations with uniform probability",
"new_centers",
"=",
"choice",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"replace",
"=",
"False",
",",
"size",
"=",
"n_reassigns",
",",
"random_state",
"=",
"random_state",
")",
"if",
"verbose",
":",
"print",
"(",
"\"[MiniBatchKMeans] Reassigning %i cluster centers.\"",
"%",
"n_reassigns",
")",
"if",
"sp",
".",
"issparse",
"(",
"X",
")",
"and",
"not",
"sp",
".",
"issparse",
"(",
"centers",
")",
":",
"assign_rows_csr",
"(",
"X",
",",
"astype",
"(",
"new_centers",
",",
"np",
".",
"intp",
")",
",",
"astype",
"(",
"np",
".",
"where",
"(",
"to_reassign",
")",
"[",
"0",
"]",
",",
"np",
".",
"intp",
")",
",",
"centers",
")",
"else",
":",
"centers",
"[",
"to_reassign",
"]",
"=",
"X",
"[",
"new_centers",
"]",
"# reset counts of reassigned centers, but don't reset them too small",
"# to avoid instant reassignment. This is a pretty dirty hack as it",
"# also modifies the learning rates.",
"counts",
"[",
"to_reassign",
"]",
"=",
"np",
".",
"min",
"(",
"counts",
"[",
"~",
"to_reassign",
"]",
")",
"# implementation for the sparse CSR representation completely written in",
"# cython",
"if",
"sp",
".",
"issparse",
"(",
"X",
")",
":",
"return",
"inertia",
",",
"_k_means",
".",
"_mini_batch_update_csr",
"(",
"X",
",",
"x_squared_norms",
",",
"centers",
",",
"counts",
",",
"nearest_center",
",",
"old_center_buffer",
",",
"compute_squared_diff",
")",
"# dense variant in mostly numpy (not as memory efficient though)",
"k",
"=",
"centers",
".",
"shape",
"[",
"0",
"]",
"squared_diff",
"=",
"0.0",
"for",
"center_idx",
"in",
"range",
"(",
"k",
")",
":",
"# find points from minibatch that are assigned to this center",
"center_mask",
"=",
"nearest_center",
"==",
"center_idx",
"count",
"=",
"center_mask",
".",
"sum",
"(",
")",
"if",
"count",
">",
"0",
":",
"if",
"compute_squared_diff",
":",
"old_center_buffer",
"[",
":",
"]",
"=",
"centers",
"[",
"center_idx",
"]",
"# inplace remove previous count scaling",
"centers",
"[",
"center_idx",
"]",
"*=",
"counts",
"[",
"center_idx",
"]",
"# inplace sum with new points members of this cluster",
"centers",
"[",
"center_idx",
"]",
"+=",
"np",
".",
"sum",
"(",
"X",
"[",
"center_mask",
"]",
",",
"axis",
"=",
"0",
")",
"# update the count statistics for this center",
"counts",
"[",
"center_idx",
"]",
"+=",
"count",
"# inplace rescale to compute mean of all points (old and new)",
"# Note: numpy >= 1.10 does not support '/=' for the following",
"# expression for a mixture of int and float (see numpy issue #6464)",
"centers",
"[",
"center_idx",
"]",
"=",
"centers",
"[",
"center_idx",
"]",
"/",
"counts",
"[",
"center_idx",
"]",
"# update the squared diff if necessary",
"if",
"compute_squared_diff",
":",
"diff",
"=",
"centers",
"[",
"center_idx",
"]",
".",
"ravel",
"(",
")",
"-",
"old_center_buffer",
".",
"ravel",
"(",
")",
"squared_diff",
"+=",
"np",
".",
"dot",
"(",
"diff",
",",
"diff",
")",
"return",
"inertia",
",",
"squared_diff"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/cluster/k_means_.py#L981-L1114 | |
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/json_format.py | python | _Printer._MessageToJsonObject | (self, message) | return self._RegularMessageToJsonObject(message, js) | Converts message to an object according to Proto3 JSON Specification. | Converts message to an object according to Proto3 JSON Specification. | [
"Converts",
"message",
"to",
"an",
"object",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | def _MessageToJsonObject(self, message):
"""Converts message to an object according to Proto3 JSON Specification."""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
return self._WrapperMessageToJsonObject(message)
if full_name in _WKTJSONMETHODS:
return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self)
js = {}
return self._RegularMessageToJsonObject(message, js) | [
"def",
"_MessageToJsonObject",
"(",
"self",
",",
"message",
")",
":",
"message_descriptor",
"=",
"message",
".",
"DESCRIPTOR",
"full_name",
"=",
"message_descriptor",
".",
"full_name",
"if",
"_IsWrapperMessage",
"(",
"message_descriptor",
")",
":",
"return",
"self",
".",
"_WrapperMessageToJsonObject",
"(",
"message",
")",
"if",
"full_name",
"in",
"_WKTJSONMETHODS",
":",
"return",
"methodcaller",
"(",
"_WKTJSONMETHODS",
"[",
"full_name",
"]",
"[",
"0",
"]",
",",
"message",
")",
"(",
"self",
")",
"js",
"=",
"{",
"}",
"return",
"self",
".",
"_RegularMessageToJsonObject",
"(",
"message",
",",
"js",
")"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/json_format.py#L197-L206 | |
NervanaSystems/ngraph | f677a119765ca30636cf407009dabd118664951f | python/src/ngraph/ops.py | python | squeeze | (data: NodeInput, axes: NodeInput, name: Optional[str] = None) | return _get_node_factory().create("Squeeze", as_nodes(data, axes)) | Perform squeeze operation on input tensor.
Remove single-dimensional entries from the shape of a tensor.
Takes a parameter :code:`axes` with a list of axes to squeeze.
If :code:`axes` is not provided, all the single dimensions will be removed from the shape.
If an :code:`axis` is selected with shape entry not equal to one, an error is raised.
For example:
Inputs: tensor with shape [1, 2, 1, 3, 1, 1], axes=[2, 4]
Result: tensor with shape [1, 2, 3, 1]
:param data: The node with data tensor.
:param axes: List of non-negative integers, indicate the dimensions to squeeze.
One of: input node or array.
:param name: Optional new name for output node.
:return: The new node performing a squeeze operation on input tensor. | Perform squeeze operation on input tensor. | [
"Perform",
"squeeze",
"operation",
"on",
"input",
"tensor",
"."
] | def squeeze(data: NodeInput, axes: NodeInput, name: Optional[str] = None) -> Node:
"""Perform squeeze operation on input tensor.
Remove single-dimensional entries from the shape of a tensor.
Takes a parameter :code:`axes` with a list of axes to squeeze.
If :code:`axes` is not provided, all the single dimensions will be removed from the shape.
If an :code:`axis` is selected with shape entry not equal to one, an error is raised.
For example:
Inputs: tensor with shape [1, 2, 1, 3, 1, 1], axes=[2, 4]
Result: tensor with shape [1, 2, 3, 1]
:param data: The node with data tensor.
:param axes: List of non-negative integers, indicate the dimensions to squeeze.
One of: input node or array.
:param name: Optional new name for output node.
:return: The new node performing a squeeze operation on input tensor.
"""
return _get_node_factory().create("Squeeze", as_nodes(data, axes)) | [
"def",
"squeeze",
"(",
"data",
":",
"NodeInput",
",",
"axes",
":",
"NodeInput",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Node",
":",
"return",
"_get_node_factory",
"(",
")",
".",
"create",
"(",
"\"Squeeze\"",
",",
"as_nodes",
"(",
"data",
",",
"axes",
")",
")"
] | https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/ops.py#L170-L191 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ribbon/buttonbar.py | python | RibbonButtonBar.InsertButton | (self, pos, button_id, label, bitmap, bitmap_small=wx.NullBitmap, bitmap_disabled=wx.NullBitmap,
bitmap_small_disabled=wx.NullBitmap, kind=RIBBON_BUTTON_NORMAL, help_string="", client_data=None) | return base | Inserts a button in the button bar at the position specified by `pos`.
:param integer `pos`: the position at which the new button must be inserted (zero-based);
:param integer `button_id`: id of the new button (used for event callbacks);
:param string `label`: label of the new button;
:param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
all other large bitmaps used on the button bar;
:param `bitmap_small`: small bitmap of the new button, an instance of :class:`Bitmap`. If left as :class:`NullBitmap`,
then a small bitmap will be automatically generated. Must be the same size
as all other small bitmaps used on the button bar;
:param `bitmap_disabled`: large bitmap of the new button when it is disabled, an instance of :class:`Bitmap`.
If left as :class:`NullBitmap`, then a bitmap will be automatically generated from `bitmap`;
:param `bitmap_small_disabled`: small bitmap of the new button when it is disabled, an instance of :class:`Bitmap`.
If left as :class:`NullBitmap`, then a bitmap will be automatically generated from `bitmap_small`;
:param integer `kind`: the kind of button to add;
:param string `help_string`: the UI help string to associate with the new button;
:param object `client_data`: client data to associate with the new button.
:returns: An opaque pointer which can be used only with other button bar methods.
:raise: `Exception` if both `bitmap` and `bitmap_small` are invalid or if the input `help_string` is not
a valid Python `basestring`.
:see: :meth:`~RibbonButtonBar.AddDropdownButton`, :meth:`~RibbonButtonBar.AddHybridButton` and :meth:`~RibbonButtonBar.AddButton` for a list of valid button `kind` values.
.. versionadded:: 0.9.5 | Inserts a button in the button bar at the position specified by `pos`. | [
"Inserts",
"a",
"button",
"in",
"the",
"button",
"bar",
"at",
"the",
"position",
"specified",
"by",
"pos",
"."
] | def InsertButton(self, pos, button_id, label, bitmap, bitmap_small=wx.NullBitmap, bitmap_disabled=wx.NullBitmap,
bitmap_small_disabled=wx.NullBitmap, kind=RIBBON_BUTTON_NORMAL, help_string="", client_data=None):
"""
Inserts a button in the button bar at the position specified by `pos`.
:param integer `pos`: the position at which the new button must be inserted (zero-based);
:param integer `button_id`: id of the new button (used for event callbacks);
:param string `label`: label of the new button;
:param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
all other large bitmaps used on the button bar;
:param `bitmap_small`: small bitmap of the new button, an instance of :class:`Bitmap`. If left as :class:`NullBitmap`,
then a small bitmap will be automatically generated. Must be the same size
as all other small bitmaps used on the button bar;
:param `bitmap_disabled`: large bitmap of the new button when it is disabled, an instance of :class:`Bitmap`.
If left as :class:`NullBitmap`, then a bitmap will be automatically generated from `bitmap`;
:param `bitmap_small_disabled`: small bitmap of the new button when it is disabled, an instance of :class:`Bitmap`.
If left as :class:`NullBitmap`, then a bitmap will be automatically generated from `bitmap_small`;
:param integer `kind`: the kind of button to add;
:param string `help_string`: the UI help string to associate with the new button;
:param object `client_data`: client data to associate with the new button.
:returns: An opaque pointer which can be used only with other button bar methods.
:raise: `Exception` if both `bitmap` and `bitmap_small` are invalid or if the input `help_string` is not
a valid Python `basestring`.
:see: :meth:`~RibbonButtonBar.AddDropdownButton`, :meth:`~RibbonButtonBar.AddHybridButton` and :meth:`~RibbonButtonBar.AddButton` for a list of valid button `kind` values.
.. versionadded:: 0.9.5
"""
if not bitmap.IsOk() and not bitmap_small.IsOk():
raise Exception("Invalid main bitmap")
if not isinstance(help_string, basestring):
raise Exception("Invalid help string parameter")
if not self._buttons:
if bitmap.IsOk():
self._bitmap_size_large = bitmap.GetSize()
if not bitmap_small.IsOk():
w, h = self._bitmap_size_large
self._bitmap_size_small = wx.Size(0.5*w, 0.5*h)
if bitmap_small.IsOk():
self._bitmap_size_small = bitmap_small.GetSize()
if not bitmap.IsOk():
w, h = self._bitmap_size_small
self._bitmap_size_large = wx.Size(2*w, 2*h)
base = RibbonButtonBarButtonBase()
base.id = button_id
base.label = label
base.bitmap_large = bitmap
if not base.bitmap_large.IsOk():
base.bitmap_large = self.MakeResizedBitmap(base.bitmap_small, self._bitmap_size_large)
elif base.bitmap_large.GetSize() != self._bitmap_size_large:
base.bitmap_large = self.MakeResizedBitmap(base.bitmap_large, self._bitmap_size_large)
base.bitmap_small = bitmap_small
if not base.bitmap_small.IsOk():
base.bitmap_small = self.MakeResizedBitmap(base.bitmap_large, self._bitmap_size_small)
elif base.bitmap_small.GetSize() != self._bitmap_size_small:
base.bitmap_small = self.MakeResizedBitmap(base.bitmap_small, self._bitmap_size_small)
base.bitmap_large_disabled = bitmap_disabled
if not base.bitmap_large_disabled.IsOk():
base.bitmap_large_disabled = self.MakeDisabledBitmap(base.bitmap_large)
base.bitmap_small_disabled = bitmap_small_disabled
if not base.bitmap_small_disabled.IsOk():
base.bitmap_small_disabled = self.MakeDisabledBitmap(base.bitmap_small)
base.kind = kind
base.help_string = help_string
base.client_data = client_data
base.state = 0
temp_dc = wx.ClientDC(self)
self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_SMALL, temp_dc)
self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_MEDIUM, temp_dc)
self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_LARGE, temp_dc)
self._buttons.insert(pos, base)
self._layouts_valid = False
return base | [
"def",
"InsertButton",
"(",
"self",
",",
"pos",
",",
"button_id",
",",
"label",
",",
"bitmap",
",",
"bitmap_small",
"=",
"wx",
".",
"NullBitmap",
",",
"bitmap_disabled",
"=",
"wx",
".",
"NullBitmap",
",",
"bitmap_small_disabled",
"=",
"wx",
".",
"NullBitmap",
",",
"kind",
"=",
"RIBBON_BUTTON_NORMAL",
",",
"help_string",
"=",
"\"\"",
",",
"client_data",
"=",
"None",
")",
":",
"if",
"not",
"bitmap",
".",
"IsOk",
"(",
")",
"and",
"not",
"bitmap_small",
".",
"IsOk",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"Invalid main bitmap\"",
")",
"if",
"not",
"isinstance",
"(",
"help_string",
",",
"basestring",
")",
":",
"raise",
"Exception",
"(",
"\"Invalid help string parameter\"",
")",
"if",
"not",
"self",
".",
"_buttons",
":",
"if",
"bitmap",
".",
"IsOk",
"(",
")",
":",
"self",
".",
"_bitmap_size_large",
"=",
"bitmap",
".",
"GetSize",
"(",
")",
"if",
"not",
"bitmap_small",
".",
"IsOk",
"(",
")",
":",
"w",
",",
"h",
"=",
"self",
".",
"_bitmap_size_large",
"self",
".",
"_bitmap_size_small",
"=",
"wx",
".",
"Size",
"(",
"0.5",
"*",
"w",
",",
"0.5",
"*",
"h",
")",
"if",
"bitmap_small",
".",
"IsOk",
"(",
")",
":",
"self",
".",
"_bitmap_size_small",
"=",
"bitmap_small",
".",
"GetSize",
"(",
")",
"if",
"not",
"bitmap",
".",
"IsOk",
"(",
")",
":",
"w",
",",
"h",
"=",
"self",
".",
"_bitmap_size_small",
"self",
".",
"_bitmap_size_large",
"=",
"wx",
".",
"Size",
"(",
"2",
"*",
"w",
",",
"2",
"*",
"h",
")",
"base",
"=",
"RibbonButtonBarButtonBase",
"(",
")",
"base",
".",
"id",
"=",
"button_id",
"base",
".",
"label",
"=",
"label",
"base",
".",
"bitmap_large",
"=",
"bitmap",
"if",
"not",
"base",
".",
"bitmap_large",
".",
"IsOk",
"(",
")",
":",
"base",
".",
"bitmap_large",
"=",
"self",
".",
"MakeResizedBitmap",
"(",
"base",
".",
"bitmap_small",
",",
"self",
".",
"_bitmap_size_large",
")",
"elif",
"base",
".",
"bitmap_large",
".",
"GetSize",
"(",
")",
"!=",
"self",
".",
"_bitmap_size_large",
":",
"base",
".",
"bitmap_large",
"=",
"self",
".",
"MakeResizedBitmap",
"(",
"base",
".",
"bitmap_large",
",",
"self",
".",
"_bitmap_size_large",
")",
"base",
".",
"bitmap_small",
"=",
"bitmap_small",
"if",
"not",
"base",
".",
"bitmap_small",
".",
"IsOk",
"(",
")",
":",
"base",
".",
"bitmap_small",
"=",
"self",
".",
"MakeResizedBitmap",
"(",
"base",
".",
"bitmap_large",
",",
"self",
".",
"_bitmap_size_small",
")",
"elif",
"base",
".",
"bitmap_small",
".",
"GetSize",
"(",
")",
"!=",
"self",
".",
"_bitmap_size_small",
":",
"base",
".",
"bitmap_small",
"=",
"self",
".",
"MakeResizedBitmap",
"(",
"base",
".",
"bitmap_small",
",",
"self",
".",
"_bitmap_size_small",
")",
"base",
".",
"bitmap_large_disabled",
"=",
"bitmap_disabled",
"if",
"not",
"base",
".",
"bitmap_large_disabled",
".",
"IsOk",
"(",
")",
":",
"base",
".",
"bitmap_large_disabled",
"=",
"self",
".",
"MakeDisabledBitmap",
"(",
"base",
".",
"bitmap_large",
")",
"base",
".",
"bitmap_small_disabled",
"=",
"bitmap_small_disabled",
"if",
"not",
"base",
".",
"bitmap_small_disabled",
".",
"IsOk",
"(",
")",
":",
"base",
".",
"bitmap_small_disabled",
"=",
"self",
".",
"MakeDisabledBitmap",
"(",
"base",
".",
"bitmap_small",
")",
"base",
".",
"kind",
"=",
"kind",
"base",
".",
"help_string",
"=",
"help_string",
"base",
".",
"client_data",
"=",
"client_data",
"base",
".",
"state",
"=",
"0",
"temp_dc",
"=",
"wx",
".",
"ClientDC",
"(",
"self",
")",
"self",
".",
"FetchButtonSizeInfo",
"(",
"base",
",",
"RIBBON_BUTTONBAR_BUTTON_SMALL",
",",
"temp_dc",
")",
"self",
".",
"FetchButtonSizeInfo",
"(",
"base",
",",
"RIBBON_BUTTONBAR_BUTTON_MEDIUM",
",",
"temp_dc",
")",
"self",
".",
"FetchButtonSizeInfo",
"(",
"base",
",",
"RIBBON_BUTTONBAR_BUTTON_LARGE",
",",
"temp_dc",
")",
"self",
".",
"_buttons",
".",
"insert",
"(",
"pos",
",",
"base",
")",
"self",
".",
"_layouts_valid",
"=",
"False",
"return",
"base"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/buttonbar.py#L308-L403 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/generator/msvs.py | python | _AddAccumulatedActionsToMSVS | (p, spec, actions_dict) | Add actions accumulated into an actions_dict, merging as needed.
Arguments:
p: the target project
spec: the target project dict
actions_dict: dictionary keyed on input name, which maps to a list of
dicts describing the actions attached to that input file. | Add actions accumulated into an actions_dict, merging as needed. | [
"Add",
"actions",
"accumulated",
"into",
"an",
"actions_dict",
"merging",
"as",
"needed",
"."
] | def _AddAccumulatedActionsToMSVS(p, spec, actions_dict):
"""Add actions accumulated into an actions_dict, merging as needed.
Arguments:
p: the target project
spec: the target project dict
actions_dict: dictionary keyed on input name, which maps to a list of
dicts describing the actions attached to that input file.
"""
for primary_input in actions_dict:
inputs = OrderedSet()
outputs = OrderedSet()
descriptions = []
commands = []
for action in actions_dict[primary_input]:
inputs.update(OrderedSet(action['inputs']))
outputs.update(OrderedSet(action['outputs']))
descriptions.append(action['description'])
commands.append(action['command'])
# Add the custom build step for one input file.
description = ', and also '.join(descriptions)
command = '\r\n'.join(commands)
_AddCustomBuildToolForMSVS(p, spec,
primary_input=primary_input,
inputs=inputs,
outputs=outputs,
description=description,
cmd=command) | [
"def",
"_AddAccumulatedActionsToMSVS",
"(",
"p",
",",
"spec",
",",
"actions_dict",
")",
":",
"for",
"primary_input",
"in",
"actions_dict",
":",
"inputs",
"=",
"OrderedSet",
"(",
")",
"outputs",
"=",
"OrderedSet",
"(",
")",
"descriptions",
"=",
"[",
"]",
"commands",
"=",
"[",
"]",
"for",
"action",
"in",
"actions_dict",
"[",
"primary_input",
"]",
":",
"inputs",
".",
"update",
"(",
"OrderedSet",
"(",
"action",
"[",
"'inputs'",
"]",
")",
")",
"outputs",
".",
"update",
"(",
"OrderedSet",
"(",
"action",
"[",
"'outputs'",
"]",
")",
")",
"descriptions",
".",
"append",
"(",
"action",
"[",
"'description'",
"]",
")",
"commands",
".",
"append",
"(",
"action",
"[",
"'command'",
"]",
")",
"# Add the custom build step for one input file.",
"description",
"=",
"', and also '",
".",
"join",
"(",
"descriptions",
")",
"command",
"=",
"'\\r\\n'",
".",
"join",
"(",
"commands",
")",
"_AddCustomBuildToolForMSVS",
"(",
"p",
",",
"spec",
",",
"primary_input",
"=",
"primary_input",
",",
"inputs",
"=",
"inputs",
",",
"outputs",
"=",
"outputs",
",",
"description",
"=",
"description",
",",
"cmd",
"=",
"command",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/msvs.py#L487-L514 | ||
NeoGeographyToolkit/StereoPipeline | eedf54a919fb5cce1ab0e280bb0df4050763aa11 | src/asp/IceBridge/input_conversions.py | python | getCameraModelsFromNav | (imageFolder, orthoFolder,
inputCalFolder, inputCalCamera,
cameraLookupFile,
navFolder, navCameraFolder,
yyyymmdd, site,
startFrame, stopFrame, cameraMounting,
logger) | Given the folder containing navigation files, generate an
estimated camera model for each file. | Given the folder containing navigation files, generate an
estimated camera model for each file. | [
"Given",
"the",
"folder",
"containing",
"navigation",
"files",
"generate",
"an",
"estimated",
"camera",
"model",
"for",
"each",
"file",
"."
] | def getCameraModelsFromNav(imageFolder, orthoFolder,
inputCalFolder, inputCalCamera,
cameraLookupFile,
navFolder, navCameraFolder,
yyyymmdd, site,
startFrame, stopFrame, cameraMounting,
logger):
'''Given the folder containing navigation files, generate an
estimated camera model for each file.'''
# Note: Currently these output files DO NOT contain accurate intrinsic parameters!
logger.info("Get camera models from nav.")
# All the work is done by the separate file.
cmd = [imageFolder, orthoFolder, inputCalFolder, navFolder, navCameraFolder,
'--start-frame', str(startFrame),
'--stop-frame', str(stopFrame)]
# Pick an input calibration file to use. The exact one is not essential here,
# things will be refined later.
if inputCalCamera == "":
inputCalCamera = getCalibrationFileForFrame(cameraLookupFile, inputCalFolder,
startFrame, yyyymmdd, site, logger)
if inputCalCamera != "" and os.path.exists(inputCalCamera):
cmd += ['--input-calibration-camera', inputCalCamera]
# Only one alternate orientation (180 degree flipped) is handled here.
# - The two 90 degree flips are handled by rotating the input images!
if cameraMounting == 1:
cmd += ['--camera-mounting', str(cameraMounting)]
logger.info("camera_models_from_nav.py " + " ".join(cmd))
if (camera_models_from_nav.main(cmd) < 0):
raise Exception('Error generating camera models from nav!') | [
"def",
"getCameraModelsFromNav",
"(",
"imageFolder",
",",
"orthoFolder",
",",
"inputCalFolder",
",",
"inputCalCamera",
",",
"cameraLookupFile",
",",
"navFolder",
",",
"navCameraFolder",
",",
"yyyymmdd",
",",
"site",
",",
"startFrame",
",",
"stopFrame",
",",
"cameraMounting",
",",
"logger",
")",
":",
"# Note: Currently these output files DO NOT contain accurate intrinsic parameters!",
"logger",
".",
"info",
"(",
"\"Get camera models from nav.\"",
")",
"# All the work is done by the separate file.",
"cmd",
"=",
"[",
"imageFolder",
",",
"orthoFolder",
",",
"inputCalFolder",
",",
"navFolder",
",",
"navCameraFolder",
",",
"'--start-frame'",
",",
"str",
"(",
"startFrame",
")",
",",
"'--stop-frame'",
",",
"str",
"(",
"stopFrame",
")",
"]",
"# Pick an input calibration file to use. The exact one is not essential here,",
"# things will be refined later.",
"if",
"inputCalCamera",
"==",
"\"\"",
":",
"inputCalCamera",
"=",
"getCalibrationFileForFrame",
"(",
"cameraLookupFile",
",",
"inputCalFolder",
",",
"startFrame",
",",
"yyyymmdd",
",",
"site",
",",
"logger",
")",
"if",
"inputCalCamera",
"!=",
"\"\"",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"inputCalCamera",
")",
":",
"cmd",
"+=",
"[",
"'--input-calibration-camera'",
",",
"inputCalCamera",
"]",
"# Only one alternate orientation (180 degree flipped) is handled here.",
"# - The two 90 degree flips are handled by rotating the input images!",
"if",
"cameraMounting",
"==",
"1",
":",
"cmd",
"+=",
"[",
"'--camera-mounting'",
",",
"str",
"(",
"cameraMounting",
")",
"]",
"logger",
".",
"info",
"(",
"\"camera_models_from_nav.py \"",
"+",
"\" \"",
".",
"join",
"(",
"cmd",
")",
")",
"if",
"(",
"camera_models_from_nav",
".",
"main",
"(",
"cmd",
")",
"<",
"0",
")",
":",
"raise",
"Exception",
"(",
"'Error generating camera models from nav!'",
")"
] | https://github.com/NeoGeographyToolkit/StereoPipeline/blob/eedf54a919fb5cce1ab0e280bb0df4050763aa11/src/asp/IceBridge/input_conversions.py#L579-L615 | ||
esa/pykep | b410363653623730b577de257c04b0e0289f2014 | pykep/trajopt/_lt_margo.py | python | lt_margo.pretty | (self, x) | prob.pretty(x)
Args:
- x (``list``, ``tuple``, ``numpy.ndarray``): Decision chromosome, e.g. (``pygmo.population.champion_x``).
Prints human readable information on the trajectory represented by the decision vector x | prob.pretty(x) | [
"prob",
".",
"pretty",
"(",
"x",
")"
] | def pretty(self, x):
"""
prob.pretty(x)
Args:
- x (``list``, ``tuple``, ``numpy.ndarray``): Decision chromosome, e.g. (``pygmo.population.champion_x``).
Prints human readable information on the trajectory represented by the decision vector x
"""
if not len(x) == len(self.get_bounds()[0]):
raise ValueError("Invalid length of the decision vector x")
n_seg = self.__n_seg
m_i = self.__sc.mass
t0 = x[0]
T = x[1]
m_f = x[2]
thrusts = [np.linalg.norm(x[3 + 3 * i: 6 + 3 * i])
for i in range(n_seg)]
tf = t0 + T
mP = m_i - m_f
deltaV = self.__sc.isp * pk.G0 * np.log(m_i / m_f)
dt = np.append(self.__fwd_dt, self.__bwd_dt) * T / pk.DAY2SEC
time_thrusts_on = sum(dt[i] for i in range(
len(thrusts)) if thrusts[i] > 0.1)
print("Departure:", pk.epoch(t0), "(", t0, "mjd2000 )")
print("Time of flight:", T, "days")
print("Arrival:", pk.epoch(tf), "(", tf, "mjd2000 )")
print("Delta-v:", deltaV, "m/s")
print("Propellant consumption:", mP, "kg")
print("Thrust-on time:", time_thrusts_on, "days") | [
"def",
"pretty",
"(",
"self",
",",
"x",
")",
":",
"if",
"not",
"len",
"(",
"x",
")",
"==",
"len",
"(",
"self",
".",
"get_bounds",
"(",
")",
"[",
"0",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid length of the decision vector x\"",
")",
"n_seg",
"=",
"self",
".",
"__n_seg",
"m_i",
"=",
"self",
".",
"__sc",
".",
"mass",
"t0",
"=",
"x",
"[",
"0",
"]",
"T",
"=",
"x",
"[",
"1",
"]",
"m_f",
"=",
"x",
"[",
"2",
"]",
"thrusts",
"=",
"[",
"np",
".",
"linalg",
".",
"norm",
"(",
"x",
"[",
"3",
"+",
"3",
"*",
"i",
":",
"6",
"+",
"3",
"*",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"n_seg",
")",
"]",
"tf",
"=",
"t0",
"+",
"T",
"mP",
"=",
"m_i",
"-",
"m_f",
"deltaV",
"=",
"self",
".",
"__sc",
".",
"isp",
"*",
"pk",
".",
"G0",
"*",
"np",
".",
"log",
"(",
"m_i",
"/",
"m_f",
")",
"dt",
"=",
"np",
".",
"append",
"(",
"self",
".",
"__fwd_dt",
",",
"self",
".",
"__bwd_dt",
")",
"*",
"T",
"/",
"pk",
".",
"DAY2SEC",
"time_thrusts_on",
"=",
"sum",
"(",
"dt",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"thrusts",
")",
")",
"if",
"thrusts",
"[",
"i",
"]",
">",
"0.1",
")",
"print",
"(",
"\"Departure:\"",
",",
"pk",
".",
"epoch",
"(",
"t0",
")",
",",
"\"(\"",
",",
"t0",
",",
"\"mjd2000 )\"",
")",
"print",
"(",
"\"Time of flight:\"",
",",
"T",
",",
"\"days\"",
")",
"print",
"(",
"\"Arrival:\"",
",",
"pk",
".",
"epoch",
"(",
"tf",
")",
",",
"\"(\"",
",",
"tf",
",",
"\"mjd2000 )\"",
")",
"print",
"(",
"\"Delta-v:\"",
",",
"deltaV",
",",
"\"m/s\"",
")",
"print",
"(",
"\"Propellant consumption:\"",
",",
"mP",
",",
"\"kg\"",
")",
"print",
"(",
"\"Thrust-on time:\"",
",",
"time_thrusts_on",
",",
"\"days\"",
")"
] | https://github.com/esa/pykep/blob/b410363653623730b577de257c04b0e0289f2014/pykep/trajopt/_lt_margo.py#L636-L670 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/layers/python/layers/layers.py | python | convolution2d | (inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
rate=1,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer,
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None) | Adds a 2D convolution followed by an optional batch_norm layer.
`convolution2d` creates a variable called `weights`, representing the
convolutional kernel, that is convolved with the `inputs` to produce a
`Tensor` of activations. If a `normalizer_fn` is provided (such as
`batch_norm`), it is then applied. Otherwise, if `normalizer_fn` is
None and a `biases_initializer` is provided then a `biases` variable would be
created and added the activations. Finally, if `activation_fn` is not `None`,
it is applied to the activations as well.
Performs a'trous convolution with input stride equal to rate if rate is
greater than one.
Args:
inputs: a 4-D tensor `[batch_size, height, width, channels]`.
num_outputs: integer, the number of output filters.
kernel_size: a list of length 2 `[kernel_height, kernel_width]` of
of the filters. Can be an int if both values are the same.
stride: a list of length 2 `[stride_height, stride_width]`.
Can be an int if both strides are the same. Note that presently
both strides must have the same value.
padding: one of `VALID` or `SAME`.
rate: integer. If less than or equal to 1, a standard convolution is used.
If greater than 1, than the a'trous convolution is applied and `stride`
must be set to 1.
activation_fn: activation function.
normalizer_fn: normalization function to use instead of `biases`. If
`normalize_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
normalizer_params: normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: optional list of collections for all the variables or
a dictionay containing a different list of collection per variable.
outputs_collections: collection to add the outputs.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for `variable_op_scope`.
Returns:
a tensor representing the output of the operation.
Raises:
ValueError: if both 'rate' and `stride` are larger than one. | Adds a 2D convolution followed by an optional batch_norm layer. | [
"Adds",
"a",
"2D",
"convolution",
"followed",
"by",
"an",
"optional",
"batch_norm",
"layer",
"."
] | def convolution2d(inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
rate=1,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer,
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
"""Adds a 2D convolution followed by an optional batch_norm layer.
`convolution2d` creates a variable called `weights`, representing the
convolutional kernel, that is convolved with the `inputs` to produce a
`Tensor` of activations. If a `normalizer_fn` is provided (such as
`batch_norm`), it is then applied. Otherwise, if `normalizer_fn` is
None and a `biases_initializer` is provided then a `biases` variable would be
created and added the activations. Finally, if `activation_fn` is not `None`,
it is applied to the activations as well.
Performs a'trous convolution with input stride equal to rate if rate is
greater than one.
Args:
inputs: a 4-D tensor `[batch_size, height, width, channels]`.
num_outputs: integer, the number of output filters.
kernel_size: a list of length 2 `[kernel_height, kernel_width]` of
of the filters. Can be an int if both values are the same.
stride: a list of length 2 `[stride_height, stride_width]`.
Can be an int if both strides are the same. Note that presently
both strides must have the same value.
padding: one of `VALID` or `SAME`.
rate: integer. If less than or equal to 1, a standard convolution is used.
If greater than 1, than the a'trous convolution is applied and `stride`
must be set to 1.
activation_fn: activation function.
normalizer_fn: normalization function to use instead of `biases`. If
`normalize_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
normalizer_params: normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: optional list of collections for all the variables or
a dictionay containing a different list of collection per variable.
outputs_collections: collection to add the outputs.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for `variable_op_scope`.
Returns:
a tensor representing the output of the operation.
Raises:
ValueError: if both 'rate' and `stride` are larger than one.
"""
with variable_scope.variable_op_scope([inputs],
scope, 'Conv', reuse=reuse) as sc:
inputs = ops.convert_to_tensor(inputs)
dtype = inputs.dtype.base_dtype
kernel_h, kernel_w = utils.two_element_tuple(kernel_size)
stride_h, stride_w = utils.two_element_tuple(stride)
if rate > 1 and (stride_h > 1 or stride_w > 1):
raise ValueError('Only one of rate or stride can be larger than one')
num_filters_in = utils.last_dimension(inputs.get_shape(), min_rank=4)
weights_shape = [kernel_h, kernel_w,
num_filters_in, num_outputs]
weights_collections = utils.get_variable_collections(
variables_collections, 'weights')
weights = variables.model_variable('weights',
shape=weights_shape,
dtype=dtype,
initializer=weights_initializer,
regularizer=weights_regularizer,
collections=weights_collections,
trainable=trainable)
if rate > 1:
outputs = nn.atrous_conv2d(inputs, weights, rate, padding=padding)
else:
outputs = nn.conv2d(inputs, weights, [1, stride_h, stride_w, 1],
padding=padding)
if normalizer_fn:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normalizer_params)
else:
if biases_initializer is not None:
biases_collections = utils.get_variable_collections(
variables_collections, 'biases')
biases = variables.model_variable('biases',
shape=[num_outputs,],
dtype=dtype,
initializer=biases_initializer,
regularizer=biases_regularizer,
collections=biases_collections,
trainable=trainable)
outputs = nn.bias_add(outputs, biases)
if activation_fn:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections, sc.name, outputs) | [
"def",
"convolution2d",
"(",
"inputs",
",",
"num_outputs",
",",
"kernel_size",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
",",
"rate",
"=",
"1",
",",
"activation_fn",
"=",
"nn",
".",
"relu",
",",
"normalizer_fn",
"=",
"None",
",",
"normalizer_params",
"=",
"None",
",",
"weights_initializer",
"=",
"initializers",
".",
"xavier_initializer",
"(",
")",
",",
"weights_regularizer",
"=",
"None",
",",
"biases_initializer",
"=",
"init_ops",
".",
"zeros_initializer",
",",
"biases_regularizer",
"=",
"None",
",",
"reuse",
"=",
"None",
",",
"variables_collections",
"=",
"None",
",",
"outputs_collections",
"=",
"None",
",",
"trainable",
"=",
"True",
",",
"scope",
"=",
"None",
")",
":",
"with",
"variable_scope",
".",
"variable_op_scope",
"(",
"[",
"inputs",
"]",
",",
"scope",
",",
"'Conv'",
",",
"reuse",
"=",
"reuse",
")",
"as",
"sc",
":",
"inputs",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"inputs",
")",
"dtype",
"=",
"inputs",
".",
"dtype",
".",
"base_dtype",
"kernel_h",
",",
"kernel_w",
"=",
"utils",
".",
"two_element_tuple",
"(",
"kernel_size",
")",
"stride_h",
",",
"stride_w",
"=",
"utils",
".",
"two_element_tuple",
"(",
"stride",
")",
"if",
"rate",
">",
"1",
"and",
"(",
"stride_h",
">",
"1",
"or",
"stride_w",
">",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'Only one of rate or stride can be larger than one'",
")",
"num_filters_in",
"=",
"utils",
".",
"last_dimension",
"(",
"inputs",
".",
"get_shape",
"(",
")",
",",
"min_rank",
"=",
"4",
")",
"weights_shape",
"=",
"[",
"kernel_h",
",",
"kernel_w",
",",
"num_filters_in",
",",
"num_outputs",
"]",
"weights_collections",
"=",
"utils",
".",
"get_variable_collections",
"(",
"variables_collections",
",",
"'weights'",
")",
"weights",
"=",
"variables",
".",
"model_variable",
"(",
"'weights'",
",",
"shape",
"=",
"weights_shape",
",",
"dtype",
"=",
"dtype",
",",
"initializer",
"=",
"weights_initializer",
",",
"regularizer",
"=",
"weights_regularizer",
",",
"collections",
"=",
"weights_collections",
",",
"trainable",
"=",
"trainable",
")",
"if",
"rate",
">",
"1",
":",
"outputs",
"=",
"nn",
".",
"atrous_conv2d",
"(",
"inputs",
",",
"weights",
",",
"rate",
",",
"padding",
"=",
"padding",
")",
"else",
":",
"outputs",
"=",
"nn",
".",
"conv2d",
"(",
"inputs",
",",
"weights",
",",
"[",
"1",
",",
"stride_h",
",",
"stride_w",
",",
"1",
"]",
",",
"padding",
"=",
"padding",
")",
"if",
"normalizer_fn",
":",
"normalizer_params",
"=",
"normalizer_params",
"or",
"{",
"}",
"outputs",
"=",
"normalizer_fn",
"(",
"outputs",
",",
"*",
"*",
"normalizer_params",
")",
"else",
":",
"if",
"biases_initializer",
"is",
"not",
"None",
":",
"biases_collections",
"=",
"utils",
".",
"get_variable_collections",
"(",
"variables_collections",
",",
"'biases'",
")",
"biases",
"=",
"variables",
".",
"model_variable",
"(",
"'biases'",
",",
"shape",
"=",
"[",
"num_outputs",
",",
"]",
",",
"dtype",
"=",
"dtype",
",",
"initializer",
"=",
"biases_initializer",
",",
"regularizer",
"=",
"biases_regularizer",
",",
"collections",
"=",
"biases_collections",
",",
"trainable",
"=",
"trainable",
")",
"outputs",
"=",
"nn",
".",
"bias_add",
"(",
"outputs",
",",
"biases",
")",
"if",
"activation_fn",
":",
"outputs",
"=",
"activation_fn",
"(",
"outputs",
")",
"return",
"utils",
".",
"collect_named_outputs",
"(",
"outputs_collections",
",",
"sc",
".",
"name",
",",
"outputs",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/layers/python/layers/layers.py#L320-L429 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/training/python/training/sampling_ops.py | python | _verify_input | (tensor_list, labels, probs_list) | return tensor_list, labels, checked_probs_list | Verify that batched inputs are well-formed. | Verify that batched inputs are well-formed. | [
"Verify",
"that",
"batched",
"inputs",
"are",
"well",
"-",
"formed",
"."
] | def _verify_input(tensor_list, labels, probs_list):
"""Verify that batched inputs are well-formed."""
checked_probs_list = []
for probs in probs_list:
# Since number of classes shouldn't change at runtime, probalities shape
# should be fully defined.
probs.get_shape().assert_is_fully_defined()
# Probabilities must be 1D.
probs.get_shape().assert_has_rank(1)
# Probabilities must be nonnegative and sum to one.
tol = 1e-6
prob_sum = math_ops.reduce_sum(probs)
checked_probs = control_flow_ops.with_dependencies(
[check_ops.assert_non_negative(probs),
check_ops.assert_less(prob_sum, 1.0 + tol),
check_ops.assert_less(1.0 - tol, prob_sum)],
probs)
checked_probs_list.append(checked_probs)
# All probabilities should be the same length.
prob_length = checked_probs_list[0].get_shape().num_elements()
for checked_prob in checked_probs_list:
if checked_prob.get_shape().num_elements() != prob_length:
raise ValueError('Probability parameters must have the same length.')
# Labels tensor should only have batch dimension.
labels.get_shape().assert_has_rank(1)
for tensor in tensor_list:
# Data tensor should have a batch dimension.
tensor_shape = tensor.get_shape().with_rank_at_least(1)
# Data and label batch dimensions must be compatible.
tensor_shape[0].assert_is_compatible_with(labels.get_shape()[0])
# Data and labels must have the same, strictly positive batch size. Since we
# can't assume we know the batch size at graph creation, add runtime checks.
labels_batch_size = array_ops.shape(labels)[0]
lbl_assert = check_ops.assert_positive(labels_batch_size)
# Make each tensor depend on its own checks.
labels = control_flow_ops.with_dependencies([lbl_assert], labels)
tensor_list = [control_flow_ops.with_dependencies(
[lbl_assert,
check_ops.assert_equal(array_ops.shape(x)[0], labels_batch_size)],
x) for x in tensor_list]
# Label's classes must be integers 0 <= x < num_classes.
labels = control_flow_ops.with_dependencies(
[check_ops.assert_integer(labels),
check_ops.assert_non_negative(labels),
check_ops.assert_less(labels, math_ops.cast(prob_length, labels.dtype))],
labels)
return tensor_list, labels, checked_probs_list | [
"def",
"_verify_input",
"(",
"tensor_list",
",",
"labels",
",",
"probs_list",
")",
":",
"checked_probs_list",
"=",
"[",
"]",
"for",
"probs",
"in",
"probs_list",
":",
"# Since number of classes shouldn't change at runtime, probalities shape",
"# should be fully defined.",
"probs",
".",
"get_shape",
"(",
")",
".",
"assert_is_fully_defined",
"(",
")",
"# Probabilities must be 1D.",
"probs",
".",
"get_shape",
"(",
")",
".",
"assert_has_rank",
"(",
"1",
")",
"# Probabilities must be nonnegative and sum to one.",
"tol",
"=",
"1e-6",
"prob_sum",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"probs",
")",
"checked_probs",
"=",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"check_ops",
".",
"assert_non_negative",
"(",
"probs",
")",
",",
"check_ops",
".",
"assert_less",
"(",
"prob_sum",
",",
"1.0",
"+",
"tol",
")",
",",
"check_ops",
".",
"assert_less",
"(",
"1.0",
"-",
"tol",
",",
"prob_sum",
")",
"]",
",",
"probs",
")",
"checked_probs_list",
".",
"append",
"(",
"checked_probs",
")",
"# All probabilities should be the same length.",
"prob_length",
"=",
"checked_probs_list",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"num_elements",
"(",
")",
"for",
"checked_prob",
"in",
"checked_probs_list",
":",
"if",
"checked_prob",
".",
"get_shape",
"(",
")",
".",
"num_elements",
"(",
")",
"!=",
"prob_length",
":",
"raise",
"ValueError",
"(",
"'Probability parameters must have the same length.'",
")",
"# Labels tensor should only have batch dimension.",
"labels",
".",
"get_shape",
"(",
")",
".",
"assert_has_rank",
"(",
"1",
")",
"for",
"tensor",
"in",
"tensor_list",
":",
"# Data tensor should have a batch dimension.",
"tensor_shape",
"=",
"tensor",
".",
"get_shape",
"(",
")",
".",
"with_rank_at_least",
"(",
"1",
")",
"# Data and label batch dimensions must be compatible.",
"tensor_shape",
"[",
"0",
"]",
".",
"assert_is_compatible_with",
"(",
"labels",
".",
"get_shape",
"(",
")",
"[",
"0",
"]",
")",
"# Data and labels must have the same, strictly positive batch size. Since we",
"# can't assume we know the batch size at graph creation, add runtime checks.",
"labels_batch_size",
"=",
"array_ops",
".",
"shape",
"(",
"labels",
")",
"[",
"0",
"]",
"lbl_assert",
"=",
"check_ops",
".",
"assert_positive",
"(",
"labels_batch_size",
")",
"# Make each tensor depend on its own checks.",
"labels",
"=",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"lbl_assert",
"]",
",",
"labels",
")",
"tensor_list",
"=",
"[",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"lbl_assert",
",",
"check_ops",
".",
"assert_equal",
"(",
"array_ops",
".",
"shape",
"(",
"x",
")",
"[",
"0",
"]",
",",
"labels_batch_size",
")",
"]",
",",
"x",
")",
"for",
"x",
"in",
"tensor_list",
"]",
"# Label's classes must be integers 0 <= x < num_classes.",
"labels",
"=",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"check_ops",
".",
"assert_integer",
"(",
"labels",
")",
",",
"check_ops",
".",
"assert_non_negative",
"(",
"labels",
")",
",",
"check_ops",
".",
"assert_less",
"(",
"labels",
",",
"math_ops",
".",
"cast",
"(",
"prob_length",
",",
"labels",
".",
"dtype",
")",
")",
"]",
",",
"labels",
")",
"return",
"tensor_list",
",",
"labels",
",",
"checked_probs_list"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/training/python/training/sampling_ops.py#L263-L319 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/autoreload.py | python | add_reload_hook | (fn: Callable[[], None]) | Add a function to be called before reloading the process.
Note that for open file and socket handles it is generally
preferable to set the ``FD_CLOEXEC`` flag (using `fcntl` or
`os.set_inheritable`) instead of using a reload hook to close them. | Add a function to be called before reloading the process. | [
"Add",
"a",
"function",
"to",
"be",
"called",
"before",
"reloading",
"the",
"process",
"."
] | def add_reload_hook(fn: Callable[[], None]) -> None:
"""Add a function to be called before reloading the process.
Note that for open file and socket handles it is generally
preferable to set the ``FD_CLOEXEC`` flag (using `fcntl` or
`os.set_inheritable`) instead of using a reload hook to close them.
"""
_reload_hooks.append(fn) | [
"def",
"add_reload_hook",
"(",
"fn",
":",
"Callable",
"[",
"[",
"]",
",",
"None",
"]",
")",
"->",
"None",
":",
"_reload_hooks",
".",
"append",
"(",
"fn",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/autoreload.py#L156-L163 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/WorkingPlane.py | python | Plane.getNormal | (self) | return n | Return the normal vector of the plane (axis).
Returns
-------
Base::Vector3
The `axis` attribute of the plane. | Return the normal vector of the plane (axis). | [
"Return",
"the",
"normal",
"vector",
"of",
"the",
"plane",
"(",
"axis",
")",
"."
] | def getNormal(self):
"""Return the normal vector of the plane (axis).
Returns
-------
Base::Vector3
The `axis` attribute of the plane.
"""
n = self.axis
# Arch active container if based on App Part
# if FreeCAD.GuiUp:
# import FreeCADGui
# view = FreeCADGui.ActiveDocument.ActiveView
# a = view.getActiveObject("Arch")
# if a:
# n = a.Placement.inverse().Rotation.multVec(n)
return n | [
"def",
"getNormal",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"axis",
"# Arch active container if based on App Part",
"# if FreeCAD.GuiUp:",
"# import FreeCADGui",
"# view = FreeCADGui.ActiveDocument.ActiveView",
"# a = view.getActiveObject(\"Arch\")",
"# if a:",
"# n = a.Placement.inverse().Rotation.multVec(n)",
"return",
"n"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/WorkingPlane.py#L906-L922 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.