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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/tensor_util.py | python | _is_array_like | (obj) | Check if a given object is array-like. | Check if a given object is array-like. | [
"Check",
"if",
"a",
"given",
"object",
"is",
"array",
"-",
"like",
"."
] | def _is_array_like(obj): # pylint: disable=invalid-name
"""Check if a given object is array-like."""
if isinstance(obj, ops.Tensor) and not isinstance(obj, ops._EagerTensorBase): # pylint: disable=protected-access
# Tensor implements __array__ only so it can inform the user that it is not
# a valid array.
return False
# TODO(slebedev): an object could also implement C-level array interface.
if (callable(getattr(obj, "__array__", None)) or
isinstance(getattr(obj, "__array_interface__", None), dict)):
return True
try:
memoryview(obj)
except TypeError:
return False
else:
return not isinstance(obj, bytes) | [
"def",
"_is_array_like",
"(",
"obj",
")",
":",
"# pylint: disable=invalid-name",
"if",
"isinstance",
"(",
"obj",
",",
"ops",
".",
"Tensor",
")",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"ops",
".",
"_EagerTensorBase",
")",
":",
"# pylint: disable=protected-a... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/tensor_util.py#L336-L353 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/math_ops.py | python | Cdist.__init__ | (self, p=2.0) | Initialize Cdist | Initialize Cdist | [
"Initialize",
"Cdist"
] | def __init__(self, p=2.0):
"""Initialize Cdist"""
validator.check_value_type("p", p, [float], self.name)
validator.check_non_negative_float(p, "p", self.name)
self.init_prim_io_names(inputs=['input_x', 'input_y'], outputs=['output']) | [
"def",
"__init__",
"(",
"self",
",",
"p",
"=",
"2.0",
")",
":",
"validator",
".",
"check_value_type",
"(",
"\"p\"",
",",
"p",
",",
"[",
"float",
"]",
",",
"self",
".",
"name",
")",
"validator",
".",
"check_non_negative_float",
"(",
"p",
",",
"\"p\"",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/math_ops.py#L1226-L1230 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/http/server.py | python | SimpleHTTPRequestHandler.guess_type | (self, path) | Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess. | Guess the type of a file. | [
"Guess",
"the",
"type",
"of",
"a",
"file",
"."
] | def guess_type(self, path):
"""Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
return self.extensions_map[''] | [
"def",
"guess_type",
"(",
"self",
",",
"path",
")",
":",
"base",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"path",
")",
"if",
"ext",
"in",
"self",
".",
"extensions_map",
":",
"return",
"self",
".",
"extensions_map",
"[",
"ext",
"]",
"ext",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/server.py#L846-L868 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexing.py | python | IndexingMixin.at | (self) | return _AtIndexer("at", self) | Access a single value for a row/column label pair.
Similar to ``loc``, in that both provide label-based lookups. Use
``at`` if you only need to get or set a single value in a DataFrame
or Series.
Raises
------
KeyError
If 'label' does not exist in DataFrame.
See Also
--------
DataFrame.iat : Access a single value for a row/column pair by integer
position.
DataFrame.loc : Access a group of rows and columns by label(s).
Series.at : Access a single value using a label.
Examples
--------
>>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
... index=[4, 5, 6], columns=['A', 'B', 'C'])
>>> df
A B C
4 0 2 3
5 0 4 1
6 10 20 30
Get value at specified row/column pair
>>> df.at[4, 'B']
2
Set value at specified row/column pair
>>> df.at[4, 'B'] = 10
>>> df.at[4, 'B']
10
Get value within a Series
>>> df.loc[5].at['B']
4 | Access a single value for a row/column label pair. | [
"Access",
"a",
"single",
"value",
"for",
"a",
"row",
"/",
"column",
"label",
"pair",
"."
] | def at(self) -> "_AtIndexer":
"""
Access a single value for a row/column label pair.
Similar to ``loc``, in that both provide label-based lookups. Use
``at`` if you only need to get or set a single value in a DataFrame
or Series.
Raises
------
KeyError
If 'label' does not exist in DataFrame.
See Also
--------
DataFrame.iat : Access a single value for a row/column pair by integer
position.
DataFrame.loc : Access a group of rows and columns by label(s).
Series.at : Access a single value using a label.
Examples
--------
>>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
... index=[4, 5, 6], columns=['A', 'B', 'C'])
>>> df
A B C
4 0 2 3
5 0 4 1
6 10 20 30
Get value at specified row/column pair
>>> df.at[4, 'B']
2
Set value at specified row/column pair
>>> df.at[4, 'B'] = 10
>>> df.at[4, 'B']
10
Get value within a Series
>>> df.loc[5].at['B']
4
"""
return _AtIndexer("at", self) | [
"def",
"at",
"(",
"self",
")",
"->",
"\"_AtIndexer\"",
":",
"return",
"_AtIndexer",
"(",
"\"at\"",
",",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexing.py#L472-L518 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | benchmark/opperf/nd_operations/misc_operators.py | python | run_mx_misc_operators_benchmarks | (ctx=mx.cpu(), dtype='float32', profiler='native', int64_tensor='off', warmup=25, runs=100) | return merge_map_list(array_ops_benchmark + add_n_benchmark + upsampling_benchmark + custom_benchmark + [mx_misc_op_results]) | Runs benchmarks with the given context and precision (dtype) for all the miscellaneous
operators in MXNet.
Parameters
----------
ctx: mx.ctx
Context to run benchmarks
dtype: str, default 'float32'
Precision to use for benchmarks
profiler: str, default 'native'
Type of Profiler to use (native/python)
int64_tensor: str, default 'off'
Input tensor size to use for tests (if on, dimensions >= 2**32)
warmup: int, default 25
Number of times to run for warmup
runs: int, default 100
Number of runs to capture benchmark results
Returns
-------
Dictionary of results. Key -> Name of the operator, Value -> Benchmark results. | Runs benchmarks with the given context and precision (dtype) for all the miscellaneous
operators in MXNet. | [
"Runs",
"benchmarks",
"with",
"the",
"given",
"context",
"and",
"precision",
"(",
"dtype",
")",
"for",
"all",
"the",
"miscellaneous",
"operators",
"in",
"MXNet",
"."
] | def run_mx_misc_operators_benchmarks(ctx=mx.cpu(), dtype='float32', profiler='native', int64_tensor='off', warmup=25, runs=100):
"""Runs benchmarks with the given context and precision (dtype) for all the miscellaneous
operators in MXNet.
Parameters
----------
ctx: mx.ctx
Context to run benchmarks
dtype: str, default 'float32'
Precision to use for benchmarks
profiler: str, default 'native'
Type of Profiler to use (native/python)
int64_tensor: str, default 'off'
Input tensor size to use for tests (if on, dimensions >= 2**32)
warmup: int, default 25
Number of times to run for warmup
runs: int, default 100
Number of runs to capture benchmark results
Returns
-------
Dictionary of results. Key -> Name of the operator, Value -> Benchmark results.
"""
standard_inputs_array_ops = [{"args": [(1024, 1024)],
"num_arrays": 1},
{"args": [(10000, 1)],
"num_arrays": 1},
{"args": [(10000, 10)],
"num_arrays": 1}]
int64_tensor_inputs_array_ops = [{"args": [(2**32, 1)],
"num_arrays":1}]
standard_inputs_add_n = [{"args": [(1024, 1024)]},
{"args": [(10000, 1)]},
{"args": [(10000, 10)]}]
int64_tensor_inputs_add_n = [{"args": [(2**16, 2**16)]}]
standard_inputs_upsampling = [{"args": (32, 3, 256, 256),
"scale": 2,
"sample_type": "nearest"},
{"args": (32, 3, 10000, 1),
"scale": 4,
"sample_type": "nearest"}]
int64_tensor_inputs_upsampling = [{"args": (2**32 + 1, 1, 1, 1),
"scale": 2,
"sample_type": "nearest"}]
standard_inputs_custom = [{"args": [(1024, 1024)],
"op_type": "CustomAddOne"},
{"args": [(10000, 1)],
"op_type": "CustomAddOne"},
{"args": [(10000, 10)],
"op_type": "CustomAddOne"}]
int64_tensor_inputs_custom = [{"args": [(2**32 + 1, 1)],
"op_type": "CustomAddOne"}]
if int64_tensor == 'on':
inputs_array_ops = int64_tensor_inputs_array_ops
inputs_add_n = int64_tensor_inputs_add_n
inputs_upsampling = int64_tensor_inputs_upsampling
inputs_custom = int64_tensor_inputs_custom
else:
inputs_array_ops = standard_inputs_array_ops
inputs_add_n = standard_inputs_add_n
inputs_upsampling = standard_inputs_upsampling
inputs_custom = standard_inputs_custom
# Individual tests for ops with positional args
array_ops_benchmark = run_performance_test([getattr(MX_OP_MODULE, "reset_arrays"),
getattr(MX_OP_MODULE, "multi_all_finite"),
getattr(MX_OP_MODULE, "multi_sum_sq")],
run_backward=False,
dtype=dtype,
ctx=ctx,
profiler=profiler,
inputs=inputs_array_ops,
warmup=warmup,
runs=runs)
add_n_benchmark = run_performance_test([getattr(MX_OP_MODULE, "add_n")],
run_backward=True,
dtype=dtype,
ctx=ctx,
profiler=profiler,
inputs=inputs_add_n,
warmup=warmup,
runs=runs)
# There are currently issus with UpSampling with bilinear interpolation.
# track issue here: https://github.com/apache/incubator-mxnet/issues/9138
upsampling_benchmark = run_performance_test([getattr(MX_OP_MODULE, "UpSampling")],
run_backward=True,
dtype=dtype,
ctx=ctx,
profiler=profiler,
inputs=inputs_upsampling,
warmup=warmup,
runs=runs)
# Create and register CustomAddOne operator for use in Custom op testing
c = CustomAddOneProp()
c.create_operator(ctx, [(1024,1024)], [dtype])
custom_benchmark = run_performance_test([getattr(MX_OP_MODULE, "Custom")],
run_backward=True,
dtype=dtype,
ctx=ctx,
profiler=profiler,
inputs=inputs_custom,
warmup=warmup,
runs=runs)
# Fetch remaining Miscellaneous Operators
mx_misc_ops = get_remaining_miscellaneous_operators()
# Run benchmarks
mx_misc_op_results = run_op_benchmarks(mx_misc_ops, dtype, ctx, profiler, int64_tensor, warmup, runs)
return merge_map_list(array_ops_benchmark + add_n_benchmark + upsampling_benchmark + custom_benchmark + [mx_misc_op_results]) | [
"def",
"run_mx_misc_operators_benchmarks",
"(",
"ctx",
"=",
"mx",
".",
"cpu",
"(",
")",
",",
"dtype",
"=",
"'float32'",
",",
"profiler",
"=",
"'native'",
",",
"int64_tensor",
"=",
"'off'",
",",
"warmup",
"=",
"25",
",",
"runs",
"=",
"100",
")",
":",
"s... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/benchmark/opperf/nd_operations/misc_operators.py#L40-L151 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/model_selection/_split.py | python | _validate_shuffle_split_init | (test_size, train_size) | Validation helper to check the test_size and train_size at init
NOTE This does not take into account the number of samples which is known
only at split | Validation helper to check the test_size and train_size at init | [
"Validation",
"helper",
"to",
"check",
"the",
"test_size",
"and",
"train_size",
"at",
"init"
] | def _validate_shuffle_split_init(test_size, train_size):
"""Validation helper to check the test_size and train_size at init
NOTE This does not take into account the number of samples which is known
only at split
"""
if test_size is None and train_size is None:
raise ValueError('test_size and train_size can not both be None')
if test_size is not None:
if np.asarray(test_size).dtype.kind == 'f':
if test_size >= 1.:
raise ValueError(
'test_size=%f should be smaller '
'than 1.0 or be an integer' % test_size)
elif np.asarray(test_size).dtype.kind != 'i':
# int values are checked during split based on the input
raise ValueError("Invalid value for test_size: %r" % test_size)
if train_size is not None:
if np.asarray(train_size).dtype.kind == 'f':
if train_size >= 1.:
raise ValueError("train_size=%f should be smaller "
"than 1.0 or be an integer" % train_size)
elif (np.asarray(test_size).dtype.kind == 'f' and
(train_size + test_size) > 1.):
raise ValueError('The sum of test_size and train_size = %f, '
'should be smaller than 1.0. Reduce '
'test_size and/or train_size.' %
(train_size + test_size))
elif np.asarray(train_size).dtype.kind != 'i':
# int values are checked during split based on the input
raise ValueError("Invalid value for train_size: %r" % train_size) | [
"def",
"_validate_shuffle_split_init",
"(",
"test_size",
",",
"train_size",
")",
":",
"if",
"test_size",
"is",
"None",
"and",
"train_size",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'test_size and train_size can not both be None'",
")",
"if",
"test_size",
"is",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/model_selection/_split.py#L1328-L1360 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | FWCore/ParameterSet/python/Config.py | python | Process.es_producers_ | (self) | return DictTypes.FixedKeysDict(self.__esproducers) | returns a dict of the esproducers that have been added to the Process | returns a dict of the esproducers that have been added to the Process | [
"returns",
"a",
"dict",
"of",
"the",
"esproducers",
"that",
"have",
"been",
"added",
"to",
"the",
"Process"
] | def es_producers_(self):
"""returns a dict of the esproducers that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__esproducers) | [
"def",
"es_producers_",
"(",
"self",
")",
":",
"return",
"DictTypes",
".",
"FixedKeysDict",
"(",
"self",
".",
"__esproducers",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/ParameterSet/python/Config.py#L328-L330 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/graph_editor/subgraph.py | python | SubGraphView.remap | (self, new_input_indices=None, new_output_indices=None) | return res | Remap the inputs and outputs of the subgraph.
Note that this is only modifying the view: the underlying tf.Graph is not
affected.
Args:
new_input_indices: an iterable of integers representing a mapping between
the old inputs and the new ones. This mapping can be under-complete and
must be without repetitions.
new_output_indices: an iterable of integers representing a mapping between
the old outputs and the new ones. This mapping can be under-complete and
can have repetitions.
Returns:
A new modified instance of the original subgraph view with remapped
inputs and outputs. | Remap the inputs and outputs of the subgraph. | [
"Remap",
"the",
"inputs",
"and",
"outputs",
"of",
"the",
"subgraph",
"."
] | def remap(self, new_input_indices=None, new_output_indices=None):
"""Remap the inputs and outputs of the subgraph.
Note that this is only modifying the view: the underlying tf.Graph is not
affected.
Args:
new_input_indices: an iterable of integers representing a mapping between
the old inputs and the new ones. This mapping can be under-complete and
must be without repetitions.
new_output_indices: an iterable of integers representing a mapping between
the old outputs and the new ones. This mapping can be under-complete and
can have repetitions.
Returns:
A new modified instance of the original subgraph view with remapped
inputs and outputs.
"""
res = copy.copy(self)
if new_input_indices is not None:
res._remap_inputs(new_input_indices) # pylint: disable=protected-access
if new_output_indices is not None:
res._remap_outputs(new_output_indices) # pylint: disable=protected-access
return res | [
"def",
"remap",
"(",
"self",
",",
"new_input_indices",
"=",
"None",
",",
"new_output_indices",
"=",
"None",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"if",
"new_input_indices",
"is",
"not",
"None",
":",
"res",
".",
"_remap_inputs",
"("... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/graph_editor/subgraph.py#L373-L395 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/cuda/__init__.py | python | memory_usage | (device: Optional[Union[Device, int]] = None) | return pynvml.nvmlDeviceGetUtilizationRates(handle).memory | r"""Returns the percent of time over the past sample period during which global (device)
memory was being read or written. as given by `nvidia-smi`.
Args:
device (torch.device or int, optional): selected device. Returns
statistic for the current device, given by :func:`~torch.cuda.current_device`,
if :attr:`device` is ``None`` (default).
Warning: Each sample period may be between 1 second and 1/6 second,
depending on the product being queried. | r"""Returns the percent of time over the past sample period during which global (device)
memory was being read or written. as given by `nvidia-smi`. | [
"r",
"Returns",
"the",
"percent",
"of",
"time",
"over",
"the",
"past",
"sample",
"period",
"during",
"which",
"global",
"(",
"device",
")",
"memory",
"was",
"being",
"read",
"or",
"written",
".",
"as",
"given",
"by",
"nvidia",
"-",
"smi",
"."
] | def memory_usage(device: Optional[Union[Device, int]] = None) -> int:
r"""Returns the percent of time over the past sample period during which global (device)
memory was being read or written. as given by `nvidia-smi`.
Args:
device (torch.device or int, optional): selected device. Returns
statistic for the current device, given by :func:`~torch.cuda.current_device`,
if :attr:`device` is ``None`` (default).
Warning: Each sample period may be between 1 second and 1/6 second,
depending on the product being queried.
"""
try:
import pynvml # type: ignore[import]
except ModuleNotFoundError:
raise ModuleNotFoundError("pynvml module not found, please install pynvml")
from pynvml import NVMLError_DriverNotLoaded
try:
pynvml.nvmlInit()
except NVMLError_DriverNotLoaded:
raise RuntimeError("cuda driver can't be loaded, is cuda enabled?")
device = _get_device_index(device, optional=True)
handle = pynvml.nvmlDeviceGetHandleByIndex(device)
return pynvml.nvmlDeviceGetUtilizationRates(handle).memory | [
"def",
"memory_usage",
"(",
"device",
":",
"Optional",
"[",
"Union",
"[",
"Device",
",",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"int",
":",
"try",
":",
"import",
"pynvml",
"# type: ignore[import]",
"except",
"ModuleNotFoundError",
":",
"raise",
"ModuleNotF... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/cuda/__init__.py#L576-L599 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/feature_column/feature_column.py | python | _CategoricalColumn._num_buckets | (self) | Returns number of buckets in this sparse feature. | Returns number of buckets in this sparse feature. | [
"Returns",
"number",
"of",
"buckets",
"in",
"this",
"sparse",
"feature",
"."
] | def _num_buckets(self):
"""Returns number of buckets in this sparse feature."""
pass | [
"def",
"_num_buckets",
"(",
"self",
")",
":",
"pass"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/feature_column/feature_column.py#L1435-L1437 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/command/config.py | python | config.try_compile | (self, body, headers=None, include_dirs=None, lang="c") | return ok | Try to compile a source file built from 'body' and 'headers'.
Return true on success, false otherwise. | Try to compile a source file built from 'body' and 'headers'.
Return true on success, false otherwise. | [
"Try",
"to",
"compile",
"a",
"source",
"file",
"built",
"from",
"body",
"and",
"headers",
".",
"Return",
"true",
"on",
"success",
"false",
"otherwise",
"."
] | def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
"""Try to compile a source file built from 'body' and 'headers'.
Return true on success, false otherwise.
"""
from distutils.ccompiler import CompileError
self._check_compiler()
try:
self._compile(body, headers, include_dirs, lang)
ok = 1
except CompileError:
ok = 0
log.info(ok and "success!" or "failure.")
self._clean()
return ok | [
"def",
"try_compile",
"(",
"self",
",",
"body",
",",
"headers",
"=",
"None",
",",
"include_dirs",
"=",
"None",
",",
"lang",
"=",
"\"c\"",
")",
":",
"from",
"distutils",
".",
"ccompiler",
"import",
"CompileError",
"self",
".",
"_check_compiler",
"(",
")",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/command/config.py#L225-L239 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | GraphicsRenderer_GetCairoRenderer | (*args) | return _gdi_.GraphicsRenderer_GetCairoRenderer(*args) | GraphicsRenderer_GetCairoRenderer() -> GraphicsRenderer | GraphicsRenderer_GetCairoRenderer() -> GraphicsRenderer | [
"GraphicsRenderer_GetCairoRenderer",
"()",
"-",
">",
"GraphicsRenderer"
] | def GraphicsRenderer_GetCairoRenderer(*args):
"""GraphicsRenderer_GetCairoRenderer() -> GraphicsRenderer"""
return _gdi_.GraphicsRenderer_GetCairoRenderer(*args) | [
"def",
"GraphicsRenderer_GetCairoRenderer",
"(",
"*",
"args",
")",
":",
"return",
"_gdi_",
".",
"GraphicsRenderer_GetCairoRenderer",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L6671-L6673 | |
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/ar.py | python | generate | (env) | Add Builders and construction variables for ar to an Environment. | Add Builders and construction variables for ar to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"ar",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for ar to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
env['AR'] = 'ar'
env['ARFLAGS'] = SCons.Util.CLVar('rc')
env['ARCOM'] = '$AR $ARFLAGS $TARGET $SOURCES'
env['LIBPREFIX'] = 'lib'
env['LIBSUFFIX'] = '.a'
if env.get('RANLIB',env.Detect('ranlib')) :
env['RANLIB'] = env.get('RANLIB','ranlib')
env['RANLIBFLAGS'] = SCons.Util.CLVar('')
env['RANLIBCOM'] = '$RANLIB $RANLIBFLAGS $TARGET' | [
"def",
"generate",
"(",
"env",
")",
":",
"SCons",
".",
"Tool",
".",
"createStaticLibBuilder",
"(",
"env",
")",
"env",
"[",
"'AR'",
"]",
"=",
"'ar'",
"env",
"[",
"'ARFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'rc'",
")",
"env",
"["... | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/ar.py#L41-L54 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py | python | collapse_addresses | (addresses) | return _collapse_addresses_internal(addrs + nets) | Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects. | Collapse a list of IP objects. | [
"Collapse",
"a",
"list",
"of",
"IP",
"objects",
"."
] | def collapse_addresses(addresses):
"""Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects.
"""
addrs = []
ips = []
nets = []
# split IP addresses and networks
for ip in addresses:
if isinstance(ip, _BaseAddress):
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
ips.append(ip)
elif ip._prefixlen == ip._max_prefixlen:
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
try:
ips.append(ip.ip)
except AttributeError:
ips.append(ip.network_address)
else:
if nets and nets[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, nets[-1]))
nets.append(ip)
# sort and dedup
ips = sorted(set(ips))
# find consecutive address ranges in the sorted sequence and summarize them
if ips:
for first, last in _find_address_range(ips):
addrs.extend(summarize_address_range(first, last))
return _collapse_addresses_internal(addrs + nets) | [
"def",
"collapse_addresses",
"(",
"addresses",
")",
":",
"addrs",
"=",
"[",
"]",
"ips",
"=",
"[",
"]",
"nets",
"=",
"[",
"]",
"# split IP addresses and networks",
"for",
"ip",
"in",
"addresses",
":",
"if",
"isinstance",
"(",
"ip",
",",
"_BaseAddress",
")",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L426-L477 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py | python | Message.add_header | (self, _name, _value, **_params) | Extended header setting.
name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added. If a
parameter value contains non-ASCII characters it can be specified as a
three-tuple of (charset, language, value), in which case it will be
encoded according to RFC2231 rules. Otherwise it will be encoded using
the utf-8 charset and a language of ''.
Examples:
msg.add_header('content-disposition', 'attachment', filename='bud.gif')
msg.add_header('content-disposition', 'attachment',
filename=('utf-8', '', Fußballer.ppt'))
msg.add_header('content-disposition', 'attachment',
filename='Fußballer.ppt')) | Extended header setting. | [
"Extended",
"header",
"setting",
"."
] | def add_header(self, _name, _value, **_params):
"""Extended header setting.
name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added. If a
parameter value contains non-ASCII characters it can be specified as a
three-tuple of (charset, language, value), in which case it will be
encoded according to RFC2231 rules. Otherwise it will be encoded using
the utf-8 charset and a language of ''.
Examples:
msg.add_header('content-disposition', 'attachment', filename='bud.gif')
msg.add_header('content-disposition', 'attachment',
filename=('utf-8', '', Fußballer.ppt'))
msg.add_header('content-disposition', 'attachment',
filename='Fußballer.ppt'))
"""
parts = []
for k, v in _params.items():
if v is None:
parts.append(k.replace('_', '-'))
else:
parts.append(_formatparam(k.replace('_', '-'), v))
if _value is not None:
parts.insert(0, _value)
self[_name] = SEMISPACE.join(parts) | [
"def",
"add_header",
"(",
"self",
",",
"_name",
",",
"_value",
",",
"*",
"*",
"_params",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"_params",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"parts",
".",
"append",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py#L515-L543 | ||
FeatherCoin/Feathercoin | 8dad11707024149029bb9bfdd7bc5e10385e0e77 | contrib/devtools/copyright_header.py | python | call_git_toplevel | () | return subprocess.check_output(GIT_TOPLEVEL_CMD).strip().decode("utf-8") | Returns the absolute path to the project root | Returns the absolute path to the project root | [
"Returns",
"the",
"absolute",
"path",
"to",
"the",
"project",
"root"
] | def call_git_toplevel():
"Returns the absolute path to the project root"
return subprocess.check_output(GIT_TOPLEVEL_CMD).strip().decode("utf-8") | [
"def",
"call_git_toplevel",
"(",
")",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"GIT_TOPLEVEL_CMD",
")",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")"
] | https://github.com/FeatherCoin/Feathercoin/blob/8dad11707024149029bb9bfdd7bc5e10385e0e77/contrib/devtools/copyright_header.py#L58-L60 | |
fasiondog/hikyuu | 842751aa25283f9fdafc6f560ea262f79e67a307 | hikyuu/draw/drawplot/bokeh_draw.py | python | kplot | (kdata, new=True, axes=None, colorup='r', colordown='g') | return gcf() | 绘制K线图
:param KData kdata: K线数据
:param bool new: 是否在新窗口中显示,只在没有指定axes时生效
:param axes: 指定的坐标轴
:param colorup: the color of the rectangle where close >= open
:param colordown: the color of the rectangle where close < open | 绘制K线图
:param KData kdata: K线数据
:param bool new: 是否在新窗口中显示,只在没有指定axes时生效
:param axes: 指定的坐标轴
:param colorup: the color of the rectangle where close >= open
:param colordown: the color of the rectangle where close < open | [
"绘制K线图",
":",
"param",
"KData",
"kdata",
":",
"K线数据",
":",
"param",
"bool",
"new",
":",
"是否在新窗口中显示,只在没有指定axes时生效",
":",
"param",
"axes",
":",
"指定的坐标轴",
":",
"param",
"colorup",
":",
"the",
"color",
"of",
"the",
"rectangle",
"where",
"close",
">",
"=",
"o... | def kplot(kdata, new=True, axes=None, colorup='r', colordown='g'):
"""绘制K线图
:param KData kdata: K线数据
:param bool new: 是否在新窗口中显示,只在没有指定axes时生效
:param axes: 指定的坐标轴
:param colorup: the color of the rectangle where close >= open
:param colordown: the color of the rectangle where close < open
"""
if not kdata:
print("kdata is None")
return
if not axes:
axes = create_figure() if new or gca() is None else gca()
k = kdata
inc_k = [r for r in k if r.close > r.open]
dec_k = [r for r in k if r.close <= r.open]
inc_source = ColumnDataSource(dict(datetime=[r.datetime.datetime() for r in inc_k],
open=[r.open for r in inc_k],
high=[r.high for r in inc_k],
low=[r.low for r in inc_k],
close=[r.close for r in inc_k],
amount=[r.amount for r in inc_k],
volume=[r.volume for r in inc_k]))
dec_source = ColumnDataSource(dict(datetime=[r.datetime.datetime() for r in dec_k],
open=[r.open for r in dec_k],
high=[r.high for r in dec_k],
low=[r.low for r in dec_k],
close=[r.close for r in dec_k],
amount=[r.amount for r in dec_k],
volume=[r.volume for r in dec_k]))
w = 12*60*60*1000
colorup = trans_color(colorup)
colordown = trans_color(colordown)
axes.segment(x0='datetime', y0='high', x1='datetime', y1='low', color=colorup, source=inc_source)
axes.segment(x0='datetime', y0='high', x1='datetime', y1='low', color=colordown, source=dec_source)
axes.vbar(x='datetime', width=w, top='close', bottom='open', fill_color="white",
line_color=colorup, source=inc_source)
axes.vbar(x='datetime', width=w, top='open', bottom='close', fill_color="green",
line_color=colordown, source=dec_source)
axes.add_tools(HoverTool(tooltips=[("index", "$index"), ('日期', get_date_format(k)),
("开盘价", "@open{0.0000}"), ("最高价", "@high{0.0000}"),
("最低价", "@low{0.0000}"),("收盘价", "@close{0.0000}"),
("成交金额", "@amount{0.0000}"), ("成交量", "@volume{0.0000}")],
formatters = { "datetime": "datetime"}))
axes.xaxis[0].formatter = DatetimeTickFormatter()
axes.title.text = k.get_stock().name
axes.title.align = "center"
axes.title.text_font_size = "16px"
last_record = kdata[-1]
color = colorup if last_record.close > kdata[-2].close else colordown
text = u'%s 开:%.2f 高:%.2f 低:%.2f 收:%.2f 涨幅:%.2f%%' % (
last_record.datetime, last_record.open, last_record.high, last_record.low,
last_record.close, 100 * (last_record.close - kdata[-2].close) / kdata[-2].close
)
label = Label(
x=axes.plot_width * 0.01,
y=axes.plot_height * 0.82,
x_units='screen', y_units='screen',
text=text,
render_mode='css',
text_font_size='14px',
text_color=color,
background_fill_color='white',
background_fill_alpha=0.5
)
axes.add_layout(label)
return gcf() | [
"def",
"kplot",
"(",
"kdata",
",",
"new",
"=",
"True",
",",
"axes",
"=",
"None",
",",
"colorup",
"=",
"'r'",
",",
"colordown",
"=",
"'g'",
")",
":",
"if",
"not",
"kdata",
":",
"print",
"(",
"\"kdata is None\"",
")",
"return",
"if",
"not",
"axes",
"... | https://github.com/fasiondog/hikyuu/blob/842751aa25283f9fdafc6f560ea262f79e67a307/hikyuu/draw/drawplot/bokeh_draw.py#L134-L209 | |
facebookresearch/habitat-sim | 63b6c71d9ca8adaefb140b198196f5d0ca1f1e34 | examples/viewer.py | python | HabitatSimInteractiveViewer.mouse_press_event | (self, event: Application.MouseEvent) | Handles `Application.MouseEvent`. When in GRAB mode, click on
objects to drag their position. (right-click for fixed constraints) | Handles `Application.MouseEvent`. When in GRAB mode, click on
objects to drag their position. (right-click for fixed constraints) | [
"Handles",
"Application",
".",
"MouseEvent",
".",
"When",
"in",
"GRAB",
"mode",
"click",
"on",
"objects",
"to",
"drag",
"their",
"position",
".",
"(",
"right",
"-",
"click",
"for",
"fixed",
"constraints",
")"
] | def mouse_press_event(self, event: Application.MouseEvent) -> None:
"""
Handles `Application.MouseEvent`. When in GRAB mode, click on
objects to drag their position. (right-click for fixed constraints)
"""
button = Application.MouseEvent.Button
physics_enabled = self.sim.get_physics_simulation_library()
# if interactive mode is True -> GRAB MODE
if self.mouse_interaction == MouseMode.GRAB and physics_enabled:
render_camera = self.render_camera.render_camera
ray = render_camera.unproject(self.get_mouse_position(event.position))
raycast_results = self.sim.cast_ray(ray=ray)
if raycast_results.has_hits():
hit_object, ao_link = -1, -1
hit_info = raycast_results.hits[0]
if hit_info.object_id >= 0:
# we hit an non-staged collision object
ro_mngr = self.sim.get_rigid_object_manager()
ao_mngr = self.sim.get_articulated_object_manager()
ao = ao_mngr.get_object_by_id(hit_info.object_id)
ro = ro_mngr.get_object_by_id(hit_info.object_id)
if ro:
# if grabbed an object
hit_object = hit_info.object_id
object_pivot = ro.transformation.inverted().transform_point(
hit_info.point
)
object_frame = ro.rotation.inverted()
elif ao:
# if grabbed the base link
hit_object = hit_info.object_id
object_pivot = ao.transformation.inverted().transform_point(
hit_info.point
)
object_frame = ao.rotation.inverted()
else:
for ao_handle in ao_mngr.get_objects_by_handle_substring():
ao = ao_mngr.get_object_by_handle(ao_handle)
link_to_obj_ids = ao.link_object_ids
if hit_info.object_id in link_to_obj_ids:
# if we got a link
ao_link = link_to_obj_ids[hit_info.object_id]
object_pivot = (
ao.get_link_scene_node(ao_link)
.transformation.inverted()
.transform_point(hit_info.point)
)
object_frame = ao.get_link_scene_node(
ao_link
).rotation.inverted()
hit_object = ao.object_id
break
# done checking for AO
if hit_object >= 0:
node = self.agent_body_node
constraint_settings = physics.RigidConstraintSettings()
constraint_settings.object_id_a = hit_object
constraint_settings.link_id_a = ao_link
constraint_settings.pivot_a = object_pivot
constraint_settings.frame_a = (
object_frame.to_matrix() @ node.rotation.to_matrix()
)
constraint_settings.frame_b = node.rotation.to_matrix()
constraint_settings.pivot_b = hit_info.point
# by default use a point 2 point constraint
if event.button == button.RIGHT:
constraint_settings.constraint_type = (
physics.RigidConstraintType.Fixed
)
grip_depth = (
hit_info.point - render_camera.node.absolute_translation
).length()
self.mouse_grabber = MouseGrabber(
constraint_settings,
grip_depth,
self.sim,
)
else:
logger.warn("Oops, couldn't find the hit object. That's odd.")
# end if didn't hit the scene
# end has raycast hit
# end has physics enabled
self.previous_mouse_point = self.get_mouse_position(event.position)
self.redraw()
event.accepted = True | [
"def",
"mouse_press_event",
"(",
"self",
",",
"event",
":",
"Application",
".",
"MouseEvent",
")",
"->",
"None",
":",
"button",
"=",
"Application",
".",
"MouseEvent",
".",
"Button",
"physics_enabled",
"=",
"self",
".",
"sim",
".",
"get_physics_simulation_library... | https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/examples/viewer.py#L431-L526 | ||
lmb-freiburg/flownet2 | b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc | scripts/cpp_lint.py | python | CloseExpression | (clean_lines, linenum, pos) | return (line, clean_lines.NumLines(), -1) | If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum. | If input points to ( or { or [ or <, finds the position that closes it. | [
"If",
"input",
"points",
"to",
"(",
"or",
"{",
"or",
"[",
"or",
"<",
"finds",
"the",
"position",
"that",
"closes",
"it",
"."
] | def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
startchar = line[pos]
if startchar not in '({[<':
return (line, clean_lines.NumLines(), -1)
if startchar == '(': endchar = ')'
if startchar == '[': endchar = ']'
if startchar == '{': endchar = '}'
if startchar == '<': endchar = '>'
# Check first line
(end_pos, num_open) = FindEndOfExpressionInLine(
line, pos, 0, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, num_open) = FindEndOfExpressionInLine(
line, 0, num_open, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find endchar before end of file, give up
return (line, clean_lines.NumLines(), -1) | [
"def",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"startchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"startchar",
"not",
"in",
"'({[<'",
":",
"return",
"(",
... | https://github.com/lmb-freiburg/flownet2/blob/b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc/scripts/cpp_lint.py#L1254-L1297 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xmlNode.isRef | (self, doc, attr) | return ret | Determine whether an attribute is of type Ref. In case we
have DTD(s) then this is simple, otherwise we use an
heuristic: name Ref (upper or lowercase). | Determine whether an attribute is of type Ref. In case we
have DTD(s) then this is simple, otherwise we use an
heuristic: name Ref (upper or lowercase). | [
"Determine",
"whether",
"an",
"attribute",
"is",
"of",
"type",
"Ref",
".",
"In",
"case",
"we",
"have",
"DTD",
"(",
"s",
")",
"then",
"this",
"is",
"simple",
"otherwise",
"we",
"use",
"an",
"heuristic",
":",
"name",
"Ref",
"(",
"upper",
"or",
"lowercase... | def isRef(self, doc, attr):
"""Determine whether an attribute is of type Ref. In case we
have DTD(s) then this is simple, otherwise we use an
heuristic: name Ref (upper or lowercase). """
if doc is None: doc__o = None
else: doc__o = doc._o
if attr is None: attr__o = None
else: attr__o = attr._o
ret = libxml2mod.xmlIsRef(doc__o, self._o, attr__o)
return ret | [
"def",
"isRef",
"(",
"self",
",",
"doc",
",",
"attr",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"if",
"attr",
"is",
"None",
":",
"attr__o",
"=",
"None",
"else",
":",
"attr__o",
... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L2868-L2877 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-fft/python/fft/logpwrfft.py | python | _logpwrfft_base.set_avg_alpha | (self, avg_alpha) | Set the average alpha and set the taps if average was on.
Args:
avg_alpha: the new iir filter tap | Set the average alpha and set the taps if average was on. | [
"Set",
"the",
"average",
"alpha",
"and",
"set",
"the",
"taps",
"if",
"average",
"was",
"on",
"."
] | def set_avg_alpha(self, avg_alpha):
"""
Set the average alpha and set the taps if average was on.
Args:
avg_alpha: the new iir filter tap
"""
self._avg_alpha = avg_alpha
self.set_average(self._average) | [
"def",
"set_avg_alpha",
"(",
"self",
",",
"avg_alpha",
")",
":",
"self",
".",
"_avg_alpha",
"=",
"avg_alpha",
"self",
".",
"set_average",
"(",
"self",
".",
"_average",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-fft/python/fft/logpwrfft.py#L116-L124 | ||
nnrg/opennero | 43e12a1bcba6e228639db3886fec1dc47ddc24cb | mods/TowerofHanoi/tree_viewer.py | python | TreeViewer.add_item_to_viewer | (self, item, viewer_index, hidden=False, completed=False) | adds an item to the item list, as long as it doesn't make the item list too long (this is a failsafe to prevent infinite loops from taking more and more memory). This function also checks to see if the item is in the list already, and if so removes it and updates all index info accordingly | adds an item to the item list, as long as it doesn't make the item list too long (this is a failsafe to prevent infinite loops from taking more and more memory). This function also checks to see if the item is in the list already, and if so removes it and updates all index info accordingly | [
"adds",
"an",
"item",
"to",
"the",
"item",
"list",
"as",
"long",
"as",
"it",
"doesn",
"t",
"make",
"the",
"item",
"list",
"too",
"long",
"(",
"this",
"is",
"a",
"failsafe",
"to",
"prevent",
"infinite",
"loops",
"from",
"taking",
"more",
"and",
"more",
... | def add_item_to_viewer(self, item, viewer_index, hidden=False, completed=False):
"""adds an item to the item list, as long as it doesn't make the item list too long (this is a failsafe to prevent infinite loops from taking more and more memory). This function also checks to see if the item is in the list already, and if so removes it and updates all index info accordingly"""
if (viewer_index < self.MAX_ITEM_VIEWERS):
self.item_viewers[viewer_index].addItem(item, hidden, completed) | [
"def",
"add_item_to_viewer",
"(",
"self",
",",
"item",
",",
"viewer_index",
",",
"hidden",
"=",
"False",
",",
"completed",
"=",
"False",
")",
":",
"if",
"(",
"viewer_index",
"<",
"self",
".",
"MAX_ITEM_VIEWERS",
")",
":",
"self",
".",
"item_viewers",
"[",
... | https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/TowerofHanoi/tree_viewer.py#L252-L255 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/special/basic.py | python | mathieu_odd_coef | (m, q) | return fc[:km] | r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
The Fourier series of the odd solutions of the Mathieu differential
equation are of the form
.. math:: \mathrm{se}_{2n+1}(z, q) = \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
.. math:: \mathrm{se}_{2n+2}(z, q) = \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
input m=2n+1.
Parameters
----------
m : int
Order of Mathieu functions. Must be non-negative.
q : float (>=0)
Parameter of Mathieu functions. Must be non-negative.
Returns
-------
Bk : ndarray
Even or odd Fourier coefficients, corresponding to even or odd m.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html | r"""Fourier coefficients for even Mathieu and modified Mathieu functions. | [
"r",
"Fourier",
"coefficients",
"for",
"even",
"Mathieu",
"and",
"modified",
"Mathieu",
"functions",
"."
] | def mathieu_odd_coef(m, q):
r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
The Fourier series of the odd solutions of the Mathieu differential
equation are of the form
.. math:: \mathrm{se}_{2n+1}(z, q) = \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
.. math:: \mathrm{se}_{2n+2}(z, q) = \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
input m=2n+1.
Parameters
----------
m : int
Order of Mathieu functions. Must be non-negative.
q : float (>=0)
Parameter of Mathieu functions. Must be non-negative.
Returns
-------
Bk : ndarray
Even or odd Fourier coefficients, corresponding to even or odd m.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(m) and isscalar(q)):
raise ValueError("m and q must be scalars.")
if (q < 0):
raise ValueError("q >=0")
if (m != floor(m)) or (m <= 0):
raise ValueError("m must be an integer > 0")
if (q <= 1):
qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
else:
qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
km = int(qm + 0.5*m)
if km > 251:
print("Warning, too many predicted coefficients.")
kd = 4
m = int(floor(m))
if m % 2:
kd = 3
b = mathieu_b(m, q)
fc = specfun.fcoef(kd, m, q, b)
return fc[:km] | [
"def",
"mathieu_odd_coef",
"(",
"m",
",",
"q",
")",
":",
"if",
"not",
"(",
"isscalar",
"(",
"m",
")",
"and",
"isscalar",
"(",
"q",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"m and q must be scalars.\"",
")",
"if",
"(",
"q",
"<",
"0",
")",
":",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/special/basic.py#L1281-L1335 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.get_bitfield_width | (self) | return conf.lib.clang_getFieldDeclBitWidth(self) | Retrieve the width of a bitfield. | Retrieve the width of a bitfield. | [
"Retrieve",
"the",
"width",
"of",
"a",
"bitfield",
"."
] | def get_bitfield_width(self):
"""
Retrieve the width of a bitfield.
"""
return conf.lib.clang_getFieldDeclBitWidth(self) | [
"def",
"get_bitfield_width",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getFieldDeclBitWidth",
"(",
"self",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L1857-L1861 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | cpp-package/scripts/lint.py | python | LintHelper.process_cpp | (self, path, suffix) | Process a cpp file. | Process a cpp file. | [
"Process",
"a",
"cpp",
"file",
"."
] | def process_cpp(self, path, suffix):
"""Process a cpp file."""
_cpplint_state.ResetErrorCounts()
cpplint.ProcessFile(str(path), _cpplint_state.verbose_level)
_cpplint_state.PrintErrorCounts()
errors = _cpplint_state.errors_by_category.copy()
if suffix == 'h':
self.cpp_header_map[str(path)] = errors
else:
self.cpp_src_map[str(path)] = errors | [
"def",
"process_cpp",
"(",
"self",
",",
"path",
",",
"suffix",
")",
":",
"_cpplint_state",
".",
"ResetErrorCounts",
"(",
")",
"cpplint",
".",
"ProcessFile",
"(",
"str",
"(",
"path",
")",
",",
"_cpplint_state",
".",
"verbose_level",
")",
"_cpplint_state",
"."... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/cpp-package/scripts/lint.py#L78-L88 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/dynamodb/conditions.py | python | AttributeBase.gt | (self, value) | return GreaterThan(self, value) | Creates a condition where the attribute is greater than the value.
:param value: The value that the attribute is greater than. | Creates a condition where the attribute is greater than the value. | [
"Creates",
"a",
"condition",
"where",
"the",
"attribute",
"is",
"greater",
"than",
"the",
"value",
"."
] | def gt(self, value):
"""Creates a condition where the attribute is greater than the value.
:param value: The value that the attribute is greater than.
"""
return GreaterThan(self, value) | [
"def",
"gt",
"(",
"self",
",",
"value",
")",
":",
"return",
"GreaterThan",
"(",
"self",
",",
"value",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/dynamodb/conditions.py#L96-L101 | |
RobotLocomotion/drake | 0e18a34604c45ed65bc9018a54f7610f91cdad5b | tools/workspace/drake_visualizer/_drake_visualizer_builtin_scripts/show_hydroelastic_contact.py | python | HydroelasticContactVisualizer.set_max_pressure | (self) | Slot for dialog widget | Slot for dialog widget | [
"Slot",
"for",
"dialog",
"widget"
] | def set_max_pressure(self):
"""Slot for dialog widget"""
new_value = float(self.dlg.max_pressure.text)
if new_value != self.max_pressure:
self.max_pressure = new_value
self.update_pressure_range()
self.update_visual_data_from_message() | [
"def",
"set_max_pressure",
"(",
"self",
")",
":",
"new_value",
"=",
"float",
"(",
"self",
".",
"dlg",
".",
"max_pressure",
".",
"text",
")",
"if",
"new_value",
"!=",
"self",
".",
"max_pressure",
":",
"self",
".",
"max_pressure",
"=",
"new_value",
"self",
... | https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/tools/workspace/drake_visualizer/_drake_visualizer_builtin_scripts/show_hydroelastic_contact.py#L1013-L1019 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/XRCed/component.py | python | _ComponentManager.preload | (self, res) | Preload external resources. | Preload external resources. | [
"Preload",
"external",
"resources",
"."
] | def preload(self, res):
'''Preload external resources.'''
for f in self.external:
TRACE('Loading external resources: %s', f)
res.Load(f) | [
"def",
"preload",
"(",
"self",
",",
"res",
")",
":",
"for",
"f",
"in",
"self",
".",
"external",
":",
"TRACE",
"(",
"'Loading external resources: %s'",
",",
"f",
")",
"res",
".",
"Load",
"(",
"f",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/XRCed/component.py#L775-L779 | ||
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/mox.py | python | MockAnything._Replay | (self) | Start replaying expected method calls. | Start replaying expected method calls. | [
"Start",
"replaying",
"expected",
"method",
"calls",
"."
] | def _Replay(self):
"""Start replaying expected method calls."""
self._replay_mode = True | [
"def",
"_Replay",
"(",
"self",
")",
":",
"self",
".",
"_replay_mode",
"=",
"True"
] | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/mox.py#L326-L329 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py | python | Block.astype | (self, dtype, copy: bool = False, errors: str = "raise") | return newb | Coerce to the new dtype.
Parameters
----------
dtype : str, dtype convertible
copy : bool, default False
copy if indicated
errors : str, {'raise', 'ignore'}, default 'ignore'
- ``raise`` : allow exceptions to be raised
- ``ignore`` : suppress exceptions. On error return original object
Returns
-------
Block | Coerce to the new dtype. | [
"Coerce",
"to",
"the",
"new",
"dtype",
"."
] | def astype(self, dtype, copy: bool = False, errors: str = "raise"):
"""
Coerce to the new dtype.
Parameters
----------
dtype : str, dtype convertible
copy : bool, default False
copy if indicated
errors : str, {'raise', 'ignore'}, default 'ignore'
- ``raise`` : allow exceptions to be raised
- ``ignore`` : suppress exceptions. On error return original object
Returns
-------
Block
"""
errors_legal_values = ("raise", "ignore")
if errors not in errors_legal_values:
invalid_arg = (
"Expected value of kwarg 'errors' to be one of "
f"{list(errors_legal_values)}. Supplied value is '{errors}'"
)
raise ValueError(invalid_arg)
if inspect.isclass(dtype) and issubclass(dtype, ExtensionDtype):
msg = (
f"Expected an instance of {dtype.__name__}, "
"but got the class instead. Try instantiating 'dtype'."
)
raise TypeError(msg)
# may need to convert to categorical
if self.is_categorical_astype(dtype):
if is_categorical_dtype(self.values):
# GH 10696/18593: update an existing categorical efficiently
return self.make_block(self.values.astype(dtype, copy=copy))
return self.make_block(Categorical(self.values, dtype=dtype))
dtype = pandas_dtype(dtype)
# astype processing
if is_dtype_equal(self.dtype, dtype):
if copy:
return self.copy()
return self
# force the copy here
if self.is_extension:
# TODO: Should we try/except this astype?
values = self.values.astype(dtype)
else:
if issubclass(dtype.type, str):
# use native type formatting for datetime/tz/timedelta
if self.is_datelike:
values = self.to_native_types()
# astype formatting
else:
values = self.get_values()
else:
values = self.get_values(dtype=dtype)
# _astype_nansafe works fine with 1-d only
vals1d = values.ravel()
try:
values = astype_nansafe(vals1d, dtype, copy=True)
except (ValueError, TypeError):
# e.g. astype_nansafe can fail on object-dtype of strings
# trying to convert to float
if errors == "raise":
raise
newb = self.copy() if copy else self
return newb
# TODO(extension)
# should we make this attribute?
if isinstance(values, np.ndarray):
values = values.reshape(self.shape)
newb = make_block(values, placement=self.mgr_locs, ndim=self.ndim)
if newb.is_numeric and self.is_numeric:
if newb.shape != self.shape:
raise TypeError(
f"cannot set astype for copy = [{copy}] for dtype "
f"({self.dtype.name} [{self.shape}]) to different shape "
f"({newb.dtype.name} [{newb.shape}])"
)
return newb | [
"def",
"astype",
"(",
"self",
",",
"dtype",
",",
"copy",
":",
"bool",
"=",
"False",
",",
"errors",
":",
"str",
"=",
"\"raise\"",
")",
":",
"errors_legal_values",
"=",
"(",
"\"raise\"",
",",
"\"ignore\"",
")",
"if",
"errors",
"not",
"in",
"errors_legal_va... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L554-L648 | |
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | MULAN_universal_lesion_analysis/maskrcnn/modeling/rpn/loss.py | python | RPNLossComputation.__call__ | (self, anchors, objectness, box_regression, targets) | return objectness_loss, box_loss | Arguments:
anchors (list[BoxList])
objectness (list[Tensor])
box_regression (list[Tensor])
targets (list[BoxList])
Returns:
objectness_loss (Tensor)
box_loss (Tensor | Arguments:
anchors (list[BoxList])
objectness (list[Tensor])
box_regression (list[Tensor])
targets (list[BoxList]) | [
"Arguments",
":",
"anchors",
"(",
"list",
"[",
"BoxList",
"]",
")",
"objectness",
"(",
"list",
"[",
"Tensor",
"]",
")",
"box_regression",
"(",
"list",
"[",
"Tensor",
"]",
")",
"targets",
"(",
"list",
"[",
"BoxList",
"]",
")"
] | def __call__(self, anchors, objectness, box_regression, targets):
"""
Arguments:
anchors (list[BoxList])
objectness (list[Tensor])
box_regression (list[Tensor])
targets (list[BoxList])
Returns:
objectness_loss (Tensor)
box_loss (Tensor
"""
anchors = [cat_boxlist(anchors_per_image) for anchors_per_image in anchors]
labels, regression_targets = self.prepare_targets(anchors, targets)
sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
sampled_pos_inds = torch.nonzero(torch.cat(sampled_pos_inds, dim=0)).squeeze(1)
sampled_neg_inds = torch.nonzero(torch.cat(sampled_neg_inds, dim=0)).squeeze(1)
cfg.debug_info.sampled_pos_inds = len(sampled_pos_inds)
sampled_inds = torch.cat([sampled_pos_inds, sampled_neg_inds], dim=0)
objectness_flattened = []
box_regression_flattened = []
# for each feature level, permute the outputs to make them be in the
# same format as the labels. Note that the labels are computed for
# all feature levels concatenated, so we keep the same representation
# for the objectness and the box_regression
for objectness_per_level, box_regression_per_level in zip(
objectness, box_regression
):
N, A, H, W = objectness_per_level.shape
objectness_per_level = objectness_per_level.permute(0, 2, 3, 1).reshape(
N, -1
)
box_regression_per_level = box_regression_per_level.view(N, -1, 4, H, W)
box_regression_per_level = box_regression_per_level.permute(0, 3, 4, 1, 2)
box_regression_per_level = box_regression_per_level.reshape(N, -1, 4)
objectness_flattened.append(objectness_per_level)
box_regression_flattened.append(box_regression_per_level)
# concatenate on the first dimension (representing the feature levels), to
# take into account the way the labels were generated (with all feature maps
# being concatenated as well)
objectness = cat(objectness_flattened, dim=1).reshape(-1)
box_regression = cat(box_regression_flattened, dim=1).reshape(-1, 4)
labels = torch.cat(labels, dim=0)
regression_targets = torch.cat(regression_targets, dim=0)
box_loss = smooth_l1_loss(
box_regression[sampled_pos_inds],
regression_targets[sampled_pos_inds],
beta=1.0 / 9,
size_average=False,
) / (sampled_inds.numel())
if not cfg.MODEL.RPN.FOCAL_LOSS:
objectness_loss = F.binary_cross_entropy_with_logits(
objectness[sampled_inds], labels[sampled_inds]
)
else:
alpha = cfg.MODEL.ROI_BOX_HEAD.FOCAL_ALPHA
gamma = cfg.MODEL.ROI_BOX_HEAD.FOCAL_GAMMA
p = objectness.sigmoid()
labels_float = labels.to(torch.float32)
pt = p * labels_float + (1 - p) * (1 - labels_float) # pt = p if t > 0 else 1-p
valid_mask = (labels >= 0).to(torch.float32)
w = valid_mask * (
alpha * labels_float + (1 - alpha) * (1 - labels_float)) # w = alpha if t > 0 else 1-alpha
objectness_loss = w * (1 - pt).pow(gamma) * pt.log()
objectness_loss = -objectness_loss.sum() / (labels_float * valid_mask).sum()
return objectness_loss, box_loss | [
"def",
"__call__",
"(",
"self",
",",
"anchors",
",",
"objectness",
",",
"box_regression",
",",
"targets",
")",
":",
"anchors",
"=",
"[",
"cat_boxlist",
"(",
"anchors_per_image",
")",
"for",
"anchors_per_image",
"in",
"anchors",
"]",
"labels",
",",
"regression_... | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/MULAN_universal_lesion_analysis/maskrcnn/modeling/rpn/loss.py#L85-L156 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/jax/deep_cfr.py | python | DeepCFRSolver._get_advantage_dataset | (self, player, nr_steps=1) | return iter(tfds.as_numpy(data)) | Returns the collected regrets for the given player as a dataset. | Returns the collected regrets for the given player as a dataset. | [
"Returns",
"the",
"collected",
"regrets",
"for",
"the",
"given",
"player",
"as",
"a",
"dataset",
"."
] | def _get_advantage_dataset(self, player, nr_steps=1):
"""Returns the collected regrets for the given player as a dataset."""
self._advantage_memories[player].shuffle_data()
data = tf.data.Dataset.from_tensor_slices(
self._advantage_memories[player].data)
data = data.repeat()
data = data.shuffle(ADVANTAGE_TRAIN_SHUFFLE_SIZE)
data = data.batch(self._batch_size_advantage)
data = data.map(self._deserialize_advantage_memory)
data = data.prefetch(tf.data.experimental.AUTOTUNE)
data = data.take(nr_steps)
return iter(tfds.as_numpy(data)) | [
"def",
"_get_advantage_dataset",
"(",
"self",
",",
"player",
",",
"nr_steps",
"=",
"1",
")",
":",
"self",
".",
"_advantage_memories",
"[",
"player",
"]",
".",
"shuffle_data",
"(",
")",
"data",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_tensor_slice... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/jax/deep_cfr.py#L498-L509 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/metrics/pairwise.py | python | _parallel_pairwise | (X, Y, func, n_jobs, **kwds) | return np.hstack(ret) | Break the pairwise matrix in n_jobs even slices
and compute them in parallel | Break the pairwise matrix in n_jobs even slices
and compute them in parallel | [
"Break",
"the",
"pairwise",
"matrix",
"in",
"n_jobs",
"even",
"slices",
"and",
"compute",
"them",
"in",
"parallel"
] | def _parallel_pairwise(X, Y, func, n_jobs, **kwds):
"""Break the pairwise matrix in n_jobs even slices
and compute them in parallel"""
if n_jobs < 0:
n_jobs = max(cpu_count() + 1 + n_jobs, 1)
if Y is None:
Y = X
if n_jobs == 1:
# Special case to avoid picklability checks in delayed
return func(X, Y, **kwds)
# TODO: in some cases, backend='threading' may be appropriate
fd = delayed(func)
ret = Parallel(n_jobs=n_jobs, verbose=0)(
fd(X, Y[s], **kwds)
for s in gen_even_slices(Y.shape[0], n_jobs))
return np.hstack(ret) | [
"def",
"_parallel_pairwise",
"(",
"X",
",",
"Y",
",",
"func",
",",
"n_jobs",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"n_jobs",
"<",
"0",
":",
"n_jobs",
"=",
"max",
"(",
"cpu_count",
"(",
")",
"+",
"1",
"+",
"n_jobs",
",",
"1",
")",
"if",
"Y",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/metrics/pairwise.py#L1072-L1091 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/encoding.py | python | _ProcessUnknownEnums | (message, encoded_message) | return message | Add unknown enum values from encoded_message as unknown fields.
ProtoRPC diverges from the usual protocol buffer behavior here and
doesn't allow unknown fields. Throwing on unknown fields makes it
impossible to let servers add new enum values and stay compatible
with older clients, which isn't reasonable for us. We simply store
unrecognized enum values as unknown fields, and all is well.
Args:
message: Proto message we've decoded thus far.
encoded_message: JSON string we're decoding.
Returns:
message, with any unknown enums stored as unrecognized fields. | Add unknown enum values from encoded_message as unknown fields. | [
"Add",
"unknown",
"enum",
"values",
"from",
"encoded_message",
"as",
"unknown",
"fields",
"."
] | def _ProcessUnknownEnums(message, encoded_message):
"""Add unknown enum values from encoded_message as unknown fields.
ProtoRPC diverges from the usual protocol buffer behavior here and
doesn't allow unknown fields. Throwing on unknown fields makes it
impossible to let servers add new enum values and stay compatible
with older clients, which isn't reasonable for us. We simply store
unrecognized enum values as unknown fields, and all is well.
Args:
message: Proto message we've decoded thus far.
encoded_message: JSON string we're decoding.
Returns:
message, with any unknown enums stored as unrecognized fields.
"""
if not encoded_message:
return message
decoded_message = json.loads(encoded_message)
for field in message.all_fields():
if (isinstance(field, messages.EnumField) and
field.name in decoded_message and
message.get_assigned_value(field.name) is None):
message.set_unrecognized_field(
field.name, decoded_message[field.name], messages.Variant.ENUM)
return message | [
"def",
"_ProcessUnknownEnums",
"(",
"message",
",",
"encoded_message",
")",
":",
"if",
"not",
"encoded_message",
":",
"return",
"message",
"decoded_message",
"=",
"json",
".",
"loads",
"(",
"encoded_message",
")",
"for",
"field",
"in",
"message",
".",
"all_field... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/encoding.py#L464-L489 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/hang_analyzer.py | python | SolarisProcessList.dump_processes | (self, logger) | return p | Get list of [Pid, Process Name] | Get list of [Pid, Process Name] | [
"Get",
"list",
"of",
"[",
"Pid",
"Process",
"Name",
"]"
] | def dump_processes(self, logger):
"""Get list of [Pid, Process Name]"""
ps = self.__find_ps()
logger.info("Getting list of processes using %s" % ps)
ret = callo([ps, "-eo", "pid,args"], logger)
b = StringIO.StringIO(ret)
csvReader = csv.reader(b, delimiter=' ', quoting=csv.QUOTE_NONE, skipinitialspace=True)
p = [[int(row[0]), os.path.split(row[1])[1]] for row in csvReader if row[0] != "PID"]
return p | [
"def",
"dump_processes",
"(",
"self",
",",
"logger",
")",
":",
"ps",
"=",
"self",
".",
"__find_ps",
"(",
")",
"logger",
".",
"info",
"(",
"\"Getting list of processes using %s\"",
"%",
"ps",
")",
"ret",
"=",
"callo",
"(",
"[",
"ps",
",",
"\"-eo\"",
",",
... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/hang_analyzer.py#L428-L441 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ftplib.py | python | parse150 | (resp) | Parse the '150' response for a RETR request.
Returns the expected transfer size or None; size is not guaranteed to
be present in the 150 message. | Parse the '150' response for a RETR request.
Returns the expected transfer size or None; size is not guaranteed to
be present in the 150 message. | [
"Parse",
"the",
"150",
"response",
"for",
"a",
"RETR",
"request",
".",
"Returns",
"the",
"expected",
"transfer",
"size",
"or",
"None",
";",
"size",
"is",
"not",
"guaranteed",
"to",
"be",
"present",
"in",
"the",
"150",
"message",
"."
] | def parse150(resp):
'''Parse the '150' response for a RETR request.
Returns the expected transfer size or None; size is not guaranteed to
be present in the 150 message.
'''
if resp[:3] != '150':
raise error_reply, resp
global _150_re
if _150_re is None:
import re
_150_re = re.compile("150 .* \((\d+) bytes\)", re.IGNORECASE)
m = _150_re.match(resp)
if not m:
return None
s = m.group(1)
try:
return int(s)
except (OverflowError, ValueError):
return long(s) | [
"def",
"parse150",
"(",
"resp",
")",
":",
"if",
"resp",
"[",
":",
"3",
"]",
"!=",
"'150'",
":",
"raise",
"error_reply",
",",
"resp",
"global",
"_150_re",
"if",
"_150_re",
"is",
"None",
":",
"import",
"re",
"_150_re",
"=",
"re",
".",
"compile",
"(",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ftplib.py#L771-L789 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pubsub/core/topictreetraverser.py | python | ITopicTreeVisitor._onTopic | (self, topicObj) | Override this to define what to do for each node. | Override this to define what to do for each node. | [
"Override",
"this",
"to",
"define",
"what",
"to",
"do",
"for",
"each",
"node",
"."
] | def _onTopic(self, topicObj):
"""Override this to define what to do for each node."""
pass | [
"def",
"_onTopic",
"(",
"self",
",",
"topicObj",
")",
":",
"pass"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/topictreetraverser.py#L124-L126 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/muelu/research/q2q1/status.py | python | sort_nicely | (l) | return l | Sort the given list in the way that humans expect. | Sort the given list in the way that humans expect. | [
"Sort",
"the",
"given",
"list",
"in",
"the",
"way",
"that",
"humans",
"expect",
"."
] | def sort_nicely(l):
""" Sort the given list in the way that humans expect. """
convert = lambda s: int(s) if s.isdigit() else s
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] # turn a string into a list of string and number chunks ("z23a" -> ["z", 23, "a"])
l.sort(key=alphanum_key)
return l | [
"def",
"sort_nicely",
"(",
"l",
")",
":",
"convert",
"=",
"lambda",
"s",
":",
"int",
"(",
"s",
")",
"if",
"s",
".",
"isdigit",
"(",
")",
"else",
"s",
"alphanum_key",
"=",
"lambda",
"key",
":",
"[",
"convert",
"(",
"c",
")",
"for",
"c",
"in",
"r... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/muelu/research/q2q1/status.py#L10-L16 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/vision/py_transforms.py | python | Decode.__call__ | (self, img) | return util.decode(img) | Call method.
Args:
img (Bytes-like Object): Raw image data to be decoded.
Returns:
PIL Image, decoded PIL Image in RGB mode. | Call method. | [
"Call",
"method",
"."
] | def __call__(self, img):
"""
Call method.
Args:
img (Bytes-like Object): Raw image data to be decoded.
Returns:
PIL Image, decoded PIL Image in RGB mode.
"""
return util.decode(img) | [
"def",
"__call__",
"(",
"self",
",",
"img",
")",
":",
"return",
"util",
".",
"decode",
"(",
"img",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/vision/py_transforms.py#L250-L260 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/ftplib.py | python | FTP.delete | (self, filename) | Delete a file. | Delete a file. | [
"Delete",
"a",
"file",
"."
] | def delete(self, filename):
'''Delete a file.'''
resp = self.sendcmd('DELE ' + filename)
if resp[:3] in ('250', '200'):
return resp
else:
raise error_reply, resp | [
"def",
"delete",
"(",
"self",
",",
"filename",
")",
":",
"resp",
"=",
"self",
".",
"sendcmd",
"(",
"'DELE '",
"+",
"filename",
")",
"if",
"resp",
"[",
":",
"3",
"]",
"in",
"(",
"'250'",
",",
"'200'",
")",
":",
"return",
"resp",
"else",
":",
"rais... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/ftplib.py#L555-L561 | ||
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | src/blpapi/version.py | python | version | () | return __version__ | Returns:
str: BLPAPI Python module version | Returns:
str: BLPAPI Python module version | [
"Returns",
":",
"str",
":",
"BLPAPI",
"Python",
"module",
"version"
] | def version():
"""
Returns:
str: BLPAPI Python module version
"""
return __version__ | [
"def",
"version",
"(",
")",
":",
"return",
"__version__"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/version.py#L16-L21 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/training/saver.py | python | generate_checkpoint_state_proto | (save_dir,
model_checkpoint_path,
all_model_checkpoint_paths=None) | return coord_checkpoint_proto | Generates a checkpoint state proto.
Args:
save_dir: Directory where the model was saved.
model_checkpoint_path: The checkpoint file.
all_model_checkpoint_paths: List of strings. Paths to all not-yet-deleted
checkpoints, sorted from oldest to newest. If this is a non-empty list,
the last element must be equal to model_checkpoint_path. These paths
are also saved in the CheckpointState proto.
Returns:
CheckpointState proto with model_checkpoint_path and
all_model_checkpoint_paths updated to either absolute paths or
relative paths to the current save_dir. | Generates a checkpoint state proto. | [
"Generates",
"a",
"checkpoint",
"state",
"proto",
"."
] | def generate_checkpoint_state_proto(save_dir,
model_checkpoint_path,
all_model_checkpoint_paths=None):
"""Generates a checkpoint state proto.
Args:
save_dir: Directory where the model was saved.
model_checkpoint_path: The checkpoint file.
all_model_checkpoint_paths: List of strings. Paths to all not-yet-deleted
checkpoints, sorted from oldest to newest. If this is a non-empty list,
the last element must be equal to model_checkpoint_path. These paths
are also saved in the CheckpointState proto.
Returns:
CheckpointState proto with model_checkpoint_path and
all_model_checkpoint_paths updated to either absolute paths or
relative paths to the current save_dir.
"""
if all_model_checkpoint_paths is None:
all_model_checkpoint_paths = []
if (not all_model_checkpoint_paths or
all_model_checkpoint_paths[-1] != model_checkpoint_path):
logging.info("%s is not in all_model_checkpoint_paths. Manually adding it.",
model_checkpoint_path)
all_model_checkpoint_paths.append(model_checkpoint_path)
# Relative paths need to be rewritten to be relative to the "save_dir"
# if model_checkpoint_path already contains "save_dir".
if not os.path.isabs(save_dir):
if not os.path.isabs(model_checkpoint_path):
model_checkpoint_path = os.path.relpath(model_checkpoint_path, save_dir)
for i in range(len(all_model_checkpoint_paths)):
p = all_model_checkpoint_paths[i]
if not os.path.isabs(p):
all_model_checkpoint_paths[i] = os.path.relpath(p, save_dir)
coord_checkpoint_proto = CheckpointState(
model_checkpoint_path=model_checkpoint_path,
all_model_checkpoint_paths=all_model_checkpoint_paths)
return coord_checkpoint_proto | [
"def",
"generate_checkpoint_state_proto",
"(",
"save_dir",
",",
"model_checkpoint_path",
",",
"all_model_checkpoint_paths",
"=",
"None",
")",
":",
"if",
"all_model_checkpoint_paths",
"is",
"None",
":",
"all_model_checkpoint_paths",
"=",
"[",
"]",
"if",
"(",
"not",
"al... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/saver.py#L836-L877 | |
kit-cel/gr-radar | ceebb6d83280526f6e08a8aa0dde486db6898c81 | docs/doxygen/doxyxml/base.py | python | Base._get_dict_members | (self, cat=None) | return self._dict_members[cat] | For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None. | For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None. | [
"For",
"given",
"category",
"a",
"dictionary",
"is",
"returned",
"mapping",
"member",
"names",
"to",
"members",
"of",
"that",
"category",
".",
"For",
"names",
"that",
"are",
"duplicated",
"the",
"name",
"is",
"mapped",
"to",
"None",
"."
] | def _get_dict_members(self, cat=None):
"""
For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None.
"""
self.confirm_no_error()
if cat not in self._dict_members:
new_dict = {}
for mem in self.in_category(cat):
if mem.name() not in new_dict:
new_dict[mem.name()] = mem
else:
new_dict[mem.name()] = self.Duplicate
self._dict_members[cat] = new_dict
return self._dict_members[cat] | [
"def",
"_get_dict_members",
"(",
"self",
",",
"cat",
"=",
"None",
")",
":",
"self",
".",
"confirm_no_error",
"(",
")",
"if",
"cat",
"not",
"in",
"self",
".",
"_dict_members",
":",
"new_dict",
"=",
"{",
"}",
"for",
"mem",
"in",
"self",
".",
"in_category... | https://github.com/kit-cel/gr-radar/blob/ceebb6d83280526f6e08a8aa0dde486db6898c81/docs/doxygen/doxyxml/base.py#L125-L140 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/numpy/array_creations.py | python | meshgrid | (*xi, sparse=False, indexing='xy') | return res | Returns coordinate matrices from coordinate vectors.
Make `N-D` coordinate arrays for vectorized evaluations of `N-D`
scalar/vector fields over `N-D` grids, given one-dimensional
coordinate arrays `x1, x2,…, xn`.
Note:
Numpy argument copy is not supported, and a copy is always
returned.
Args:
*xi (Tensor): 1-D arrays representing the coordinates
of a grid.
indexing ('xy', 'ij', optional): Cartesian ('xy', default) or
matrix ('ij') indexing of output. In the 2-D case with
inputs of length `M` and `N`, the outputs are of shape `(N, M)`
for 'xy' indexing and `(M, N)` for 'ij' indexing. In the 3-D
case with inputs of length `M`, `N` and `P`, outputs are of shape
`(N, M, P)` for 'xy' indexing and `(M, N, P)` for 'ij' indexing.
sparse (bool, optional): If True a sparse grid is returned in
order to conserve memory. Default is False.
Returns:
Tuple of tensors, for vectors `x1, x2,…, xn` with lengths
``Ni=len(xi)``, return `(N1, N2, N3,...Nn)` shaped arrays if
``indexing='ij'`` or `(N2, N1, N3,...Nn)` shaped arrays if
``indexing='xy'`` with the elements of `xi` repeated to fill the matrix
along the first dimension for `x1`, the second for `x2` and so on.
Raises:
TypeError: If the input is not a tensor, or sparse is not boolean, or
indexing is not 'xy' or 'ij'.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> x = np.linspace(0, 1, 3)
>>> y = np.linspace(0, 1, 2)
>>> xv, yv = np.meshgrid(x, y)
>>> print(xv)
[[0. 0.5 1. ]
[0. 0.5 1. ]]
>>> print(yv)
[[0. 0. 0.]
[1. 1. 1.]]
>>> xv, yv = np.meshgrid(x, y, sparse=True)
>>> print(xv)
[[0. 0.5 1. ]]
>>> print(yv)
[[0.]
[1.]] | Returns coordinate matrices from coordinate vectors. | [
"Returns",
"coordinate",
"matrices",
"from",
"coordinate",
"vectors",
"."
] | def meshgrid(*xi, sparse=False, indexing='xy'):
"""
Returns coordinate matrices from coordinate vectors.
Make `N-D` coordinate arrays for vectorized evaluations of `N-D`
scalar/vector fields over `N-D` grids, given one-dimensional
coordinate arrays `x1, x2,…, xn`.
Note:
Numpy argument copy is not supported, and a copy is always
returned.
Args:
*xi (Tensor): 1-D arrays representing the coordinates
of a grid.
indexing ('xy', 'ij', optional): Cartesian ('xy', default) or
matrix ('ij') indexing of output. In the 2-D case with
inputs of length `M` and `N`, the outputs are of shape `(N, M)`
for 'xy' indexing and `(M, N)` for 'ij' indexing. In the 3-D
case with inputs of length `M`, `N` and `P`, outputs are of shape
`(N, M, P)` for 'xy' indexing and `(M, N, P)` for 'ij' indexing.
sparse (bool, optional): If True a sparse grid is returned in
order to conserve memory. Default is False.
Returns:
Tuple of tensors, for vectors `x1, x2,…, xn` with lengths
``Ni=len(xi)``, return `(N1, N2, N3,...Nn)` shaped arrays if
``indexing='ij'`` or `(N2, N1, N3,...Nn)` shaped arrays if
``indexing='xy'`` with the elements of `xi` repeated to fill the matrix
along the first dimension for `x1`, the second for `x2` and so on.
Raises:
TypeError: If the input is not a tensor, or sparse is not boolean, or
indexing is not 'xy' or 'ij'.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> x = np.linspace(0, 1, 3)
>>> y = np.linspace(0, 1, 2)
>>> xv, yv = np.meshgrid(x, y)
>>> print(xv)
[[0. 0.5 1. ]
[0. 0.5 1. ]]
>>> print(yv)
[[0. 0. 0.]
[1. 1. 1.]]
>>> xv, yv = np.meshgrid(x, y, sparse=True)
>>> print(xv)
[[0. 0.5 1. ]]
>>> print(yv)
[[0.]
[1.]]
"""
_check_input_tensor(*xi)
if not isinstance(sparse, bool):
_raise_type_error('argument sparse should be boolean')
if indexing not in ('xy', 'ij'):
_raise_type_error("Valid values for `indexing` are 'xy' and 'ij'.")
shape_out = ()
for x in xi:
shape_out += (x.size,)
if _is_shape_empty(shape_out):
return ones(shape_out)
grids = []
for x in xi:
if F.rank(x) == 1:
grids.append(x)
else:
grids.append(ravel(x))
ndim = len(grids)
cartesian = indexing == 'xy'
shape_out = ()
for i in range(len(grids)):
grid_index = _index(i, ndim, cartesian=cartesian)
shape_out += (F.shape(grids[grid_index])[0],)
res = []
for i, x in enumerate(grids):
grid_index = _index(i, ndim, cartesian=cartesian)
shape_expanded = _expanded_shape(ndim, shape_out[grid_index], grid_index)
x = x.reshape(shape_expanded)
if not sparse:
x = F.tile(x, _tile_size(shape_expanded, shape_out, ndim))
res.append(x)
return res | [
"def",
"meshgrid",
"(",
"*",
"xi",
",",
"sparse",
"=",
"False",
",",
"indexing",
"=",
"'xy'",
")",
":",
"_check_input_tensor",
"(",
"*",
"xi",
")",
"if",
"not",
"isinstance",
"(",
"sparse",
",",
"bool",
")",
":",
"_raise_type_error",
"(",
"'argument spar... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/array_creations.py#L1212-L1302 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/runtime.py | python | Context.get_all | (self) | return dict(self.parent, **self.vars) | Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it. | Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it. | [
"Return",
"the",
"complete",
"context",
"as",
"dict",
"including",
"the",
"exported",
"variables",
".",
"For",
"optimizations",
"reasons",
"this",
"might",
"not",
"return",
"an",
"actual",
"copy",
"so",
"be",
"careful",
"with",
"using",
"it",
"."
] | def get_all(self):
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
"""
if not self.vars:
return self.parent
if not self.parent:
return self.vars
return dict(self.parent, **self.vars) | [
"def",
"get_all",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"vars",
":",
"return",
"self",
".",
"parent",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"self",
".",
"vars",
"return",
"dict",
"(",
"self",
".",
"parent",
",",
"*",
"*",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/runtime.py#L223-L232 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/gradients_impl.py | python | _hessian_vector_product | (ys, xs, v) | return gradients(elemwise_products, xs) | Multiply the Hessian of `ys` wrt `xs` by `v`.
This is an efficient construction that uses a backprop-like approach
to compute the product between the Hessian and another vector. The
Hessian is usually too large to be explicitly computed or even
represented, but this method allows us to at least multiply by it
for the same big-O cost as backprop.
Implicit Hessian-vector products are the main practical, scalable way
of using second derivatives with neural networks. They allow us to
do things like construct Krylov subspaces and approximate conjugate
gradient descent.
Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y,
x, v)` will return an expression that evaluates to the same values
as (A + A.T) `v`.
Args:
ys: A scalar value, or a tensor or list of tensors to be summed to
yield a scalar.
xs: A list of tensors that we should construct the Hessian over.
v: A list of tensors, with the same shapes as xs, that we want to
multiply by the Hessian.
Returns:
A list of tensors (or if the list would be length 1, a single tensor)
containing the product between the Hessian and `v`.
Raises:
ValueError: `xs` and `v` have different length. | Multiply the Hessian of `ys` wrt `xs` by `v`. | [
"Multiply",
"the",
"Hessian",
"of",
"ys",
"wrt",
"xs",
"by",
"v",
"."
] | def _hessian_vector_product(ys, xs, v):
"""Multiply the Hessian of `ys` wrt `xs` by `v`.
This is an efficient construction that uses a backprop-like approach
to compute the product between the Hessian and another vector. The
Hessian is usually too large to be explicitly computed or even
represented, but this method allows us to at least multiply by it
for the same big-O cost as backprop.
Implicit Hessian-vector products are the main practical, scalable way
of using second derivatives with neural networks. They allow us to
do things like construct Krylov subspaces and approximate conjugate
gradient descent.
Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y,
x, v)` will return an expression that evaluates to the same values
as (A + A.T) `v`.
Args:
ys: A scalar value, or a tensor or list of tensors to be summed to
yield a scalar.
xs: A list of tensors that we should construct the Hessian over.
v: A list of tensors, with the same shapes as xs, that we want to
multiply by the Hessian.
Returns:
A list of tensors (or if the list would be length 1, a single tensor)
containing the product between the Hessian and `v`.
Raises:
ValueError: `xs` and `v` have different length.
"""
# Validate the input
length = len(xs)
if len(v) != length:
raise ValueError("xs and v must have the same length.")
# First backprop
grads = gradients(ys, xs)
assert len(grads) == length
elemwise_products = [
math_ops.multiply(grad_elem, array_ops.stop_gradient(v_elem))
for grad_elem, v_elem in zip(grads, v) if grad_elem is not None
]
# Second backprop
return gradients(elemwise_products, xs) | [
"def",
"_hessian_vector_product",
"(",
"ys",
",",
"xs",
",",
"v",
")",
":",
"# Validate the input",
"length",
"=",
"len",
"(",
"xs",
")",
"if",
"len",
"(",
"v",
")",
"!=",
"length",
":",
"raise",
"ValueError",
"(",
"\"xs and v must have the same length.\"",
... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/gradients_impl.py#L845-L894 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/dist.py | python | Distribution._clean_req | (self, req) | return req | Given a Requirement, remove environment markers and return it. | Given a Requirement, remove environment markers and return it. | [
"Given",
"a",
"Requirement",
"remove",
"environment",
"markers",
"and",
"return",
"it",
"."
] | def _clean_req(self, req):
"""
Given a Requirement, remove environment markers and return it.
"""
req.marker = None
return req | [
"def",
"_clean_req",
"(",
"self",
",",
"req",
")",
":",
"req",
".",
"marker",
"=",
"None",
"return",
"req"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/dist.py#L427-L432 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/frog-position-after-t-seconds.py | python | Solution4.frogPosition | (self, n, edges, t, target) | return dfs(G, target, t, 1, 0) | :type n: int
:type edges: List[List[int]]
:type t: int
:type target: int
:rtype: float | :type n: int
:type edges: List[List[int]]
:type t: int
:type target: int
:rtype: float | [
":",
"type",
"n",
":",
"int",
":",
"type",
"edges",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"type",
"t",
":",
"int",
":",
"type",
"target",
":",
"int",
":",
"rtype",
":",
"float"
] | def frogPosition(self, n, edges, t, target):
"""
:type n: int
:type edges: List[List[int]]
:type t: int
:type target: int
:rtype: float
"""
def dfs(G, target, t, node, parent):
if not t or not (len(G[node])-(parent != 0)):
return float(node == target)
for child in G[node]:
if child == parent:
continue
result = dfs(G, target, t-1, child, node)
if result:
break
return result/(len(G[node])-(parent != 0))
G = collections.defaultdict(list)
for u, v in edges:
G[u].append(v)
G[v].append(u)
return dfs(G, target, t, 1, 0) | [
"def",
"frogPosition",
"(",
"self",
",",
"n",
",",
"edges",
",",
"t",
",",
"target",
")",
":",
"def",
"dfs",
"(",
"G",
",",
"target",
",",
"t",
",",
"node",
",",
"parent",
")",
":",
"if",
"not",
"t",
"or",
"not",
"(",
"len",
"(",
"G",
"[",
... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/frog-position-after-t-seconds.py#L108-L131 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewListCtrl.AppendToggleColumn | (*args, **kwargs) | return _dataview.DataViewListCtrl_AppendToggleColumn(*args, **kwargs) | AppendToggleColumn(self, String label, int mode=DATAVIEW_CELL_ACTIVATABLE, int width=-1,
int align=ALIGN_LEFT, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn | AppendToggleColumn(self, String label, int mode=DATAVIEW_CELL_ACTIVATABLE, int width=-1,
int align=ALIGN_LEFT, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn | [
"AppendToggleColumn",
"(",
"self",
"String",
"label",
"int",
"mode",
"=",
"DATAVIEW_CELL_ACTIVATABLE",
"int",
"width",
"=",
"-",
"1",
"int",
"align",
"=",
"ALIGN_LEFT",
"int",
"flags",
"=",
"DATAVIEW_COL_RESIZABLE",
")",
"-",
">",
"DataViewColumn"
] | def AppendToggleColumn(*args, **kwargs):
"""
AppendToggleColumn(self, String label, int mode=DATAVIEW_CELL_ACTIVATABLE, int width=-1,
int align=ALIGN_LEFT, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
"""
return _dataview.DataViewListCtrl_AppendToggleColumn(*args, **kwargs) | [
"def",
"AppendToggleColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewListCtrl_AppendToggleColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L2136-L2141 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/ndarray/ndarray.py | python | NDArray.grad | (self) | return _ndarray_cls(hdl) | Returns gradient buffer attached to this NDArray. | Returns gradient buffer attached to this NDArray. | [
"Returns",
"gradient",
"buffer",
"attached",
"to",
"this",
"NDArray",
"."
] | def grad(self):
"""Returns gradient buffer attached to this NDArray."""
from . import _ndarray_cls
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetGrad(self.handle, ctypes.byref(hdl)))
if hdl.value is None:
return None
return _ndarray_cls(hdl) | [
"def",
"grad",
"(",
"self",
")",
":",
"from",
".",
"import",
"_ndarray_cls",
"hdl",
"=",
"NDArrayHandle",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXNDArrayGetGrad",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"hdl",
")",
")",
")",
... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/ndarray.py#L1958-L1965 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/cluster/k_means_.py | python | MiniBatchKMeans._labels_inertia_minibatch | (self, X) | return np.hstack(labels), np.sum(inertia) | Compute labels and inertia using mini batches.
This is slightly slower than doing everything at once but preventes
memory errors / segfaults.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data.
Returns
-------
labels : array, shap (n_samples,)
Cluster labels for each point.
inertia : float
Sum of squared distances of points to nearest cluster. | Compute labels and inertia using mini batches. | [
"Compute",
"labels",
"and",
"inertia",
"using",
"mini",
"batches",
"."
] | def _labels_inertia_minibatch(self, X):
"""Compute labels and inertia using mini batches.
This is slightly slower than doing everything at once but preventes
memory errors / segfaults.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data.
Returns
-------
labels : array, shap (n_samples,)
Cluster labels for each point.
inertia : float
Sum of squared distances of points to nearest cluster.
"""
if self.verbose:
print('Computing label assignment and total inertia')
x_squared_norms = row_norms(X, squared=True)
slices = gen_batches(X.shape[0], self.batch_size)
results = [_labels_inertia(X[s], x_squared_norms[s],
self.cluster_centers_) for s in slices]
labels, inertia = zip(*results)
return np.hstack(labels), np.sum(inertia) | [
"def",
"_labels_inertia_minibatch",
"(",
"self",
",",
"X",
")",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"'Computing label assignment and total inertia'",
")",
"x_squared_norms",
"=",
"row_norms",
"(",
"X",
",",
"squared",
"=",
"True",
")",
"slices"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/cluster/k_means_.py#L1441-L1467 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/graph_editor/transform.py | python | Transformer._transform_op | (self, op) | return op_ | Transform a tf.Operation.
Args:
op: the operation to be transformed.
Returns:
The transformed operation. | Transform a tf.Operation. | [
"Transform",
"a",
"tf",
".",
"Operation",
"."
] | def _transform_op(self, op):
"""Transform a tf.Operation.
Args:
op: the operation to be transformed.
Returns:
The transformed operation.
"""
if op in self._info.transformed_ops:
return self._info.transformed_ops[op]
op_ = self.transform_op_handler(self._info, op)
# Add to all the active control dependencies
self._info.graph_._record_op_seen_by_control_dependencies(op_) # pylint: disable=protected-access
# All to all the active devices
for device_function in reversed(self._info.graph_._device_function_stack): # pylint: disable=protected-access
op_._set_device(device_function(op_)) # pylint: disable=protected-access
# TODO(fkp): Establish clear policy about what context managers are allowed.
# assign to collection
if op is not op_:
self.assign_collections_handler(self._info, op, op_)
self._info.transformed_ops[op] = op_
return op_ | [
"def",
"_transform_op",
"(",
"self",
",",
"op",
")",
":",
"if",
"op",
"in",
"self",
".",
"_info",
".",
"transformed_ops",
":",
"return",
"self",
".",
"_info",
".",
"transformed_ops",
"[",
"op",
"]",
"op_",
"=",
"self",
".",
"transform_op_handler",
"(",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/transform.py#L338-L365 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_simulation.py | python | SimulationDomain.getCollidingVehiclesIDList | (self) | return self._getUniversal(tc.VAR_COLLIDING_VEHICLES_IDS) | getCollidingVehiclesIDList() -> list(string)
Return Ids of vehicles involved in a collision (typically 2 per
collision). | getCollidingVehiclesIDList() -> list(string)
Return Ids of vehicles involved in a collision (typically 2 per
collision). | [
"getCollidingVehiclesIDList",
"()",
"-",
">",
"list",
"(",
"string",
")",
"Return",
"Ids",
"of",
"vehicles",
"involved",
"in",
"a",
"collision",
"(",
"typically",
"2",
"per",
"collision",
")",
"."
] | def getCollidingVehiclesIDList(self):
"""getCollidingVehiclesIDList() -> list(string)
Return Ids of vehicles involved in a collision (typically 2 per
collision).
"""
return self._getUniversal(tc.VAR_COLLIDING_VEHICLES_IDS) | [
"def",
"getCollidingVehiclesIDList",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_COLLIDING_VEHICLES_IDS",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_simulation.py#L422-L427 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PGProperty.SetMaxLength | (*args, **kwargs) | return _propgrid.PGProperty_SetMaxLength(*args, **kwargs) | SetMaxLength(self, int maxLen) -> bool | SetMaxLength(self, int maxLen) -> bool | [
"SetMaxLength",
"(",
"self",
"int",
"maxLen",
")",
"-",
">",
"bool"
] | def SetMaxLength(*args, **kwargs):
"""SetMaxLength(self, int maxLen) -> bool"""
return _propgrid.PGProperty_SetMaxLength(*args, **kwargs) | [
"def",
"SetMaxLength",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_SetMaxLength",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L778-L780 | |
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | docs/doxygen/graphbuilder.py | python | Node.get_children | (self, recursive=False) | Get list of child nodes. | Get list of child nodes. | [
"Get",
"list",
"of",
"child",
"nodes",
"."
] | def get_children(self, recursive=False):
"""Get list of child nodes."""
if recursive:
result = list(self._children)
for child in self._children:
result.extend(child.get_children(recursive=True))
return result
else:
return self._children | [
"def",
"get_children",
"(",
"self",
",",
"recursive",
"=",
"False",
")",
":",
"if",
"recursive",
":",
"result",
"=",
"list",
"(",
"self",
".",
"_children",
")",
"for",
"child",
"in",
"self",
".",
"_children",
":",
"result",
".",
"extend",
"(",
"child",... | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/docs/doxygen/graphbuilder.py#L204-L212 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/gtk+/gtk/compose-parse.py | python | process_gdkkeysymsh | () | return keysymdb | Opens the gdkkeysyms.h file from GTK+/gdk/gdkkeysyms.h | Opens the gdkkeysyms.h file from GTK+/gdk/gdkkeysyms.h | [
"Opens",
"the",
"gdkkeysyms",
".",
"h",
"file",
"from",
"GTK",
"+",
"/",
"gdk",
"/",
"gdkkeysyms",
".",
"h"
] | def process_gdkkeysymsh():
""" Opens the gdkkeysyms.h file from GTK+/gdk/gdkkeysyms.h """
""" Fills up keysymdb with contents """
filename_gdkkeysymsh = download_file(URL_GDKKEYSYMSH)
try:
gdkkeysymsh = open(filename_gdkkeysymsh, 'r')
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
sys.exit(-1)
except:
print "Unexpected error: ", sys.exc_info()[0]
sys.exit(-1)
""" Parse the gdkkeysyms.h file and place contents in keysymdb """
linenum_gdkkeysymsh = 0
keysymdb = {}
for line in gdkkeysymsh.readlines():
linenum_gdkkeysymsh += 1
line = line.strip()
if line == "" or not match('^#define GDK_KEY_', line):
continue
components = split('\s+', line)
if len(components) < 3:
print "Invalid line %(linenum)d in %(filename)s: %(line)s"\
% {'linenum': linenum_gdkkeysymsh, 'filename': filename_gdkkeysymsh, 'line': line}
print "Was expecting 3 items in the line"
sys.exit(-1)
if not match('^GDK_KEY_', components[1]):
print "Invalid line %(linenum)d in %(filename)s: %(line)s"\
% {'linenum': linenum_gdkkeysymsh, 'filename': filename_gdkkeysymsh, 'line': line}
print "Was expecting a keysym starting with GDK_KEY_"
sys.exit(-1)
if match('^0x[0-9a-fA-F]+$', components[2]):
unival = long(components[2][2:], 16)
if unival == 0:
continue
keysymdb[components[1][8:]] = unival
else:
print "Invalid line %(linenum)d in %(filename)s: %(line)s"\
% {'linenum': linenum_gdkkeysymsh, 'filename': filename_gdkkeysymsh, 'line': line}
print "Was expecting a hexadecimal number at the end of the line"
sys.exit(-1)
gdkkeysymsh.close()
""" Patch up the keysymdb with some of our own stuff """
""" This is for a missing keysym from the currently upstream file """
#keysymdb['dead_stroke'] = 0x338
""" This is for a missing keysym from the currently upstream file """
###keysymdb['dead_belowring'] = 0x323
###keysymdb['dead_belowmacron'] = 0x331
###keysymdb['dead_belowcircumflex'] = 0x32d
###keysymdb['dead_belowtilde'] = 0x330
###keysymdb['dead_belowbreve'] = 0x32e
###keysymdb['dead_belowdiaeresis'] = 0x324
""" This is^Wwas preferential treatment for Greek """
# keysymdb['dead_tilde'] = 0x342
""" This is^was preferential treatment for Greek """
#keysymdb['combining_tilde'] = 0x342
""" Fixing VoidSymbol """
keysymdb['VoidSymbol'] = 0xFFFF
return keysymdb | [
"def",
"process_gdkkeysymsh",
"(",
")",
":",
"\"\"\" Fills up keysymdb with contents \"\"\"",
"filename_gdkkeysymsh",
"=",
"download_file",
"(",
"URL_GDKKEYSYMSH",
")",
"try",
":",
"gdkkeysymsh",
"=",
"open",
"(",
"filename_gdkkeysymsh",
",",
"'r'",
")",
"except",
"IOEr... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/gtk+/gtk/compose-parse.py#L240-L305 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/utils.py | python | S3RegionRedirector.redirect_from_cache | (self, params, context, **kwargs) | This handler retrieves a given bucket's signing context from the cache
and adds it into the request context. | This handler retrieves a given bucket's signing context from the cache
and adds it into the request context. | [
"This",
"handler",
"retrieves",
"a",
"given",
"bucket",
"s",
"signing",
"context",
"from",
"the",
"cache",
"and",
"adds",
"it",
"into",
"the",
"request",
"context",
"."
] | def redirect_from_cache(self, params, context, **kwargs):
"""
This handler retrieves a given bucket's signing context from the cache
and adds it into the request context.
"""
bucket = params.get('Bucket')
signing_context = self._cache.get(bucket)
if signing_context is not None:
context['signing'] = signing_context
else:
context['signing'] = {'bucket': bucket} | [
"def",
"redirect_from_cache",
"(",
"self",
",",
"params",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"bucket",
"=",
"params",
".",
"get",
"(",
"'Bucket'",
")",
"signing_context",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"bucket",
")",
"if",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/utils.py#L987-L997 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/utilities/canonical.py | python | Canonical.atoms | (self) | return unique_list(atom for arg in self.args for atom in arg.atoms()) | Returns all the atoms present in the args.
Returns
-------
list | Returns all the atoms present in the args. | [
"Returns",
"all",
"the",
"atoms",
"present",
"in",
"the",
"args",
"."
] | def atoms(self):
"""Returns all the atoms present in the args.
Returns
-------
list
"""
# Remove duplicates.
return unique_list(atom for arg in self.args for atom in arg.atoms()) | [
"def",
"atoms",
"(",
"self",
")",
":",
"# Remove duplicates.",
"return",
"unique_list",
"(",
"atom",
"for",
"arg",
"in",
"self",
".",
"args",
"for",
"atom",
"in",
"arg",
".",
"atoms",
"(",
")",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/utilities/canonical.py#L110-L118 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListCtrl.SetItemHyperText | (self, itemOrId, col=0, hyper=True) | return self._mainWin.SetItemHyperText(item, hyper) | Sets whether the item is hypertext or not.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise. | Sets whether the item is hypertext or not. | [
"Sets",
"whether",
"the",
"item",
"is",
"hypertext",
"or",
"not",
"."
] | def SetItemHyperText(self, itemOrId, col=0, hyper=True):
"""
Sets whether the item is hypertext or not.
:param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
:param `col`: the column index to which the input item belongs to;
:param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
"""
item = CreateListItem(itemOrId, col)
return self._mainWin.SetItemHyperText(item, hyper) | [
"def",
"SetItemHyperText",
"(",
"self",
",",
"itemOrId",
",",
"col",
"=",
"0",
",",
"hyper",
"=",
"True",
")",
":",
"item",
"=",
"CreateListItem",
"(",
"itemOrId",
",",
"col",
")",
"return",
"self",
".",
"_mainWin",
".",
"SetItemHyperText",
"(",
"item",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L13074-L13084 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/one_shot_object_detector/one_shot_object_detector.py | python | OneShotObjectDetector._get_summary_struct | (self) | return ([model_fields, data_fields, training_fields], section_titles) | Returns a structured description of the model, including (where
relevant) the schema of the training data, description of the training
data, training statistics, and model hyperparameters.
Returns
-------
sections : list (of list of tuples)
A list of summary sections.
Each section is a list.
Each item in a section list is a tuple of the form:
('<label>','<field>')
section_titles: list
A list of section titles.
The order matches that of the 'sections' object. | Returns a structured description of the model, including (where
relevant) the schema of the training data, description of the training
data, training statistics, and model hyperparameters. | [
"Returns",
"a",
"structured",
"description",
"of",
"the",
"model",
"including",
"(",
"where",
"relevant",
")",
"the",
"schema",
"of",
"the",
"training",
"data",
"description",
"of",
"the",
"training",
"data",
"training",
"statistics",
"and",
"model",
"hyperparam... | def _get_summary_struct(self):
"""
Returns a structured description of the model, including (where
relevant) the schema of the training data, description of the training
data, training statistics, and model hyperparameters.
Returns
-------
sections : list (of list of tuples)
A list of summary sections.
Each section is a list.
Each item in a section list is a tuple of the form:
('<label>','<field>')
section_titles: list
A list of section titles.
The order matches that of the 'sections' object.
"""
model_fields = [
("Number of classes", "num_classes"),
("Input image shape", "input_image_shape"),
]
data_fields = [
("Number of synthetically generated examples", "num_examples"),
("Number of synthetically generated bounding boxes", "num_bounding_boxes"),
]
training_fields = [
("Training time", "_training_time_as_string"),
("Training iterations", "training_iterations"),
("Training epochs", "training_epochs"),
("Final loss (specific to model)", "training_loss"),
]
section_titles = ["Model summary", "Synthetic data summary", "Training summary"]
return ([model_fields, data_fields, training_fields], section_titles) | [
"def",
"_get_summary_struct",
"(",
"self",
")",
":",
"model_fields",
"=",
"[",
"(",
"\"Number of classes\"",
",",
"\"num_classes\"",
")",
",",
"(",
"\"Input image shape\"",
",",
"\"input_image_shape\"",
")",
",",
"]",
"data_fields",
"=",
"[",
"(",
"\"Number of syn... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/one_shot_object_detector/one_shot_object_detector.py#L353-L386 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py | python | BufferControl.get_invalidate_events | (self) | Return the Window invalidate events. | Return the Window invalidate events. | [
"Return",
"the",
"Window",
"invalidate",
"events",
"."
] | def get_invalidate_events(self) -> Iterable["Event[object]"]:
"""
Return the Window invalidate events.
"""
# Whenever the buffer changes, the UI has to be updated.
yield self.buffer.on_text_changed
yield self.buffer.on_cursor_position_changed
yield self.buffer.on_completions_changed
yield self.buffer.on_suggestion_set | [
"def",
"get_invalidate_events",
"(",
"self",
")",
"->",
"Iterable",
"[",
"\"Event[object]\"",
"]",
":",
"# Whenever the buffer changes, the UI has to be updated.",
"yield",
"self",
".",
"buffer",
".",
"on_text_changed",
"yield",
"self",
".",
"buffer",
".",
"on_cursor_po... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py#L921-L930 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/errors.py | python | ParserContext._add_error | (self, location, error_id, msg) | Add an error with a source location information.
This is usually directly from an idl.syntax or idl.ast class. | Add an error with a source location information. | [
"Add",
"an",
"error",
"with",
"a",
"source",
"location",
"information",
"."
] | def _add_error(self, location, error_id, msg):
# type: (common.SourceLocation, str, str) -> None
"""
Add an error with a source location information.
This is usually directly from an idl.syntax or idl.ast class.
"""
self.errors.add(location, error_id, msg) | [
"def",
"_add_error",
"(",
"self",
",",
"location",
",",
"error_id",
",",
"msg",
")",
":",
"# type: (common.SourceLocation, str, str) -> None",
"self",
".",
"errors",
".",
"add",
"(",
"location",
",",
"error_id",
",",
"msg",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/errors.py#L237-L244 | ||
microsoft/clang | 86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5 | tools/scan-build-py/libscanbuild/report.py | python | assemble_cover | (args, prefix, fragments) | Put together the fragments into a final report. | Put together the fragments into a final report. | [
"Put",
"together",
"the",
"fragments",
"into",
"a",
"final",
"report",
"."
] | def assemble_cover(args, prefix, fragments):
""" Put together the fragments into a final report. """
import getpass
import socket
if args.html_title is None:
args.html_title = os.path.basename(prefix) + ' - analyzer results'
with open(os.path.join(args.output, 'index.html'), 'w') as handle:
indent = 0
handle.write(reindent("""
|<!DOCTYPE html>
|<html>
| <head>
| <title>{html_title}</title>
| <link type="text/css" rel="stylesheet" href="scanview.css"/>
| <script type='text/javascript' src="sorttable.js"></script>
| <script type='text/javascript' src='selectable.js'></script>
| </head>""", indent).format(html_title=args.html_title))
handle.write(comment('SUMMARYENDHEAD'))
handle.write(reindent("""
| <body>
| <h1>{html_title}</h1>
| <table>
| <tr><th>User:</th><td>{user_name}@{host_name}</td></tr>
| <tr><th>Working Directory:</th><td>{current_dir}</td></tr>
| <tr><th>Command Line:</th><td>{cmd_args}</td></tr>
| <tr><th>Clang Version:</th><td>{clang_version}</td></tr>
| <tr><th>Date:</th><td>{date}</td></tr>
| </table>""", indent).format(html_title=args.html_title,
user_name=getpass.getuser(),
host_name=socket.gethostname(),
current_dir=prefix,
cmd_args=' '.join(sys.argv),
clang_version=get_version(args.clang),
date=datetime.datetime.today(
).strftime('%c')))
for fragment in fragments:
# copy the content of fragments
with open(fragment, 'r') as input_handle:
shutil.copyfileobj(input_handle, handle)
handle.write(reindent("""
| </body>
|</html>""", indent)) | [
"def",
"assemble_cover",
"(",
"args",
",",
"prefix",
",",
"fragments",
")",
":",
"import",
"getpass",
"import",
"socket",
"if",
"args",
".",
"html_title",
"is",
"None",
":",
"args",
".",
"html_title",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"prefix... | https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/tools/scan-build-py/libscanbuild/report.py#L64-L108 | ||
Kitware/VTK | 5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8 | Wrapping/Python/vtkmodules/gtk/GtkVTKRenderWindowInteractor.py | python | GtkVTKRenderWindowInteractor.OnKeyRelease | (self, wid, event) | return gtk.TRUE | Key released. | Key released. | [
"Key",
"released",
"."
] | def OnKeyRelease(self, wid, event):
"Key released."
m = self.get_pointer()
ctrl, shift = self._GetCtrlShift(event)
keycode, keysym = event.keyval, event.string
key = chr(0)
if keycode < 256:
key = chr(keycode)
self._Iren.SetEventInformationFlipY(m[0], m[1], ctrl, shift,
key, 0, keysym)
self._Iren.KeyReleaseEvent()
return gtk.TRUE | [
"def",
"OnKeyRelease",
"(",
"self",
",",
"wid",
",",
"event",
")",
":",
"m",
"=",
"self",
".",
"get_pointer",
"(",
")",
"ctrl",
",",
"shift",
"=",
"self",
".",
"_GetCtrlShift",
"(",
"event",
")",
"keycode",
",",
"keysym",
"=",
"event",
".",
"keyval",... | https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/gtk/GtkVTKRenderWindowInteractor.py#L230-L241 | |
leela-zero/leela-zero | e3ed6310d33d75078ba74c3adf887d18439fc2e3 | scripts/cpplint.py | python | CheckMakePairUsesDeduction | (filename, clean_lines, linenum, error) | Check that make_pair's template arguments are deduced.
G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Check that make_pair's template arguments are deduced. | [
"Check",
"that",
"make_pair",
"s",
"template",
"arguments",
"are",
"deduced",
"."
] | def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
"""Check that make_pair's template arguments are deduced.
G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4, # 4 = high confidence
'For C++11-compatibility, omit template arguments from make_pair'
' OR use pair directly OR if appropriate, construct a pair directly') | [
"def",
"CheckMakePairUsesDeduction",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"match",
"=",
"_RE_PATTERN_EXPLICIT_MAKEPAIR",
".",
"search",
"(",
"line",
")",
"i... | https://github.com/leela-zero/leela-zero/blob/e3ed6310d33d75078ba74c3adf887d18439fc2e3/scripts/cpplint.py#L5693-L5711 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/multiprocessing/forkserver.py | python | main | (listener_fd, alive_r, preload, main_path=None, sys_path=None) | Run forkserver. | Run forkserver. | [
"Run",
"forkserver",
"."
] | def main(listener_fd, alive_r, preload, main_path=None, sys_path=None):
'''Run forkserver.'''
if preload:
if '__main__' in preload and main_path is not None:
process.current_process()._inheriting = True
try:
spawn.import_main_path(main_path)
finally:
del process.current_process()._inheriting
for modname in preload:
try:
__import__(modname)
except ImportError:
pass
util._close_stdin()
sig_r, sig_w = os.pipe()
os.set_blocking(sig_r, False)
os.set_blocking(sig_w, False)
def sigchld_handler(*_unused):
# Dummy signal handler, doesn't do anything
pass
handlers = {
# unblocking SIGCHLD allows the wakeup fd to notify our event loop
signal.SIGCHLD: sigchld_handler,
# protect the process from ^C
signal.SIGINT: signal.SIG_IGN,
}
old_handlers = {sig: signal.signal(sig, val)
for (sig, val) in handlers.items()}
# calling os.write() in the Python signal handler is racy
signal.set_wakeup_fd(sig_w)
# map child pids to client fds
pid_to_fd = {}
with socket.socket(socket.AF_UNIX, fileno=listener_fd) as listener, \
selectors.DefaultSelector() as selector:
_forkserver._forkserver_address = listener.getsockname()
selector.register(listener, selectors.EVENT_READ)
selector.register(alive_r, selectors.EVENT_READ)
selector.register(sig_r, selectors.EVENT_READ)
while True:
try:
while True:
rfds = [key.fileobj for (key, events) in selector.select()]
if rfds:
break
if alive_r in rfds:
# EOF because no more client processes left
assert os.read(alive_r, 1) == b'', "Not at EOF?"
raise SystemExit
if sig_r in rfds:
# Got SIGCHLD
os.read(sig_r, 65536) # exhaust
while True:
# Scan for child processes
try:
pid, sts = os.waitpid(-1, os.WNOHANG)
except ChildProcessError:
break
if pid == 0:
break
child_w = pid_to_fd.pop(pid, None)
if child_w is not None:
if os.WIFSIGNALED(sts):
returncode = -os.WTERMSIG(sts)
else:
if not os.WIFEXITED(sts):
raise AssertionError(
"Child {0:n} status is {1:n}".format(
pid,sts))
returncode = os.WEXITSTATUS(sts)
# Send exit code to client process
try:
write_signed(child_w, returncode)
except BrokenPipeError:
# client vanished
pass
os.close(child_w)
else:
# This shouldn't happen really
warnings.warn('forkserver: waitpid returned '
'unexpected pid %d' % pid)
if listener in rfds:
# Incoming fork request
with listener.accept()[0] as s:
# Receive fds from client
fds = reduction.recvfds(s, MAXFDS_TO_SEND + 1)
if len(fds) > MAXFDS_TO_SEND:
raise RuntimeError(
"Too many ({0:n}) fds to send".format(
len(fds)))
child_r, child_w, *fds = fds
s.close()
pid = os.fork()
if pid == 0:
# Child
code = 1
try:
listener.close()
selector.close()
unused_fds = [alive_r, child_w, sig_r, sig_w]
unused_fds.extend(pid_to_fd.values())
code = _serve_one(child_r, fds,
unused_fds,
old_handlers)
except Exception:
sys.excepthook(*sys.exc_info())
sys.stderr.flush()
finally:
os._exit(code)
else:
# Send pid to client process
try:
write_signed(child_w, pid)
except BrokenPipeError:
# client vanished
pass
pid_to_fd[pid] = child_w
os.close(child_r)
for fd in fds:
os.close(fd)
except OSError as e:
if e.errno != errno.ECONNABORTED:
raise | [
"def",
"main",
"(",
"listener_fd",
",",
"alive_r",
",",
"preload",
",",
"main_path",
"=",
"None",
",",
"sys_path",
"=",
"None",
")",
":",
"if",
"preload",
":",
"if",
"'__main__'",
"in",
"preload",
"and",
"main_path",
"is",
"not",
"None",
":",
"process",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/multiprocessing/forkserver.py#L166-L301 | ||
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/mox.py | python | MockMethod.__ne__ | (self, rhs) | return not self == rhs | Test whether this MockMethod is not equivalent to another MockMethod.
Args:
# rhs: the right hand side of the test
rhs: MockMethod | Test whether this MockMethod is not equivalent to another MockMethod. | [
"Test",
"whether",
"this",
"MockMethod",
"is",
"not",
"equivalent",
"to",
"another",
"MockMethod",
"."
] | def __ne__(self, rhs):
"""Test whether this MockMethod is not equivalent to another MockMethod.
Args:
# rhs: the right hand side of the test
rhs: MockMethod
"""
return not self == rhs | [
"def",
"__ne__",
"(",
"self",
",",
"rhs",
")",
":",
"return",
"not",
"self",
"==",
"rhs"
] | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/mox.py#L635-L643 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py | python | SubstitutionEnvironment.Override | (self, overrides) | return env | Produce a modified environment whose variables are overridden by
the overrides dictionaries. "overrides" is a dictionary that
will override the variables of this environment.
This function is much more efficient than Clone() or creating
a new Environment because it doesn't copy the construction
environment dictionary, it just wraps the underlying construction
environment, and doesn't even create a wrapper object if there
are no overrides. | Produce a modified environment whose variables are overridden by
the overrides dictionaries. "overrides" is a dictionary that
will override the variables of this environment. | [
"Produce",
"a",
"modified",
"environment",
"whose",
"variables",
"are",
"overridden",
"by",
"the",
"overrides",
"dictionaries",
".",
"overrides",
"is",
"a",
"dictionary",
"that",
"will",
"override",
"the",
"variables",
"of",
"this",
"environment",
"."
] | def Override(self, overrides):
"""
Produce a modified environment whose variables are overridden by
the overrides dictionaries. "overrides" is a dictionary that
will override the variables of this environment.
This function is much more efficient than Clone() or creating
a new Environment because it doesn't copy the construction
environment dictionary, it just wraps the underlying construction
environment, and doesn't even create a wrapper object if there
are no overrides.
"""
if not overrides: return self
o = copy_non_reserved_keywords(overrides)
if not o: return self
overrides = {}
merges = None
for key, value in o.items():
if key == 'parse_flags':
merges = value
else:
overrides[key] = SCons.Subst.scons_subst_once(value, self, key)
env = OverrideEnvironment(self, overrides)
if merges: env.MergeFlags(merges)
return env | [
"def",
"Override",
"(",
"self",
",",
"overrides",
")",
":",
"if",
"not",
"overrides",
":",
"return",
"self",
"o",
"=",
"copy_non_reserved_keywords",
"(",
"overrides",
")",
"if",
"not",
"o",
":",
"return",
"self",
"overrides",
"=",
"{",
"}",
"merges",
"="... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py#L608-L632 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/inspect.py | python | getfile | (object) | Work out which source or compiled file an object was defined in. | Work out which source or compiled file an object was defined in. | [
"Work",
"out",
"which",
"source",
"or",
"compiled",
"file",
"an",
"object",
"was",
"defined",
"in",
"."
] | def getfile(object):
"""Work out which source or compiled file an object was defined in."""
if ismodule(object):
if hasattr(object, '__file__'):
return object.__file__
raise TypeError('arg is a built-in module')
if isclass(object):
object = sys.modules.get(object.__module__)
if hasattr(object, '__file__'):
return object.__file__
raise TypeError('arg is a built-in class')
if ismethod(object):
object = object.im_func
if isfunction(object):
object = object.func_code
if istraceback(object):
object = object.tb_frame
if isframe(object):
object = object.f_code
if iscode(object):
return object.co_filename
raise TypeError('arg is not a module, class, method, '
'function, traceback, frame, or code object') | [
"def",
"getfile",
"(",
"object",
")",
":",
"if",
"ismodule",
"(",
"object",
")",
":",
"if",
"hasattr",
"(",
"object",
",",
"'__file__'",
")",
":",
"return",
"object",
".",
"__file__",
"raise",
"TypeError",
"(",
"'arg is a built-in module'",
")",
"if",
"isc... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/inspect.py#L397-L419 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/fused_conv/python/ops/fused_conv2d_bias_activation_op.py | python | fused_conv2d_bias_activation | (conv_input,
filter,
bias,
strides=None,
padding=None,
conv_input_scale=1.0,
side_input_scale=0.0,
side_input=None,
activation_mode="Relu",
data_format=None,
filter_format=None,
name=None) | return gen_fused_conv2d_bias_activation_op.fused_conv2d_bias_activation(
conv_input,
filter,
bias,
side_input,
conv_input_scale,
side_input_scale,
padding=padding,
strides=strides,
activation_mode=activation_mode,
data_format=data_format,
filter_format=filter_format,
name=name) | Fused 2D conv, bias and activation with optional side input.
Computes a fused 2-D convolution scaled by conv_input_scale,
adds an optional side input scaled by side_input_scale, adds biases,
and applies ReLU. As an equation:
output = ReLU(conv_input_scale * Conv(conv_input, filter) +
side_input_scale * side_input + bias)
Note: In int8 mode, The ReLU will clip the output to the range [0..127].
Args:
conv_input: A `Tensor` of the format specified by `data_format`.
filter: A `Tensor` whose format depends on `data_format`:
if `data_format` is "NCHW_VECT_C", filter should be "OIHW_VECT_I"
otherwise, it should be "HWIO" format.
bias: A 1-D `Tensor` of type `float32`, and dimensions equal to the
number of output channels.
strides: A list of 4 `ints` specifying convolution strides.
if `data_format` is "NCHW" or "NCHW_VECT_C", the order should be NCHW.
if `data_format` is "NHWC", the order should be NHWC.
padding: A `string` from: `"SAME", "VALID"`.
conv_input_scale: A scalar `float32` that will be multiplied by conv_input.
This is optional and defaults to 1. However it should be set to
specify the quantization scale when `data_format` is "NCHW_VECT_C".
side_input_scale: A scalar `float32` that will be multiplied by side_input.
This is optional and defaults to 0.
side_input: A `Tensor` of the format specified by `data_format`.
This is useful for implementing ResNet blocks.
activation_mode: (optional) currently supports the default "Relu", or
"None" activation function.
Note: in qint8 mode, "None" actually clips to the range [-128, 127],
while "Relu" clips to the range [0, 127].
data_format: Specifies the data format.
Possible values are:
"NHWC" float [batch, height, width, channels]
"NCHW" float [batch, channels, height, width]
"NCHW_VECT_C" qint8 [batch, channels / 4, height, width, channels % 4]
Defaults to `"NHWC"`.
Performance is worst for `"NHWC"` and best for `"NCHW_VECT_C"`.
filter_format: Specifies the filter format.
Possible values are:
"HWIO" float [kernel_height, kernel_width, input_channels,
output_channels ]
"OIHW" float [output_channels, input_channels, kernel_height,
kernel_width ]
"OIHW_VECT_I" qint8 [ output_channels, input_channels / 4,
kernel_height, kernel_width, input_channels % 4 ]
Defaults to `"HWIO"`.
name: A name for the operation (optional).
Returns:
A `Tensor` of the format specified by `data_format`. | Fused 2D conv, bias and activation with optional side input. | [
"Fused",
"2D",
"conv",
"bias",
"and",
"activation",
"with",
"optional",
"side",
"input",
"."
] | def fused_conv2d_bias_activation(conv_input,
filter,
bias,
strides=None,
padding=None,
conv_input_scale=1.0,
side_input_scale=0.0,
side_input=None,
activation_mode="Relu",
data_format=None,
filter_format=None,
name=None):
"""Fused 2D conv, bias and activation with optional side input.
Computes a fused 2-D convolution scaled by conv_input_scale,
adds an optional side input scaled by side_input_scale, adds biases,
and applies ReLU. As an equation:
output = ReLU(conv_input_scale * Conv(conv_input, filter) +
side_input_scale * side_input + bias)
Note: In int8 mode, The ReLU will clip the output to the range [0..127].
Args:
conv_input: A `Tensor` of the format specified by `data_format`.
filter: A `Tensor` whose format depends on `data_format`:
if `data_format` is "NCHW_VECT_C", filter should be "OIHW_VECT_I"
otherwise, it should be "HWIO" format.
bias: A 1-D `Tensor` of type `float32`, and dimensions equal to the
number of output channels.
strides: A list of 4 `ints` specifying convolution strides.
if `data_format` is "NCHW" or "NCHW_VECT_C", the order should be NCHW.
if `data_format` is "NHWC", the order should be NHWC.
padding: A `string` from: `"SAME", "VALID"`.
conv_input_scale: A scalar `float32` that will be multiplied by conv_input.
This is optional and defaults to 1. However it should be set to
specify the quantization scale when `data_format` is "NCHW_VECT_C".
side_input_scale: A scalar `float32` that will be multiplied by side_input.
This is optional and defaults to 0.
side_input: A `Tensor` of the format specified by `data_format`.
This is useful for implementing ResNet blocks.
activation_mode: (optional) currently supports the default "Relu", or
"None" activation function.
Note: in qint8 mode, "None" actually clips to the range [-128, 127],
while "Relu" clips to the range [0, 127].
data_format: Specifies the data format.
Possible values are:
"NHWC" float [batch, height, width, channels]
"NCHW" float [batch, channels, height, width]
"NCHW_VECT_C" qint8 [batch, channels / 4, height, width, channels % 4]
Defaults to `"NHWC"`.
Performance is worst for `"NHWC"` and best for `"NCHW_VECT_C"`.
filter_format: Specifies the filter format.
Possible values are:
"HWIO" float [kernel_height, kernel_width, input_channels,
output_channels ]
"OIHW" float [output_channels, input_channels, kernel_height,
kernel_width ]
"OIHW_VECT_I" qint8 [ output_channels, input_channels / 4,
kernel_height, kernel_width, input_channels % 4 ]
Defaults to `"HWIO"`.
name: A name for the operation (optional).
Returns:
A `Tensor` of the format specified by `data_format`.
"""
if strides is None:
strides = [1, 1, 1, 1]
if side_input is None:
side_input = []
return gen_fused_conv2d_bias_activation_op.fused_conv2d_bias_activation(
conv_input,
filter,
bias,
side_input,
conv_input_scale,
side_input_scale,
padding=padding,
strides=strides,
activation_mode=activation_mode,
data_format=data_format,
filter_format=filter_format,
name=name) | [
"def",
"fused_conv2d_bias_activation",
"(",
"conv_input",
",",
"filter",
",",
"bias",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"None",
",",
"conv_input_scale",
"=",
"1.0",
",",
"side_input_scale",
"=",
"0.0",
",",
"side_input",
"=",
"None",
",",
"ac... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/fused_conv/python/ops/fused_conv2d_bias_activation_op.py#L30-L110 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/rexec.py | python | RExec.s_eval | (self, *args) | return self.s_apply(self.r_eval, args) | Evaluate code within a restricted environment.
Similar to the r_eval() method, but the code will be granted access
to restricted versions of the standard I/O streams sys.stdin,
sys.stderr, and sys.stdout.
The code parameter must either be a string containing a Python
expression, or a compiled code object, which will be evaluated in
the restricted environment's __main__ module. The value of the
expression or code object will be returned. | Evaluate code within a restricted environment. | [
"Evaluate",
"code",
"within",
"a",
"restricted",
"environment",
"."
] | def s_eval(self, *args):
"""Evaluate code within a restricted environment.
Similar to the r_eval() method, but the code will be granted access
to restricted versions of the standard I/O streams sys.stdin,
sys.stderr, and sys.stdout.
The code parameter must either be a string containing a Python
expression, or a compiled code object, which will be evaluated in
the restricted environment's __main__ module. The value of the
expression or code object will be returned.
"""
return self.s_apply(self.r_eval, args) | [
"def",
"s_eval",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"s_apply",
"(",
"self",
".",
"r_eval",
",",
"args",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/rexec.py#L436-L449 | |
moderngl/moderngl | 32fe79927e02b0fa893b3603d677bdae39771e14 | moderngl/framebuffer.py | python | Framebuffer.scissor | (self) | return self.mglo.scissor | tuple: Get or set the scissor box of the framebuffer.
When scissor testing is enabled fragments outside
the defined scissor box will be discarded. This
applies to rendered geometry or :py:meth:`Framebuffer.clear`.
Setting is value enables scissor testing in the framebuffer.
Setting the scissor to ``None`` disables scissor testing
and reverts the scissor box to match the framebuffer size.
Example::
# Enable scissor testing
>>> ctx.scissor = 100, 100, 200, 100
# Disable scissor testing
>>> ctx.scissor = None | tuple: Get or set the scissor box of the framebuffer. | [
"tuple",
":",
"Get",
"or",
"set",
"the",
"scissor",
"box",
"of",
"the",
"framebuffer",
"."
] | def scissor(self) -> Tuple[int, int, int, int]:
'''
tuple: Get or set the scissor box of the framebuffer.
When scissor testing is enabled fragments outside
the defined scissor box will be discarded. This
applies to rendered geometry or :py:meth:`Framebuffer.clear`.
Setting is value enables scissor testing in the framebuffer.
Setting the scissor to ``None`` disables scissor testing
and reverts the scissor box to match the framebuffer size.
Example::
# Enable scissor testing
>>> ctx.scissor = 100, 100, 200, 100
# Disable scissor testing
>>> ctx.scissor = None
'''
return self.mglo.scissor | [
"def",
"scissor",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
",",
"int",
"]",
":",
"return",
"self",
".",
"mglo",
".",
"scissor"
] | https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/framebuffer.py#L78-L98 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.SetAndShowDefaultStyle | (*args, **kwargs) | return _richtext.RichTextCtrl_SetAndShowDefaultStyle(*args, **kwargs) | SetAndShowDefaultStyle(self, RichTextAttr attr) | SetAndShowDefaultStyle(self, RichTextAttr attr) | [
"SetAndShowDefaultStyle",
"(",
"self",
"RichTextAttr",
"attr",
")"
] | def SetAndShowDefaultStyle(*args, **kwargs):
"""SetAndShowDefaultStyle(self, RichTextAttr attr)"""
return _richtext.RichTextCtrl_SetAndShowDefaultStyle(*args, **kwargs) | [
"def",
"SetAndShowDefaultStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_SetAndShowDefaultStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L4140-L4142 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/utils/cli_parser.py | python | get_onnx_cli_parser | (parser: argparse.ArgumentParser = None) | return parser | Specifies cli arguments for Model Optimizer for ONNX
Returns
-------
ArgumentParser instance | Specifies cli arguments for Model Optimizer for ONNX | [
"Specifies",
"cli",
"arguments",
"for",
"Model",
"Optimizer",
"for",
"ONNX"
] | def get_onnx_cli_parser(parser: argparse.ArgumentParser = None):
"""
Specifies cli arguments for Model Optimizer for ONNX
Returns
-------
ArgumentParser instance
"""
if not parser:
parser = argparse.ArgumentParser(usage='%(prog)s [options]')
get_common_cli_parser(parser=parser)
return parser | [
"def",
"get_onnx_cli_parser",
"(",
"parser",
":",
"argparse",
".",
"ArgumentParser",
"=",
"None",
")",
":",
"if",
"not",
"parser",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"usage",
"=",
"'%(prog)s [options]'",
")",
"get_common_cli_parser",
"("... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/cli_parser.py#L732-L744 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/six.py | python | _add_doc | (func, doc) | Add documentation to a function. | Add documentation to a function. | [
"Add",
"documentation",
"to",
"a",
"function",
"."
] | def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc | [
"def",
"_add_doc",
"(",
"func",
",",
"doc",
")",
":",
"func",
".",
"__doc__",
"=",
"doc"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/six.py#L75-L77 | ||
lattice/quda | 7d04db018e01718e80cf32d78f44e8cdffdbe46e | lib/generate/wrap.py | python | foreachfn | (out, scope, args, children) | Iterate over all functions listed in args. | Iterate over all functions listed in args. | [
"Iterate",
"over",
"all",
"functions",
"listed",
"in",
"args",
"."
] | def foreachfn(out, scope, args, children):
"""Iterate over all functions listed in args."""
args or syntax_error("Error: foreachfn requires function name argument.")
global cur_function
fn_var = args[0]
for fn_name in args[1:]:
cur_function = fn_name
if not fn_name in mpi_functions:
syntax_error(fn_name + " is not an MPI function")
fn = mpi_functions[fn_name]
fn_scope = Scope(scope)
fn_scope[fn_var] = fn_name
include_decl(fn_scope, fn)
for child in children:
child.evaluate(out, fn_scope)
cur_function = None | [
"def",
"foreachfn",
"(",
"out",
",",
"scope",
",",
"args",
",",
"children",
")",
":",
"args",
"or",
"syntax_error",
"(",
"\"Error: foreachfn requires function name argument.\"",
")",
"global",
"cur_function",
"fn_var",
"=",
"args",
"[",
"0",
"]",
"for",
"fn_name... | https://github.com/lattice/quda/blob/7d04db018e01718e80cf32d78f44e8cdffdbe46e/lib/generate/wrap.py#L869-L887 | ||
simsong/bulk_extractor | 738911df22b7066ca9e1662f4131fb44090a4196 | python/dfxml.py | python | volumeobject_reader._start_element | (self, name, attrs) | Handles the start of an element for the XPAT scanner | Handles the start of an element for the XPAT scanner | [
"Handles",
"the",
"start",
"of",
"an",
"element",
"for",
"the",
"XPAT",
"scanner"
] | def _start_element(self, name, attrs):
""" Handles the start of an element for the XPAT scanner"""
self.tagstack.append(name)
if name=="volume":
self.volumeobject = volumeobject_sax()
self.volumeobject.image = self.imageobject
return
if name=="fileobject":
self.cdata = None # don't record this
return
self.cdata = "" | [
"def",
"_start_element",
"(",
"self",
",",
"name",
",",
"attrs",
")",
":",
"self",
".",
"tagstack",
".",
"append",
"(",
"name",
")",
"if",
"name",
"==",
"\"volume\"",
":",
"self",
".",
"volumeobject",
"=",
"volumeobject_sax",
"(",
")",
"self",
".",
"vo... | https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L1312-L1322 | ||
abseil/abseil-cpp | 73316fc3c565e5998983b0fb502d938ccddcded2 | absl/abseil.podspec.gen.py | python | write_podspec_rule | (f, rule, depth) | Writes podspec from given rule. | Writes podspec from given rule. | [
"Writes",
"podspec",
"from",
"given",
"rule",
"."
] | def write_podspec_rule(f, rule, depth):
"""Writes podspec from given rule."""
indent = " " * (depth + 1)
spec_var = get_spec_var(depth)
# Puts all files in hdrs, textual_hdrs, and srcs into source_files.
# Since CocoaPods treats header_files a bit differently from bazel,
# this won't generate a header_files field so that all source_files
# are considered as header files.
srcs = sorted(set(rule.hdrs + rule.textual_hdrs + rule.srcs))
write_indented_list(
f, "{indent}{var}.source_files = ".format(indent=indent, var=spec_var),
srcs)
# Writes dependencies of this rule.
for dep in sorted(rule.deps):
name = get_spec_name(dep.replace(":", "/"))
f.write("{indent}{var}.dependency '{dep}'\n".format(
indent=indent, var=spec_var, dep=name)) | [
"def",
"write_podspec_rule",
"(",
"f",
",",
"rule",
",",
"depth",
")",
":",
"indent",
"=",
"\" \"",
"*",
"(",
"depth",
"+",
"1",
")",
"spec_var",
"=",
"get_spec_var",
"(",
"depth",
")",
"# Puts all files in hdrs, textual_hdrs, and srcs into source_files.",
"# Sin... | https://github.com/abseil/abseil-cpp/blob/73316fc3c565e5998983b0fb502d938ccddcded2/absl/abseil.podspec.gen.py#L174-L190 | ||
facebookincubator/fizz | bd0ba1b80f72023cb7ede671a4caa85f6664d3f6 | build/fbcode_builder/getdeps/dyndeps.py | python | WinDeps.emit_dev_run_script | (self, script_path, dep_dirs) | Emit a script that can be used to run build artifacts directly from the
build directory, without installing them.
The dep_dirs parameter should be a list of paths that need to be added to $PATH.
This can be computed by calling compute_dependency_paths() or
compute_dependency_paths_fast().
This is only necessary on Windows, which does not have RPATH, and instead
requires the $PATH environment variable be updated in order to find the proper
library dependencies. | Emit a script that can be used to run build artifacts directly from the
build directory, without installing them. | [
"Emit",
"a",
"script",
"that",
"can",
"be",
"used",
"to",
"run",
"build",
"artifacts",
"directly",
"from",
"the",
"build",
"directory",
"without",
"installing",
"them",
"."
] | def emit_dev_run_script(self, script_path, dep_dirs):
"""Emit a script that can be used to run build artifacts directly from the
build directory, without installing them.
The dep_dirs parameter should be a list of paths that need to be added to $PATH.
This can be computed by calling compute_dependency_paths() or
compute_dependency_paths_fast().
This is only necessary on Windows, which does not have RPATH, and instead
requires the $PATH environment variable be updated in order to find the proper
library dependencies.
"""
contents = self._get_dev_run_script_contents(dep_dirs)
with open(script_path, "w") as f:
f.write(contents) | [
"def",
"emit_dev_run_script",
"(",
"self",
",",
"script_path",
",",
"dep_dirs",
")",
":",
"contents",
"=",
"self",
".",
"_get_dev_run_script_contents",
"(",
"dep_dirs",
")",
"with",
"open",
"(",
"script_path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"... | https://github.com/facebookincubator/fizz/blob/bd0ba1b80f72023cb7ede671a4caa85f6664d3f6/build/fbcode_builder/getdeps/dyndeps.py#L233-L247 | ||
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/json_format.py | python | _ConvertFloat | (value) | Convert an floating point number. | Convert an floating point number. | [
"Convert",
"an",
"floating",
"point",
"number",
"."
] | def _ConvertFloat(value):
"""Convert an floating point number."""
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
try:
# Assume Python compatible syntax.
return float(value)
except ValueError:
# Check alternative spellings.
if value == _NEG_INFINITY:
return float('-inf')
elif value == _INFINITY:
return float('inf')
elif value == _NAN:
return float('nan')
else:
raise ParseError('Couldn\'t parse float: {0}.'.format(value)) | [
"def",
"_ConvertFloat",
"(",
"value",
")",
":",
"if",
"value",
"==",
"'nan'",
":",
"raise",
"ParseError",
"(",
"'Couldn\\'t parse float \"nan\", use \"NaN\" instead.'",
")",
"try",
":",
"# Assume Python compatible syntax.",
"return",
"float",
"(",
"value",
")",
"excep... | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/json_format.py#L605-L621 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32comext/axdebug/gateways.py | python | RemoteDebugApplicationEvents.OnDestroyThread | (self, rdat) | rdat -- PyIRemoteDebugApplicationThread | rdat -- PyIRemoteDebugApplicationThread | [
"rdat",
"--",
"PyIRemoteDebugApplicationThread"
] | def OnDestroyThread(self, rdat):
"""rdat -- PyIRemoteDebugApplicationThread
"""
RaiseNotImpl("OnDestroyThread") | [
"def",
"OnDestroyThread",
"(",
"self",
",",
"rdat",
")",
":",
"RaiseNotImpl",
"(",
"\"OnDestroyThread\"",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32comext/axdebug/gateways.py#L393-L396 | ||
nlohmann/json | eb2182414749825be086c825edb5229e5c28503d | third_party/cpplint/cpplint.py | python | NestingState.InNamespaceBody | (self) | return self.stack and isinstance(self.stack[-1], _NamespaceInfo) | Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise. | Check if we are currently one level inside a namespace body. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"a",
"namespace",
"body",
"."
] | def InNamespaceBody(self):
"""Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _NamespaceInfo) | [
"def",
"InNamespaceBody",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_NamespaceInfo",
")"
] | https://github.com/nlohmann/json/blob/eb2182414749825be086c825edb5229e5c28503d/third_party/cpplint/cpplint.py#L2932-L2938 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py | python | _turtle_docrevise | (docstr) | return newdocstr | To reduce docstrings from RawTurtle class for functions | To reduce docstrings from RawTurtle class for functions | [
"To",
"reduce",
"docstrings",
"from",
"RawTurtle",
"class",
"for",
"functions"
] | def _turtle_docrevise(docstr):
"""To reduce docstrings from RawTurtle class for functions
"""
import re
if docstr is None:
return None
turtlename = _CFG["exampleturtle"]
newdocstr = docstr.replace("%s." % turtlename,"")
parexp = re.compile(r' \(.+ %s\):' % turtlename)
newdocstr = parexp.sub(":", newdocstr)
return newdocstr | [
"def",
"_turtle_docrevise",
"(",
"docstr",
")",
":",
"import",
"re",
"if",
"docstr",
"is",
"None",
":",
"return",
"None",
"turtlename",
"=",
"_CFG",
"[",
"\"exampleturtle\"",
"]",
"newdocstr",
"=",
"docstr",
".",
"replace",
"(",
"\"%s.\"",
"%",
"turtlename",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py#L3914-L3924 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBTypeFilter.__init__ | (self, *args) | __init__(lldb::SBTypeFilter self) -> SBTypeFilter
__init__(lldb::SBTypeFilter self, uint32_t options) -> SBTypeFilter
__init__(lldb::SBTypeFilter self, SBTypeFilter rhs) -> SBTypeFilter | __init__(lldb::SBTypeFilter self) -> SBTypeFilter
__init__(lldb::SBTypeFilter self, uint32_t options) -> SBTypeFilter
__init__(lldb::SBTypeFilter self, SBTypeFilter rhs) -> SBTypeFilter | [
"__init__",
"(",
"lldb",
"::",
"SBTypeFilter",
"self",
")",
"-",
">",
"SBTypeFilter",
"__init__",
"(",
"lldb",
"::",
"SBTypeFilter",
"self",
"uint32_t",
"options",
")",
"-",
">",
"SBTypeFilter",
"__init__",
"(",
"lldb",
"::",
"SBTypeFilter",
"self",
"SBTypeFil... | def __init__(self, *args):
"""
__init__(lldb::SBTypeFilter self) -> SBTypeFilter
__init__(lldb::SBTypeFilter self, uint32_t options) -> SBTypeFilter
__init__(lldb::SBTypeFilter self, SBTypeFilter rhs) -> SBTypeFilter
"""
this = _lldb.new_SBTypeFilter(*args)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"this",
"=",
"_lldb",
".",
"new_SBTypeFilter",
"(",
"*",
"args",
")",
"try",
":",
"self",
".",
"this",
".",
"append",
"(",
"this",
")",
"except",
"__builtin__",
".",
"Exception",
":",
"self"... | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L13433-L13443 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ctc_ops.py | python | ctc_unique_labels | (labels, name=None) | Get unique labels and indices for batched labels for `tf.nn.ctc_loss`.
For use with `tf.nn.ctc_loss` optional argument `unique`: This op can be
used to preprocess labels in input pipeline to for better speed/memory use
computing the ctc loss on TPU.
Example:
ctc_unique_labels([[3, 4, 4, 3]]) ->
unique labels padded with 0: [[3, 4, 0, 0]]
indices of original labels in unique: [0, 1, 1, 0]
Args:
labels: tensor of shape [batch_size, max_label_length] padded with 0.
name: A name for this `Op`. Defaults to "ctc_unique_labels".
Returns:
tuple of
- unique labels, tensor of shape `[batch_size, max_label_length]`
- indices into unique labels, shape `[batch_size, max_label_length]` | Get unique labels and indices for batched labels for `tf.nn.ctc_loss`. | [
"Get",
"unique",
"labels",
"and",
"indices",
"for",
"batched",
"labels",
"for",
"tf",
".",
"nn",
".",
"ctc_loss",
"."
] | def ctc_unique_labels(labels, name=None):
"""Get unique labels and indices for batched labels for `tf.nn.ctc_loss`.
For use with `tf.nn.ctc_loss` optional argument `unique`: This op can be
used to preprocess labels in input pipeline to for better speed/memory use
computing the ctc loss on TPU.
Example:
ctc_unique_labels([[3, 4, 4, 3]]) ->
unique labels padded with 0: [[3, 4, 0, 0]]
indices of original labels in unique: [0, 1, 1, 0]
Args:
labels: tensor of shape [batch_size, max_label_length] padded with 0.
name: A name for this `Op`. Defaults to "ctc_unique_labels".
Returns:
tuple of
- unique labels, tensor of shape `[batch_size, max_label_length]`
- indices into unique labels, shape `[batch_size, max_label_length]`
"""
with ops.name_scope(name, "ctc_unique_labels", [labels]):
labels = ops.convert_to_tensor(labels, name="labels")
def _unique(x):
u = array_ops.unique(x)
y = array_ops.pad(u.y, [[0, _get_dim(u.idx, 0) - _get_dim(u.y, 0)]])
y = math_ops.cast(y, dtypes.int64)
return [y, u.idx]
return map_fn.map_fn(_unique, labels, dtype=[dtypes.int64, dtypes.int32]) | [
"def",
"ctc_unique_labels",
"(",
"labels",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"ctc_unique_labels\"",
",",
"[",
"labels",
"]",
")",
":",
"labels",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"labels",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ctc_ops.py#L911-L942 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/WebOb/webob/request.py | python | BaseRequest._urlvars__get | (self) | Return any *named* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value. | Return any *named* variables matched in the URL. | [
"Return",
"any",
"*",
"named",
"*",
"variables",
"matched",
"in",
"the",
"URL",
"."
] | def _urlvars__get(self):
"""
Return any *named* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
if 'paste.urlvars' in self.environ:
return self.environ['paste.urlvars']
elif 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][1]
else:
result = {}
self.environ['wsgiorg.routing_args'] = ((), result)
return result | [
"def",
"_urlvars__get",
"(",
"self",
")",
":",
"if",
"'paste.urlvars'",
"in",
"self",
".",
"environ",
":",
"return",
"self",
".",
"environ",
"[",
"'paste.urlvars'",
"]",
"elif",
"'wsgiorg.routing_args'",
"in",
"self",
".",
"environ",
":",
"return",
"self",
"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/WebOb/webob/request.py#L566-L580 | ||
crosslife/OpenBird | 9e0198a1a2295f03fa1e8676e216e22c9c7d380b | cocos2d/tools/pylib/PathUtils.py | python | PathUtils.set_root | (self, root) | set the root path | set the root path | [
"set",
"the",
"root",
"path"
] | def set_root(self, root):
"set the root path"
self._root = root | [
"def",
"set_root",
"(",
"self",
",",
"root",
")",
":",
"self",
".",
"_root",
"=",
"root"
] | https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/pylib/PathUtils.py#L53-L55 | ||
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | scripts/cpp_lint.py | python | _CppLintState.IncrementErrorCount | (self, category) | Bumps the module's error statistic. | Bumps the module's error statistic. | [
"Bumps",
"the",
"module",
"s",
"error",
"statistic",
"."
] | def IncrementErrorCount(self, category):
"""Bumps the module's error statistic."""
self.error_count += 1
if self.counting in ('toplevel', 'detailed'):
if self.counting != 'detailed':
category = category.split('/')[0]
if category not in self.errors_by_category:
self.errors_by_category[category] = 0
self.errors_by_category[category] += 1 | [
"def",
"IncrementErrorCount",
"(",
"self",
",",
"category",
")",
":",
"self",
".",
"error_count",
"+=",
"1",
"if",
"self",
".",
"counting",
"in",
"(",
"'toplevel'",
",",
"'detailed'",
")",
":",
"if",
"self",
".",
"counting",
"!=",
"'detailed'",
":",
"cat... | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L751-L759 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | SAXCallback.attributeDecl | (self, elem, name, type, defi, defaultValue, nameList) | called when an ATTRIBUTE definition has been found | called when an ATTRIBUTE definition has been found | [
"called",
"when",
"an",
"ATTRIBUTE",
"definition",
"has",
"been",
"found"
] | def attributeDecl(self, elem, name, type, defi, defaultValue, nameList):
"""called when an ATTRIBUTE definition has been found"""
pass | [
"def",
"attributeDecl",
"(",
"self",
",",
"elem",
",",
"name",
",",
"type",
",",
"defi",
",",
"defaultValue",
",",
"nameList",
")",
":",
"pass"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L236-L238 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/environment.py | python | create_cache | (size) | return LRUCache(size) | Return the cache class for the given size. | Return the cache class for the given size. | [
"Return",
"the",
"cache",
"class",
"for",
"the",
"given",
"size",
"."
] | def create_cache(size):
"""Return the cache class for the given size."""
if size == 0:
return None
if size < 0:
return {}
return LRUCache(size) | [
"def",
"create_cache",
"(",
"size",
")",
":",
"if",
"size",
"==",
"0",
":",
"return",
"None",
"if",
"size",
"<",
"0",
":",
"return",
"{",
"}",
"return",
"LRUCache",
"(",
"size",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/environment.py#L60-L66 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibar.py | python | AuiToolBar.GetToolIndex | (self, tool_id) | return wx.NOT_FOUND | Returns the position of the tool in the toolbar given its identifier.
:param integer `tool_id`: the toolbar item identifier. | Returns the position of the tool in the toolbar given its identifier. | [
"Returns",
"the",
"position",
"of",
"the",
"tool",
"in",
"the",
"toolbar",
"given",
"its",
"identifier",
"."
] | def GetToolIndex(self, tool_id):
"""
Returns the position of the tool in the toolbar given its identifier.
:param integer `tool_id`: the toolbar item identifier.
"""
# this will prevent us from returning the index of the
# first separator in the toolbar since its id is equal to -1
if tool_id == -1:
return wx.NOT_FOUND
for i, item in enumerate(self._items):
if item.id == tool_id:
return i
return wx.NOT_FOUND | [
"def",
"GetToolIndex",
"(",
"self",
",",
"tool_id",
")",
":",
"# this will prevent us from returning the index of the",
"# first separator in the toolbar since its id is equal to -1",
"if",
"tool_id",
"==",
"-",
"1",
":",
"return",
"wx",
".",
"NOT_FOUND",
"for",
"i",
",",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L2876-L2892 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pathlib.py | python | PurePath.joinpath | (self, *args) | return self._make_child(args) | Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored). | Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored). | [
"Combine",
"this",
"path",
"with",
"one",
"or",
"several",
"arguments",
"and",
"return",
"a",
"new",
"path",
"representing",
"either",
"a",
"subpath",
"(",
"if",
"all",
"arguments",
"are",
"relative",
"paths",
")",
"or",
"a",
"totally",
"different",
"path",
... | def joinpath(self, *args):
"""Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored).
"""
return self._make_child(args) | [
"def",
"joinpath",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"_make_child",
"(",
"args",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pathlib.py#L916-L922 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/timeit.py | python | reindent | (src, indent) | return src.replace("\n", "\n" + " "*indent) | Helper to reindent a multi-line statement. | Helper to reindent a multi-line statement. | [
"Helper",
"to",
"reindent",
"a",
"multi",
"-",
"line",
"statement",
"."
] | def reindent(src, indent):
"""Helper to reindent a multi-line statement."""
return src.replace("\n", "\n" + " "*indent) | [
"def",
"reindent",
"(",
"src",
",",
"indent",
")",
":",
"return",
"src",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\\n\"",
"+",
"\" \"",
"*",
"indent",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/timeit.py#L90-L92 | |
bairdzhang/smallhardface | 76fa1d87a9602d9b13d7a7fe693fc7aec91cab80 | lib/roi_data_layer/layer.py | python | RoIDataLayer.reshape | (self, bottom, top) | Reshaping happens during the call to forward. | Reshaping happens during the call to forward. | [
"Reshaping",
"happens",
"during",
"the",
"call",
"to",
"forward",
"."
] | def reshape(self, bottom, top):
"""Reshaping happens during the call to forward."""
pass | [
"def",
"reshape",
"(",
"self",
",",
"bottom",
",",
"top",
")",
":",
"pass"
] | https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/lib/roi_data_layer/layer.py#L146-L148 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/ndlstm/python/lstm1d.py | python | ndlstm_base_unrolled | (inputs, noutput, scope=None, reverse=False) | Run an LSTM, either forward or backward.
This is a 1D LSTM implementation using unrolling and the TensorFlow
LSTM op.
Args:
inputs: input sequence (length, batch_size, ninput)
noutput: depth of output
scope: optional scope name
reverse: run LSTM in reverse
Returns:
Output sequence (length, batch_size, noutput) | Run an LSTM, either forward or backward. | [
"Run",
"an",
"LSTM",
"either",
"forward",
"or",
"backward",
"."
] | def ndlstm_base_unrolled(inputs, noutput, scope=None, reverse=False):
"""Run an LSTM, either forward or backward.
This is a 1D LSTM implementation using unrolling and the TensorFlow
LSTM op.
Args:
inputs: input sequence (length, batch_size, ninput)
noutput: depth of output
scope: optional scope name
reverse: run LSTM in reverse
Returns:
Output sequence (length, batch_size, noutput)
"""
with tf.variable_scope(scope, "SeqLstmUnrolled", [inputs]):
length, batch_size, _ = _shape(inputs)
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(noutput, state_is_tuple=False)
state = tf.zeros([batch_size, lstm_cell.state_size])
output_u = []
inputs_u = tf.unpack(inputs)
if reverse:
inputs_u = list(reversed(inputs_u))
for i in xrange(length):
if i > 0:
tf.get_variable_scope().reuse_variables()
output, state = lstm_cell(inputs_u[i], state)
output_u += [output]
if reverse:
output_u = list(reversed(output_u))
outputs = tf.pack(output_u)
return outputs | [
"def",
"ndlstm_base_unrolled",
"(",
"inputs",
",",
"noutput",
",",
"scope",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"\"SeqLstmUnrolled\"",
",",
"[",
"inputs",
"]",
")",
":",
"length",
"... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/ndlstm/python/lstm1d.py#L35-L67 | ||
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/unit/unit.py | python | Unit.__hash__ | (self) | return self._hash | Compute a hash code for this object. | Compute a hash code for this object. | [
"Compute",
"a",
"hash",
"code",
"for",
"this",
"object",
"."
] | def __hash__(self):
"""
Compute a hash code for this object.
"""
try:
return self._hash
except AttributeError:
pass
self._hash = hash(self.get_name())
return self._hash | [
"def",
"__hash__",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_hash",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_hash",
"=",
"hash",
"(",
"self",
".",
"get_name",
"(",
")",
")",
"return",
"self",
".",
"_hash"
] | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/unit/unit.py#L203-L212 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/formats/info.py | python | TableBuilderVerboseMixin._gen_rows_without_counts | (self) | Iterator with string representation of body data without counts. | Iterator with string representation of body data without counts. | [
"Iterator",
"with",
"string",
"representation",
"of",
"body",
"data",
"without",
"counts",
"."
] | def _gen_rows_without_counts(self) -> Iterator[Sequence[str]]:
"""Iterator with string representation of body data without counts.""" | [
"def",
"_gen_rows_without_counts",
"(",
"self",
")",
"->",
"Iterator",
"[",
"Sequence",
"[",
"str",
"]",
"]",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/info.py#L577-L578 | ||
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/generator/ninja.py | python | Target.FinalOutput | (self) | return self.bundle or self.binary or self.actions_stamp | Return the last output of the target, which depends on all prior
steps. | Return the last output of the target, which depends on all prior
steps. | [
"Return",
"the",
"last",
"output",
"of",
"the",
"target",
"which",
"depends",
"on",
"all",
"prior",
"steps",
"."
] | def FinalOutput(self):
"""Return the last output of the target, which depends on all prior
steps."""
return self.bundle or self.binary or self.actions_stamp | [
"def",
"FinalOutput",
"(",
"self",
")",
":",
"return",
"self",
".",
"bundle",
"or",
"self",
".",
"binary",
"or",
"self",
".",
"actions_stamp"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/generator/ninja.py#L188-L191 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/graph_editor/subgraph.py | python | SubGraphView.__init__ | (self, inside_ops=(), passthrough_ts=()) | Create a subgraph containing the given ops and the "passthrough" tensors.
Args:
inside_ops: an object convertible to a list of `tf.Operation`. This list
defines all the operations in the subgraph.
passthrough_ts: an object convertible to a list of `tf.Tensor`. This list
define all the "passthrough" tensors. A passthrough tensor is a tensor
which goes directly from the input of the subgraph to it output, without
any intermediate operations. All the non passthrough tensors are
silently ignored.
Raises:
TypeError: if inside_ops cannot be converted to a list of `tf.Operation`
or if `passthrough_ts` cannot be converted to a list of `tf.Tensor`. | Create a subgraph containing the given ops and the "passthrough" tensors. | [
"Create",
"a",
"subgraph",
"containing",
"the",
"given",
"ops",
"and",
"the",
"passthrough",
"tensors",
"."
] | def __init__(self, inside_ops=(), passthrough_ts=()):
"""Create a subgraph containing the given ops and the "passthrough" tensors.
Args:
inside_ops: an object convertible to a list of `tf.Operation`. This list
defines all the operations in the subgraph.
passthrough_ts: an object convertible to a list of `tf.Tensor`. This list
define all the "passthrough" tensors. A passthrough tensor is a tensor
which goes directly from the input of the subgraph to it output, without
any intermediate operations. All the non passthrough tensors are
silently ignored.
Raises:
TypeError: if inside_ops cannot be converted to a list of `tf.Operation`
or if `passthrough_ts` cannot be converted to a list of `tf.Tensor`.
"""
inside_ops = util.make_list_of_op(inside_ops)
passthrough_ts = util.make_list_of_t(passthrough_ts)
ops_and_ts = inside_ops + passthrough_ts
if ops_and_ts:
self._graph = util.get_unique_graph(ops_and_ts)
self._ops = inside_ops
# Compute inside and outside tensor
inputs, outputs, insides = select.compute_boundary_ts(inside_ops)
# Compute passthrough tensors, silently ignoring the non-passthrough ones.
all_tensors = frozenset(inputs + outputs + list(insides))
self._passthrough_ts = [t for t in passthrough_ts if t not in all_tensors]
# Set inputs and outputs.
self._input_ts = inputs + self._passthrough_ts
self._output_ts = outputs + self._passthrough_ts
else:
self._graph = None
self._passthrough_ts = []
self._input_ts = []
self._output_ts = []
self._ops = [] | [
"def",
"__init__",
"(",
"self",
",",
"inside_ops",
"=",
"(",
")",
",",
"passthrough_ts",
"=",
"(",
")",
")",
":",
"inside_ops",
"=",
"util",
".",
"make_list_of_op",
"(",
"inside_ops",
")",
"passthrough_ts",
"=",
"util",
".",
"make_list_of_t",
"(",
"passthr... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/graph_editor/subgraph.py#L162-L200 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/sparse_ops.py | python | sparse_reset_shape | (sp_input, new_shape=None) | return ops.SparseTensor(in_indices, in_values, output_shape_tensor) | Resets the shape of a `SparseTensor` with indices and values unchanged.
If `new_shape` is None, returns a copy of `sp_input` with its shape reset
to the tight bounding box of `sp_input`.
If `new_shape` is provided, then it must be larger or equal in all dimensions
compared to the shape of `sp_input`. When this condition is met, the returned
SparseTensor will have its shape reset to `new_shape` and its indices and
values unchanged from that of `sp_input.`
For example:
Consider a `sp_input` with shape [2, 3, 5]:
[0, 0, 1]: a
[0, 1, 0]: b
[0, 2, 2]: c
[1, 0, 3]: d
- It is an error to set `new_shape` as [3, 7] since this represents a
rank-2 tensor while `sp_input` is rank-3. This is either a ValueError
during graph construction (if both shapes are known) or an OpError during
run time.
- Setting `new_shape` as [2, 3, 6] will be fine as this shape is larger or
eqaul in every dimension compared to the original shape [2, 3, 5].
- On the other hand, setting new_shape as [2, 3, 4] is also an error: The
third dimension is smaller than the original shape [2, 3, 5] (and an
`InvalidArgumentError` will be raised).
- If `new_shape` is None, the returned SparseTensor will have a shape
[2, 3, 4], which is the tight bounding box of `sp_input`.
Args:
sp_input: The input `SparseTensor`.
new_shape: None or a vector representing the new shape for the returned
`SpraseTensor`.
Returns:
A `SparseTensor` indices and values unchanged from `input_sp`. Its shape is
`new_shape` if that is set. Otherwise it is the tight bounding box of
`input_sp`
Raises:
TypeError: If `sp_input` is not a `SparseTensor`.
ValueError: If `new_shape` represents a tensor with a different rank from
that of `sp_input` (if shapes are known when graph is constructed).
OpError:
- If `new_shape` has dimension sizes that are too small.
- If shapes are not known during graph construction time, and during run
time it is found out that the ranks do not match. | Resets the shape of a `SparseTensor` with indices and values unchanged. | [
"Resets",
"the",
"shape",
"of",
"a",
"SparseTensor",
"with",
"indices",
"and",
"values",
"unchanged",
"."
] | def sparse_reset_shape(sp_input, new_shape=None):
"""Resets the shape of a `SparseTensor` with indices and values unchanged.
If `new_shape` is None, returns a copy of `sp_input` with its shape reset
to the tight bounding box of `sp_input`.
If `new_shape` is provided, then it must be larger or equal in all dimensions
compared to the shape of `sp_input`. When this condition is met, the returned
SparseTensor will have its shape reset to `new_shape` and its indices and
values unchanged from that of `sp_input.`
For example:
Consider a `sp_input` with shape [2, 3, 5]:
[0, 0, 1]: a
[0, 1, 0]: b
[0, 2, 2]: c
[1, 0, 3]: d
- It is an error to set `new_shape` as [3, 7] since this represents a
rank-2 tensor while `sp_input` is rank-3. This is either a ValueError
during graph construction (if both shapes are known) or an OpError during
run time.
- Setting `new_shape` as [2, 3, 6] will be fine as this shape is larger or
eqaul in every dimension compared to the original shape [2, 3, 5].
- On the other hand, setting new_shape as [2, 3, 4] is also an error: The
third dimension is smaller than the original shape [2, 3, 5] (and an
`InvalidArgumentError` will be raised).
- If `new_shape` is None, the returned SparseTensor will have a shape
[2, 3, 4], which is the tight bounding box of `sp_input`.
Args:
sp_input: The input `SparseTensor`.
new_shape: None or a vector representing the new shape for the returned
`SpraseTensor`.
Returns:
A `SparseTensor` indices and values unchanged from `input_sp`. Its shape is
`new_shape` if that is set. Otherwise it is the tight bounding box of
`input_sp`
Raises:
TypeError: If `sp_input` is not a `SparseTensor`.
ValueError: If `new_shape` represents a tensor with a different rank from
that of `sp_input` (if shapes are known when graph is constructed).
OpError:
- If `new_shape` has dimension sizes that are too small.
- If shapes are not known during graph construction time, and during run
time it is found out that the ranks do not match.
"""
if not isinstance(sp_input, ops.SparseTensor):
raise TypeError("Input must be a SparseTensor")
in_indices = array_ops.identity(sp_input.indices)
in_values = array_ops.identity(sp_input.values)
in_shape = array_ops.identity(sp_input.shape)
if new_shape is None:
dim_low_bound = math_ops.reduce_max(in_indices, 0)
output_shape_tensor = math_ops.add(dim_low_bound,
array_ops.ones_like(in_shape))
else:
output_shape_tensor = ops.convert_to_tensor(new_shape)
output_shape_tensor.get_shape().assert_has_rank(1)
output_shape_tensor = math_ops.cast(output_shape_tensor, dtypes.int64)
# For cases when shape is known during graph construction, this catches the
# error before the ops.SparseTensor catches it.
output_shape_tensor.get_shape()[0].merge_with(in_shape.get_shape()[0])
# For cases where shape is not known during graph construction.
output_shape_tensor = control_flow_ops.with_dependencies(
[check_ops.assert_equal(array_ops.shape(in_shape),
array_ops.shape(output_shape_tensor))],
output_shape_tensor)
output_shape_tensor = control_flow_ops.with_dependencies(
[check_ops.assert_less_equal(in_shape, output_shape_tensor)],
output_shape_tensor)
return ops.SparseTensor(in_indices, in_values, output_shape_tensor) | [
"def",
"sparse_reset_shape",
"(",
"sp_input",
",",
"new_shape",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"sp_input",
",",
"ops",
".",
"SparseTensor",
")",
":",
"raise",
"TypeError",
"(",
"\"Input must be a SparseTensor\"",
")",
"in_indices",
"=",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/sparse_ops.py#L929-L1011 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.