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/lite/python/wrap_toco.py | python | wrapped_toco_convert | (model_flags_str, toco_flags_str, input_data_str,
debug_info_str, enable_mlir_converter) | return _pywrap_toco_api.TocoConvert(
model_flags_str,
toco_flags_str,
input_data_str,
False, # extended_return
debug_info_str,
enable_mlir_converter) | Wraps TocoConvert with lazy loader. | Wraps TocoConvert with lazy loader. | [
"Wraps",
"TocoConvert",
"with",
"lazy",
"loader",
"."
] | def wrapped_toco_convert(model_flags_str, toco_flags_str, input_data_str,
debug_info_str, enable_mlir_converter):
"""Wraps TocoConvert with lazy loader."""
return _pywrap_toco_api.TocoConvert(
model_flags_str,
toco_flags_str,
input_data_str,
False, # extended_return
debug_info_str,
enable_mlir_converter) | [
"def",
"wrapped_toco_convert",
"(",
"model_flags_str",
",",
"toco_flags_str",
",",
"input_data_str",
",",
"debug_info_str",
",",
"enable_mlir_converter",
")",
":",
"return",
"_pywrap_toco_api",
".",
"TocoConvert",
"(",
"model_flags_str",
",",
"toco_flags_str",
",",
"input_data_str",
",",
"False",
",",
"# extended_return",
"debug_info_str",
",",
"enable_mlir_converter",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/wrap_toco.py#L24-L33 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/mime/application.py | python | MIMEApplication.__init__ | (self, _data, _subtype='octet-stream',
_encoder=encoders.encode_base64, *, policy=None, **_params) | Create an application/* type MIME document.
_data is a string containing the raw application data.
_subtype is the MIME content type subtype, defaulting to
'octet-stream'.
_encoder is a function which will perform the actual encoding for
transport of the application data, defaulting to base64 encoding.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header. | Create an application/* type MIME document. | [
"Create",
"an",
"application",
"/",
"*",
"type",
"MIME",
"document",
"."
] | def __init__(self, _data, _subtype='octet-stream',
_encoder=encoders.encode_base64, *, policy=None, **_params):
"""Create an application/* type MIME document.
_data is a string containing the raw application data.
_subtype is the MIME content type subtype, defaulting to
'octet-stream'.
_encoder is a function which will perform the actual encoding for
transport of the application data, defaulting to base64 encoding.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
raise TypeError('Invalid application MIME subtype')
MIMENonMultipart.__init__(self, 'application', _subtype, policy=policy,
**_params)
self.set_payload(_data)
_encoder(self) | [
"def",
"__init__",
"(",
"self",
",",
"_data",
",",
"_subtype",
"=",
"'octet-stream'",
",",
"_encoder",
"=",
"encoders",
".",
"encode_base64",
",",
"*",
",",
"policy",
"=",
"None",
",",
"*",
"*",
"_params",
")",
":",
"if",
"_subtype",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Invalid application MIME subtype'",
")",
"MIMENonMultipart",
".",
"__init__",
"(",
"self",
",",
"'application'",
",",
"_subtype",
",",
"policy",
"=",
"policy",
",",
"*",
"*",
"_params",
")",
"self",
".",
"set_payload",
"(",
"_data",
")",
"_encoder",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/mime/application.py#L16-L37 | ||
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | vtr_flow/scripts/python_libs/vtr/util.py | python | get_next_run_dir | (base_dir) | return str(PurePath(base_dir) / run_dir_name(get_next_run_number(base_dir))) | Returns the next unused run directory within base_dir.
Does not create the directory | Returns the next unused run directory within base_dir. | [
"Returns",
"the",
"next",
"unused",
"run",
"directory",
"within",
"base_dir",
"."
] | def get_next_run_dir(base_dir):
"""
Returns the next unused run directory within base_dir.
Does not create the directory
"""
return str(PurePath(base_dir) / run_dir_name(get_next_run_number(base_dir))) | [
"def",
"get_next_run_dir",
"(",
"base_dir",
")",
":",
"return",
"str",
"(",
"PurePath",
"(",
"base_dir",
")",
"/",
"run_dir_name",
"(",
"get_next_run_number",
"(",
"base_dir",
")",
")",
")"
] | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/util.py#L444-L450 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/settings2.py | python | Settings._getState | (self) | return self._stateBuffer | Gets the buffered state rather than asking its parent for its state. | Gets the buffered state rather than asking its parent for its state. | [
"Gets",
"the",
"buffered",
"state",
"rather",
"than",
"asking",
"its",
"parent",
"for",
"its",
"state",
"."
] | def _getState(self):
"""Gets the buffered state rather than asking its parent for its state.
"""
return self._stateBuffer | [
"def",
"_getState",
"(",
"self",
")",
":",
"return",
"self",
".",
"_stateBuffer"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/settings2.py#L241-L244 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py | python | check_input_files_for_variadic_seq | (headerDir, sourceDir) | return False | Checks if files, used as input when pre-processing MPL-containers in their variadic form, need fixing. | Checks if files, used as input when pre-processing MPL-containers in their variadic form, need fixing. | [
"Checks",
"if",
"files",
"used",
"as",
"input",
"when",
"pre",
"-",
"processing",
"MPL",
"-",
"containers",
"in",
"their",
"variadic",
"form",
"need",
"fixing",
"."
] | def check_input_files_for_variadic_seq(headerDir, sourceDir):
"""Checks if files, used as input when pre-processing MPL-containers in their variadic form, need fixing."""
# Check input files in include/source-directories.
files = glob.glob( os.path.join( headerDir, "*.hpp" ) )
files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) )
files += glob.glob( os.path.join( sourceDir, "src", "*" ) )
for currentFile in sorted( files ):
if check_header_comment( currentFile ):
return True
return False | [
"def",
"check_input_files_for_variadic_seq",
"(",
"headerDir",
",",
"sourceDir",
")",
":",
"# Check input files in include/source-directories.",
"files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"headerDir",
",",
"\"*.hpp\"",
")",
")",
"files",
"+=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"headerDir",
",",
"\"aux_\"",
",",
"\"*.hpp\"",
")",
")",
"files",
"+=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sourceDir",
",",
"\"src\"",
",",
"\"*\"",
")",
")",
"for",
"currentFile",
"in",
"sorted",
"(",
"files",
")",
":",
"if",
"check_header_comment",
"(",
"currentFile",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/libs/mpl/preprocessed/fix_boost_mpl_preprocess.py#L39-L48 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_impl.py | python | sampled_softmax_loss | (weights,
biases,
labels,
inputs,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
remove_accidental_hits=True,
partition_strategy="mod",
name="sampled_softmax_loss",
seed=None) | return sampled_losses | Computes and returns the sampled softmax training loss.
This is a faster way to train a softmax classifier over a huge number of
classes.
This operation is for training only. It is generally an underestimate of
the full softmax loss.
A common use case is to use this method for training, and calculate the full
softmax loss for evaluation or inference. In this case, you must set
`partition_strategy="div"` for the two losses to be consistent, as in the
following example:
```python
if mode == "train":
loss = tf.nn.sampled_softmax_loss(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
...,
partition_strategy="div")
elif mode == "eval":
logits = tf.matmul(inputs, tf.transpose(weights))
logits = tf.nn.bias_add(logits, biases)
labels_one_hot = tf.one_hot(labels, n_classes)
loss = tf.nn.softmax_cross_entropy_with_logits(
labels=labels_one_hot,
logits=logits)
```
See our [Candidate Sampling Algorithms Reference]
(https://www.tensorflow.org/extras/candidate_sampling.pdf)
Also see Section 3 of [Jean et al., 2014](http://arxiv.org/abs/1412.2007)
([pdf](http://arxiv.org/pdf/1412.2007.pdf)) for the math.
Args:
weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`
objects whose concatenation along dimension 0 has shape
[num_classes, dim]. The (possibly-sharded) class embeddings.
biases: A `Tensor` of shape `[num_classes]`. The class biases.
labels: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes. Note that this format differs from
the `labels` argument of `nn.softmax_cross_entropy_with_logits`.
inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
activations of the input network.
num_sampled: An `int`. The number of classes to randomly sample per batch.
num_classes: An `int`. The number of possible classes.
num_true: An `int`. The number of target classes per training example.
sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
`sampled_expected_count`) returned by a `*_candidate_sampler` function.
(if None, we default to `log_uniform_candidate_sampler`)
remove_accidental_hits: A `bool`. whether to remove "accidental hits"
where a sampled class equals one of the target classes. Default is
True.
partition_strategy: A string specifying the partitioning strategy, relevant
if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
Default is `"mod"`. See `tf.nn.embedding_lookup` for more details.
name: A name for the operation (optional).
seed: random seed for candidate sampling. Default to None, which doesn't set
the op-level random seed for candidate sampling.
Returns:
A `batch_size` 1-D tensor of per-example sampled softmax losses. | Computes and returns the sampled softmax training loss. | [
"Computes",
"and",
"returns",
"the",
"sampled",
"softmax",
"training",
"loss",
"."
] | def sampled_softmax_loss(weights,
biases,
labels,
inputs,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
remove_accidental_hits=True,
partition_strategy="mod",
name="sampled_softmax_loss",
seed=None):
"""Computes and returns the sampled softmax training loss.
This is a faster way to train a softmax classifier over a huge number of
classes.
This operation is for training only. It is generally an underestimate of
the full softmax loss.
A common use case is to use this method for training, and calculate the full
softmax loss for evaluation or inference. In this case, you must set
`partition_strategy="div"` for the two losses to be consistent, as in the
following example:
```python
if mode == "train":
loss = tf.nn.sampled_softmax_loss(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
...,
partition_strategy="div")
elif mode == "eval":
logits = tf.matmul(inputs, tf.transpose(weights))
logits = tf.nn.bias_add(logits, biases)
labels_one_hot = tf.one_hot(labels, n_classes)
loss = tf.nn.softmax_cross_entropy_with_logits(
labels=labels_one_hot,
logits=logits)
```
See our [Candidate Sampling Algorithms Reference]
(https://www.tensorflow.org/extras/candidate_sampling.pdf)
Also see Section 3 of [Jean et al., 2014](http://arxiv.org/abs/1412.2007)
([pdf](http://arxiv.org/pdf/1412.2007.pdf)) for the math.
Args:
weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`
objects whose concatenation along dimension 0 has shape
[num_classes, dim]. The (possibly-sharded) class embeddings.
biases: A `Tensor` of shape `[num_classes]`. The class biases.
labels: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes. Note that this format differs from
the `labels` argument of `nn.softmax_cross_entropy_with_logits`.
inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
activations of the input network.
num_sampled: An `int`. The number of classes to randomly sample per batch.
num_classes: An `int`. The number of possible classes.
num_true: An `int`. The number of target classes per training example.
sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
`sampled_expected_count`) returned by a `*_candidate_sampler` function.
(if None, we default to `log_uniform_candidate_sampler`)
remove_accidental_hits: A `bool`. whether to remove "accidental hits"
where a sampled class equals one of the target classes. Default is
True.
partition_strategy: A string specifying the partitioning strategy, relevant
if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
Default is `"mod"`. See `tf.nn.embedding_lookup` for more details.
name: A name for the operation (optional).
seed: random seed for candidate sampling. Default to None, which doesn't set
the op-level random seed for candidate sampling.
Returns:
A `batch_size` 1-D tensor of per-example sampled softmax losses.
"""
logits, labels = _compute_sampled_logits(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
num_sampled=num_sampled,
num_classes=num_classes,
num_true=num_true,
sampled_values=sampled_values,
subtract_log_q=True,
remove_accidental_hits=remove_accidental_hits,
partition_strategy=partition_strategy,
name=name,
seed=seed)
labels = array_ops.stop_gradient(labels, name="labels_stop_gradient")
sampled_losses = nn_ops.softmax_cross_entropy_with_logits_v2(
labels=labels, logits=logits)
# sampled_losses is a [batch_size] tensor.
return sampled_losses | [
"def",
"sampled_softmax_loss",
"(",
"weights",
",",
"biases",
",",
"labels",
",",
"inputs",
",",
"num_sampled",
",",
"num_classes",
",",
"num_true",
"=",
"1",
",",
"sampled_values",
"=",
"None",
",",
"remove_accidental_hits",
"=",
"True",
",",
"partition_strategy",
"=",
"\"mod\"",
",",
"name",
"=",
"\"sampled_softmax_loss\"",
",",
"seed",
"=",
"None",
")",
":",
"logits",
",",
"labels",
"=",
"_compute_sampled_logits",
"(",
"weights",
"=",
"weights",
",",
"biases",
"=",
"biases",
",",
"labels",
"=",
"labels",
",",
"inputs",
"=",
"inputs",
",",
"num_sampled",
"=",
"num_sampled",
",",
"num_classes",
"=",
"num_classes",
",",
"num_true",
"=",
"num_true",
",",
"sampled_values",
"=",
"sampled_values",
",",
"subtract_log_q",
"=",
"True",
",",
"remove_accidental_hits",
"=",
"remove_accidental_hits",
",",
"partition_strategy",
"=",
"partition_strategy",
",",
"name",
"=",
"name",
",",
"seed",
"=",
"seed",
")",
"labels",
"=",
"array_ops",
".",
"stop_gradient",
"(",
"labels",
",",
"name",
"=",
"\"labels_stop_gradient\"",
")",
"sampled_losses",
"=",
"nn_ops",
".",
"softmax_cross_entropy_with_logits_v2",
"(",
"labels",
"=",
"labels",
",",
"logits",
"=",
"logits",
")",
"# sampled_losses is a [batch_size] tensor.",
"return",
"sampled_losses"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_impl.py#L2120-L2217 | |
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/automate/automate-git.py | python | log_chromium_changes | () | Evaluate the Chromium checkout for changes. | Evaluate the Chromium checkout for changes. | [
"Evaluate",
"the",
"Chromium",
"checkout",
"for",
"changes",
"."
] | def log_chromium_changes():
""" Evaluate the Chromium checkout for changes. """
config = read_update_file()
if config is None:
msg("Skipping Chromium changes log.")
return
if 'files' in config:
out_file = os.path.join(download_dir, 'chromium_update_changes.diff')
if os.path.exists(out_file):
os.remove(out_file)
old_commit = get_chromium_main_commit(
get_chromium_main_position(chromium_compat_version))
new_commit = get_chromium_main_commit(
get_chromium_main_position(chromium_checkout))
cmd = '%s diff --relative --no-prefix %s..%s -- %s' % (
git_exe, old_commit, new_commit, ' '.join(config['files']))
result = exec_cmd(cmd, chromium_src_dir)
if result['out'] != '':
write_file(out_file, result['out']) | [
"def",
"log_chromium_changes",
"(",
")",
":",
"config",
"=",
"read_update_file",
"(",
")",
"if",
"config",
"is",
"None",
":",
"msg",
"(",
"\"Skipping Chromium changes log.\"",
")",
"return",
"if",
"'files'",
"in",
"config",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"download_dir",
",",
"'chromium_update_changes.diff'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"out_file",
")",
":",
"os",
".",
"remove",
"(",
"out_file",
")",
"old_commit",
"=",
"get_chromium_main_commit",
"(",
"get_chromium_main_position",
"(",
"chromium_compat_version",
")",
")",
"new_commit",
"=",
"get_chromium_main_commit",
"(",
"get_chromium_main_position",
"(",
"chromium_checkout",
")",
")",
"cmd",
"=",
"'%s diff --relative --no-prefix %s..%s -- %s'",
"%",
"(",
"git_exe",
",",
"old_commit",
",",
"new_commit",
",",
"' '",
".",
"join",
"(",
"config",
"[",
"'files'",
"]",
")",
")",
"result",
"=",
"exec_cmd",
"(",
"cmd",
",",
"chromium_src_dir",
")",
"if",
"result",
"[",
"'out'",
"]",
"!=",
"''",
":",
"write_file",
"(",
"out_file",
",",
"result",
"[",
"'out'",
"]",
")"
] | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/automate/automate-git.py#L507-L528 | ||
mitmedialab/Junkyard-Jumbotron | 7e32ecc8a01ea5a578fea6ea54f1f44c7f8f546e | python/artoolkit.py | python | main | (argv) | return 0 | Perform detection from the command line.
Usage: python artoolkit.py <image_name> | Perform detection from the command line.
Usage: python artoolkit.py <image_name> | [
"Perform",
"detection",
"from",
"the",
"command",
"line",
".",
"Usage",
":",
"python",
"artoolkit",
".",
"py",
"<image_name",
">"
] | def main(argv):
"""Perform detection from the command line.
Usage: python artoolkit.py <image_name>"""
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
if argv[1] == "-makeMarkers":
for i in xrange(-1, 4095):
if (i % 10) == 0:
print i
get_marker_image(i)
return 0
image = Image.open(argv[1])
#image = core.reorient_image(image);
if image.mode != 'RGB' or image.mode != 'RGBA':
image = image.convert('RGB')
markers = detect(image, debug=True, debug_image=image)
image.save("artoolkit_out.jpg")
return 0 | [
"def",
"main",
"(",
"argv",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"format",
"=",
"\"%(message)s\"",
")",
"if",
"argv",
"[",
"1",
"]",
"==",
"\"-makeMarkers\"",
":",
"for",
"i",
"in",
"xrange",
"(",
"-",
"1",
",",
"4095",
")",
":",
"if",
"(",
"i",
"%",
"10",
")",
"==",
"0",
":",
"print",
"i",
"get_marker_image",
"(",
"i",
")",
"return",
"0",
"image",
"=",
"Image",
".",
"open",
"(",
"argv",
"[",
"1",
"]",
")",
"#image = core.reorient_image(image);",
"if",
"image",
".",
"mode",
"!=",
"'RGB'",
"or",
"image",
".",
"mode",
"!=",
"'RGBA'",
":",
"image",
"=",
"image",
".",
"convert",
"(",
"'RGB'",
")",
"markers",
"=",
"detect",
"(",
"image",
",",
"debug",
"=",
"True",
",",
"debug_image",
"=",
"image",
")",
"image",
".",
"save",
"(",
"\"artoolkit_out.jpg\"",
")",
"return",
"0"
] | https://github.com/mitmedialab/Junkyard-Jumbotron/blob/7e32ecc8a01ea5a578fea6ea54f1f44c7f8f546e/python/artoolkit.py#L200-L220 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py | python | Node.get_build_scanner_path | (self, scanner) | return self.get_executor().get_build_scanner_path(scanner) | Fetch the appropriate scanner path for this node. | Fetch the appropriate scanner path for this node. | [
"Fetch",
"the",
"appropriate",
"scanner",
"path",
"for",
"this",
"node",
"."
] | def get_build_scanner_path(self, scanner):
"""Fetch the appropriate scanner path for this node."""
return self.get_executor().get_build_scanner_path(scanner) | [
"def",
"get_build_scanner_path",
"(",
"self",
",",
"scanner",
")",
":",
"return",
"self",
".",
"get_executor",
"(",
")",
".",
"get_build_scanner_path",
"(",
"scanner",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py#L617-L619 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/input.py | python | GetIncludedBuildFiles | (build_file_path, aux_data, included=None) | return included | Return a list of all build files included into build_file_path.
The returned list will contain build_file_path as well as all other files
that it included, either directly or indirectly. Note that the list may
contain files that were included into a conditional section that evaluated
to false and was not merged into build_file_path's dict.
aux_data is a dict containing a key for each build file or included build
file. Those keys provide access to dicts whose "included" keys contain
lists of all other files included by the build file.
included should be left at its default None value by external callers. It
is used for recursion.
The returned list will not contain any duplicate entries. Each build file
in the list will be relative to the current directory. | Return a list of all build files included into build_file_path. | [
"Return",
"a",
"list",
"of",
"all",
"build",
"files",
"included",
"into",
"build_file_path",
"."
] | def GetIncludedBuildFiles(build_file_path, aux_data, included=None):
"""Return a list of all build files included into build_file_path.
The returned list will contain build_file_path as well as all other files
that it included, either directly or indirectly. Note that the list may
contain files that were included into a conditional section that evaluated
to false and was not merged into build_file_path's dict.
aux_data is a dict containing a key for each build file or included build
file. Those keys provide access to dicts whose "included" keys contain
lists of all other files included by the build file.
included should be left at its default None value by external callers. It
is used for recursion.
The returned list will not contain any duplicate entries. Each build file
in the list will be relative to the current directory.
"""
if included is None:
included = []
if build_file_path in included:
return included
included.append(build_file_path)
for included_build_file in aux_data[build_file_path].get('included', []):
GetIncludedBuildFiles(included_build_file, aux_data, included)
return included | [
"def",
"GetIncludedBuildFiles",
"(",
"build_file_path",
",",
"aux_data",
",",
"included",
"=",
"None",
")",
":",
"if",
"included",
"is",
"None",
":",
"included",
"=",
"[",
"]",
"if",
"build_file_path",
"in",
"included",
":",
"return",
"included",
"included",
".",
"append",
"(",
"build_file_path",
")",
"for",
"included_build_file",
"in",
"aux_data",
"[",
"build_file_path",
"]",
".",
"get",
"(",
"'included'",
",",
"[",
"]",
")",
":",
"GetIncludedBuildFiles",
"(",
"included_build_file",
",",
"aux_data",
",",
"included",
")",
"return",
"included"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/input.py#L142-L172 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/shortcuteditor.py | python | Shortcut.GetId | (self) | return self.accelId | Returns this :class:`Shortcut` ID. | Returns this :class:`Shortcut` ID. | [
"Returns",
"this",
":",
"class",
":",
"Shortcut",
"ID",
"."
] | def GetId(self):
""" Returns this :class:`Shortcut` ID. """
if self.menuItem is not None:
if isinstance(self.menuItem, wx.Menu):
return 1
return self.menuItem.GetId()
return self.accelId | [
"def",
"GetId",
"(",
"self",
")",
":",
"if",
"self",
".",
"menuItem",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"menuItem",
",",
"wx",
".",
"Menu",
")",
":",
"return",
"1",
"return",
"self",
".",
"menuItem",
".",
"GetId",
"(",
")",
"return",
"self",
".",
"accelId"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/shortcuteditor.py#L1484-L1492 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Alignment/MuonAlignment/python/svgfig.py | python | Ticks.compute_logminiticks | (self, base) | Return optimal logarithmic miniticks, given a set of ticks.
Normally only used internally. | Return optimal logarithmic miniticks, given a set of ticks. | [
"Return",
"optimal",
"logarithmic",
"miniticks",
"given",
"a",
"set",
"of",
"ticks",
"."
] | def compute_logminiticks(self, base):
"""Return optimal logarithmic miniticks, given a set of ticks.
Normally only used internally.
"""
if self.low >= self.high: raise ValueError("low must be less than high")
lowN = math.floor(math.log(self.low, base))
highN = math.ceil(math.log(self.high, base))
output = []
num_ticks = 0
for n in range(int(lowN), int(highN)+1):
x = base**n
if self.low <= x <= self.high: num_ticks += 1
for m in range(2, int(math.ceil(base))):
minix = m * x
if self.low <= minix <= self.high: output.append(minix)
if num_ticks <= 2: return []
else: return output | [
"def",
"compute_logminiticks",
"(",
"self",
",",
"base",
")",
":",
"if",
"self",
".",
"low",
">=",
"self",
".",
"high",
":",
"raise",
"ValueError",
"(",
"\"low must be less than high\"",
")",
"lowN",
"=",
"math",
".",
"floor",
"(",
"math",
".",
"log",
"(",
"self",
".",
"low",
",",
"base",
")",
")",
"highN",
"=",
"math",
".",
"ceil",
"(",
"math",
".",
"log",
"(",
"self",
".",
"high",
",",
"base",
")",
")",
"output",
"=",
"[",
"]",
"num_ticks",
"=",
"0",
"for",
"n",
"in",
"range",
"(",
"int",
"(",
"lowN",
")",
",",
"int",
"(",
"highN",
")",
"+",
"1",
")",
":",
"x",
"=",
"base",
"**",
"n",
"if",
"self",
".",
"low",
"<=",
"x",
"<=",
"self",
".",
"high",
":",
"num_ticks",
"+=",
"1",
"for",
"m",
"in",
"range",
"(",
"2",
",",
"int",
"(",
"math",
".",
"ceil",
"(",
"base",
")",
")",
")",
":",
"minix",
"=",
"m",
"*",
"x",
"if",
"self",
".",
"low",
"<=",
"minix",
"<=",
"self",
".",
"high",
":",
"output",
".",
"append",
"(",
"minix",
")",
"if",
"num_ticks",
"<=",
"2",
":",
"return",
"[",
"]",
"else",
":",
"return",
"output"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MuonAlignment/python/svgfig.py#L2768-L2787 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/pty.py | python | spawn | (argv, master_read=_read, stdin_read=_read) | Create a spawned process. | Create a spawned process. | [
"Create",
"a",
"spawned",
"process",
"."
] | def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except (IOError, OSError):
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd) | [
"def",
"spawn",
"(",
"argv",
",",
"master_read",
"=",
"_read",
",",
"stdin_read",
"=",
"_read",
")",
":",
"if",
"type",
"(",
"argv",
")",
"==",
"type",
"(",
"''",
")",
":",
"argv",
"=",
"(",
"argv",
",",
")",
"pid",
",",
"master_fd",
"=",
"fork",
"(",
")",
"if",
"pid",
"==",
"CHILD",
":",
"os",
".",
"execlp",
"(",
"argv",
"[",
"0",
"]",
",",
"*",
"argv",
")",
"try",
":",
"mode",
"=",
"tty",
".",
"tcgetattr",
"(",
"STDIN_FILENO",
")",
"tty",
".",
"setraw",
"(",
"STDIN_FILENO",
")",
"restore",
"=",
"1",
"except",
"tty",
".",
"error",
":",
"# This is the same as termios.error",
"restore",
"=",
"0",
"try",
":",
"_copy",
"(",
"master_fd",
",",
"master_read",
",",
"stdin_read",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"if",
"restore",
":",
"tty",
".",
"tcsetattr",
"(",
"STDIN_FILENO",
",",
"tty",
".",
"TCSAFLUSH",
",",
"mode",
")",
"os",
".",
"close",
"(",
"master_fd",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pty.py#L161-L180 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_ui.py | python | UI.__init__ | (self) | Declare UI state variables | Declare UI state variables | [
"Declare",
"UI",
"state",
"variables"
] | def __init__(self):
""" Declare UI state variables """
# Default panes to display
self.defaultPanes = [
'breakpoints',
'backtrace',
'locals',
'threads',
'registers',
'disassembly']
# map of tuples (filename, line) --> SBBreakpoint
self.markedBreakpoints = {}
# Currently shown signs
self.breakpointSigns = {}
self.pcSigns = []
# Container for panes
self.paneCol = PaneLayout()
# All possible LLDB panes
self.backtracePane = BacktracePane(self.paneCol)
self.threadPane = ThreadPane(self.paneCol)
self.disassemblyPane = DisassemblyPane(self.paneCol)
self.localsPane = LocalsPane(self.paneCol)
self.registersPane = RegistersPane(self.paneCol)
self.breakPane = BreakpointsPane(self.paneCol) | [
"def",
"__init__",
"(",
"self",
")",
":",
"# Default panes to display",
"self",
".",
"defaultPanes",
"=",
"[",
"'breakpoints'",
",",
"'backtrace'",
",",
"'locals'",
",",
"'threads'",
",",
"'registers'",
",",
"'disassembly'",
"]",
"# map of tuples (filename, line) --> SBBreakpoint",
"self",
".",
"markedBreakpoints",
"=",
"{",
"}",
"# Currently shown signs",
"self",
".",
"breakpointSigns",
"=",
"{",
"}",
"self",
".",
"pcSigns",
"=",
"[",
"]",
"# Container for panes",
"self",
".",
"paneCol",
"=",
"PaneLayout",
"(",
")",
"# All possible LLDB panes",
"self",
".",
"backtracePane",
"=",
"BacktracePane",
"(",
"self",
".",
"paneCol",
")",
"self",
".",
"threadPane",
"=",
"ThreadPane",
"(",
"self",
".",
"paneCol",
")",
"self",
".",
"disassemblyPane",
"=",
"DisassemblyPane",
"(",
"self",
".",
"paneCol",
")",
"self",
".",
"localsPane",
"=",
"LocalsPane",
"(",
"self",
".",
"paneCol",
")",
"self",
".",
"registersPane",
"=",
"RegistersPane",
"(",
"self",
".",
"paneCol",
")",
"self",
".",
"breakPane",
"=",
"BreakpointsPane",
"(",
"self",
".",
"paneCol",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_ui.py#L22-L50 | ||
adnanaziz/epicode | e81d4387d2ae442d21631dfc958690d424e1d84d | cpp/cpplint.py | python | _SetOutputFormat | (output_format) | Sets the module's output format. | Sets the module's output format. | [
"Sets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _SetOutputFormat(output_format):
"""Sets the module's output format."""
_cpplint_state.SetOutputFormat(output_format) | [
"def",
"_SetOutputFormat",
"(",
"output_format",
")",
":",
"_cpplint_state",
".",
"SetOutputFormat",
"(",
"output_format",
")"
] | https://github.com/adnanaziz/epicode/blob/e81d4387d2ae442d21631dfc958690d424e1d84d/cpp/cpplint.py#L576-L578 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xpathParserContext.xpathNextFollowingSibling | (self, cur) | return __tmp | Traversal function for the "following-sibling" direction
The following-sibling axis contains the following siblings
of the context node in document order. | Traversal function for the "following-sibling" direction
The following-sibling axis contains the following siblings
of the context node in document order. | [
"Traversal",
"function",
"for",
"the",
"following",
"-",
"sibling",
"direction",
"The",
"following",
"-",
"sibling",
"axis",
"contains",
"the",
"following",
"siblings",
"of",
"the",
"context",
"node",
"in",
"document",
"order",
"."
] | def xpathNextFollowingSibling(self, cur):
"""Traversal function for the "following-sibling" direction
The following-sibling axis contains the following siblings
of the context node in document order. """
if cur is None: cur__o = None
else: cur__o = cur._o
ret = libxml2mod.xmlXPathNextFollowingSibling(self._o, cur__o)
if ret is None:raise xpathError('xmlXPathNextFollowingSibling() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"xpathNextFollowingSibling",
"(",
"self",
",",
"cur",
")",
":",
"if",
"cur",
"is",
"None",
":",
"cur__o",
"=",
"None",
"else",
":",
"cur__o",
"=",
"cur",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathNextFollowingSibling",
"(",
"self",
".",
"_o",
",",
"cur__o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"xpathError",
"(",
"'xmlXPathNextFollowingSibling() failed'",
")",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L7683-L7692 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_base/geometry.py | python | anglediffs | (a1, a2, deg=False) | return wrapanglediffs(a1 - a2, deg=deg) | Compute the smallest difference between two angle arrays.
Parameters
----------
a1, a2 : np.ndarray
The angle arrays to subtract
deg : bool (default=False)
Whether to compute the difference in degrees or radians
Returns
-------
out : np.ndarray
The difference between a1 and a2 | Compute the smallest difference between two angle arrays.
Parameters
----------
a1, a2 : np.ndarray
The angle arrays to subtract
deg : bool (default=False)
Whether to compute the difference in degrees or radians
Returns
-------
out : np.ndarray
The difference between a1 and a2 | [
"Compute",
"the",
"smallest",
"difference",
"between",
"two",
"angle",
"arrays",
".",
"Parameters",
"----------",
"a1",
"a2",
":",
"np",
".",
"ndarray",
"The",
"angle",
"arrays",
"to",
"subtract",
"deg",
":",
"bool",
"(",
"default",
"=",
"False",
")",
"Whether",
"to",
"compute",
"the",
"difference",
"in",
"degrees",
"or",
"radians",
"Returns",
"-------",
"out",
":",
"np",
".",
"ndarray",
"The",
"difference",
"between",
"a1",
"and",
"a2"
] | def anglediffs(a1, a2, deg=False):
"""Compute the smallest difference between two angle arrays.
Parameters
----------
a1, a2 : np.ndarray
The angle arrays to subtract
deg : bool (default=False)
Whether to compute the difference in degrees or radians
Returns
-------
out : np.ndarray
The difference between a1 and a2
"""
print 'anglediffs', a1, a2
return wrapanglediffs(a1 - a2, deg=deg) | [
"def",
"anglediffs",
"(",
"a1",
",",
"a2",
",",
"deg",
"=",
"False",
")",
":",
"print",
"'anglediffs'",
",",
"a1",
",",
"a2",
"return",
"wrapanglediffs",
"(",
"a1",
"-",
"a2",
",",
"deg",
"=",
"deg",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_base/geometry.py#L619-L633 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/middle/RNNSequenceNormalizeToIE.py | python | RNNSequenceNormalize.squeeze_initial_states | (graph: Graph, match: dict) | Squeeze input initial states of recurrent node to 2-D shape. | Squeeze input initial states of recurrent node to 2-D shape. | [
"Squeeze",
"input",
"initial",
"states",
"of",
"recurrent",
"node",
"to",
"2",
"-",
"D",
"shape",
"."
] | def squeeze_initial_states(graph: Graph, match: dict):
"""
Squeeze input initial states of recurrent node to 2-D shape.
"""
hidden_init_port = 5
cell_init_port = 6
rnn_layer = match['rnn_layer']
# Add input ports to rnn_layer
rnn_layer.add_sequence_of_ports(type='in', rng=range(7))
rnn_layer_name = rnn_layer.soft_get('name', rnn_layer.id)
assert hidden_init_port in rnn_layer.in_nodes()
hidden_size = rnn_layer.hidden_size
shape = Shape(graph, dict(name=rnn_layer_name + '/ShapeOf')).create_node()
rnn_layer.in_port(0).get_source().connect(shape.in_port(0))
batch = node_to_get_shape_value_of_indices(shape, int64_array([rnn_layer.batch_dim]))
new_dim = create_op_node_with_second_input(graph, Concat, second_input_value=int64_array([hidden_size]),
op_attrs=dict(name=rnn_layer_name + '/HiddenStateResizeDim',
in_ports_count=2, axis=0), input_node=batch)
reshape_h = Reshape(graph, dict(name=rnn_layer_name + '/HiddenStateResize', override_output_shape=True)).create_node()
new_dim.out_port(0).connect(reshape_h.in_port(1))
rnn_layer.in_port(hidden_init_port).get_connection().insert_node(reshape_h)
if rnn_layer.op == 'LSTM':
assert cell_init_port in rnn_layer.in_nodes()
reshape_c = Reshape(graph, dict(name=rnn_layer_name + '/CellStateResize', override_output_shape=True)).create_node()
new_dim.out_port(0).connect(reshape_c.in_port(1))
rnn_layer.in_port(cell_init_port).get_connection().insert_node(reshape_c) | [
"def",
"squeeze_initial_states",
"(",
"graph",
":",
"Graph",
",",
"match",
":",
"dict",
")",
":",
"hidden_init_port",
"=",
"5",
"cell_init_port",
"=",
"6",
"rnn_layer",
"=",
"match",
"[",
"'rnn_layer'",
"]",
"# Add input ports to rnn_layer",
"rnn_layer",
".",
"add_sequence_of_ports",
"(",
"type",
"=",
"'in'",
",",
"rng",
"=",
"range",
"(",
"7",
")",
")",
"rnn_layer_name",
"=",
"rnn_layer",
".",
"soft_get",
"(",
"'name'",
",",
"rnn_layer",
".",
"id",
")",
"assert",
"hidden_init_port",
"in",
"rnn_layer",
".",
"in_nodes",
"(",
")",
"hidden_size",
"=",
"rnn_layer",
".",
"hidden_size",
"shape",
"=",
"Shape",
"(",
"graph",
",",
"dict",
"(",
"name",
"=",
"rnn_layer_name",
"+",
"'/ShapeOf'",
")",
")",
".",
"create_node",
"(",
")",
"rnn_layer",
".",
"in_port",
"(",
"0",
")",
".",
"get_source",
"(",
")",
".",
"connect",
"(",
"shape",
".",
"in_port",
"(",
"0",
")",
")",
"batch",
"=",
"node_to_get_shape_value_of_indices",
"(",
"shape",
",",
"int64_array",
"(",
"[",
"rnn_layer",
".",
"batch_dim",
"]",
")",
")",
"new_dim",
"=",
"create_op_node_with_second_input",
"(",
"graph",
",",
"Concat",
",",
"second_input_value",
"=",
"int64_array",
"(",
"[",
"hidden_size",
"]",
")",
",",
"op_attrs",
"=",
"dict",
"(",
"name",
"=",
"rnn_layer_name",
"+",
"'/HiddenStateResizeDim'",
",",
"in_ports_count",
"=",
"2",
",",
"axis",
"=",
"0",
")",
",",
"input_node",
"=",
"batch",
")",
"reshape_h",
"=",
"Reshape",
"(",
"graph",
",",
"dict",
"(",
"name",
"=",
"rnn_layer_name",
"+",
"'/HiddenStateResize'",
",",
"override_output_shape",
"=",
"True",
")",
")",
".",
"create_node",
"(",
")",
"new_dim",
".",
"out_port",
"(",
"0",
")",
".",
"connect",
"(",
"reshape_h",
".",
"in_port",
"(",
"1",
")",
")",
"rnn_layer",
".",
"in_port",
"(",
"hidden_init_port",
")",
".",
"get_connection",
"(",
")",
".",
"insert_node",
"(",
"reshape_h",
")",
"if",
"rnn_layer",
".",
"op",
"==",
"'LSTM'",
":",
"assert",
"cell_init_port",
"in",
"rnn_layer",
".",
"in_nodes",
"(",
")",
"reshape_c",
"=",
"Reshape",
"(",
"graph",
",",
"dict",
"(",
"name",
"=",
"rnn_layer_name",
"+",
"'/CellStateResize'",
",",
"override_output_shape",
"=",
"True",
")",
")",
".",
"create_node",
"(",
")",
"new_dim",
".",
"out_port",
"(",
"0",
")",
".",
"connect",
"(",
"reshape_c",
".",
"in_port",
"(",
"1",
")",
")",
"rnn_layer",
".",
"in_port",
"(",
"cell_init_port",
")",
".",
"get_connection",
"(",
")",
".",
"insert_node",
"(",
"reshape_c",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/middle/RNNSequenceNormalizeToIE.py#L160-L190 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py | python | StreamHandler.__init__ | (self, stream=None) | Initialize the handler.
If stream is not specified, sys.stderr is used. | Initialize the handler. | [
"Initialize",
"the",
"handler",
"."
] | def __init__(self, stream=None):
"""
Initialize the handler.
If stream is not specified, sys.stderr is used.
"""
Handler.__init__(self)
if stream is None:
stream = sys.stderr
self.stream = stream | [
"def",
"__init__",
"(",
"self",
",",
"stream",
"=",
"None",
")",
":",
"Handler",
".",
"__init__",
"(",
"self",
")",
"if",
"stream",
"is",
"None",
":",
"stream",
"=",
"sys",
".",
"stderr",
"self",
".",
"stream",
"=",
"stream"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py#L817-L826 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Scanner/Dir.py | python | DirScanner | (**kw) | return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw) | Return a prototype Scanner instance for scanning
directories for on-disk files | Return a prototype Scanner instance for scanning
directories for on-disk files | [
"Return",
"a",
"prototype",
"Scanner",
"instance",
"for",
"scanning",
"directories",
"for",
"on",
"-",
"disk",
"files"
] | def DirScanner(**kw):
"""Return a prototype Scanner instance for scanning
directories for on-disk files"""
kw['node_factory'] = SCons.Node.FS.Entry
kw['recursive'] = only_dirs
return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw) | [
"def",
"DirScanner",
"(",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"'node_factory'",
"]",
"=",
"SCons",
".",
"Node",
".",
"FS",
".",
"Entry",
"kw",
"[",
"'recursive'",
"]",
"=",
"only_dirs",
"return",
"SCons",
".",
"Scanner",
".",
"Base",
"(",
"scan_on_disk",
",",
"\"DirScanner\"",
",",
"*",
"*",
"kw",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Scanner/Dir.py#L32-L37 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/examples/python/gdbremote.py | python | stop_gdb_log | (debugger, command, result, dict) | Stop logging GDB remote packets to the file that was specified in a call
to "start_gdb_log" and normalize the timestamps to be relative to the first
timestamp in the log file. Also print out statistics for how long each
command took to allow performance bottlenecks to be determined. | Stop logging GDB remote packets to the file that was specified in a call
to "start_gdb_log" and normalize the timestamps to be relative to the first
timestamp in the log file. Also print out statistics for how long each
command took to allow performance bottlenecks to be determined. | [
"Stop",
"logging",
"GDB",
"remote",
"packets",
"to",
"the",
"file",
"that",
"was",
"specified",
"in",
"a",
"call",
"to",
"start_gdb_log",
"and",
"normalize",
"the",
"timestamps",
"to",
"be",
"relative",
"to",
"the",
"first",
"timestamp",
"in",
"the",
"log",
"file",
".",
"Also",
"print",
"out",
"statistics",
"for",
"how",
"long",
"each",
"command",
"took",
"to",
"allow",
"performance",
"bottlenecks",
"to",
"be",
"determined",
"."
] | def stop_gdb_log(debugger, command, result, dict):
'''Stop logging GDB remote packets to the file that was specified in a call
to "start_gdb_log" and normalize the timestamps to be relative to the first
timestamp in the log file. Also print out statistics for how long each
command took to allow performance bottlenecks to be determined.'''
global g_log_file
# Any commands whose names might be followed by more valid C identifier
# characters must be listed here
command_args = shlex.split(command)
usage = "usage: stop_gdb_log [options]"
description = '''The command stops a previously enabled GDB remote packet logging command. Packet logging must have been previously enabled with a call to start_gdb_log.'''
parser = optparse.OptionParser(
description=description,
prog='stop_gdb_log',
usage=usage)
parser.add_option(
'-v',
'--verbose',
action='store_true',
dest='verbose',
help='display verbose debug info',
default=False)
parser.add_option(
'-q',
'--quiet',
action='store_true',
dest='quiet',
help='display verbose debug info',
default=False)
parser.add_option(
'-C',
'--color',
action='store_true',
dest='color',
help='add terminal colors',
default=False)
parser.add_option(
'-c',
'--sort-by-count',
action='store_true',
dest='sort_count',
help='display verbose debug info',
default=False)
parser.add_option(
'-s',
'--symbolicate',
action='store_true',
dest='symbolicate',
help='symbolicate addresses in log using current "lldb.target"',
default=False)
try:
(options, args) = parser.parse_args(command_args)
except:
return
options.colors = TerminalColors(options.color)
options.symbolicator = None
if options.symbolicate:
if lldb.target:
import lldb.utils.symbolication
options.symbolicator = lldb.utils.symbolication.Symbolicator()
options.symbolicator.target = lldb.target
else:
print("error: can't symbolicate without a target")
if not g_log_file:
result.PutCString(
'error: logging must have been previously enabled with a call to "stop_gdb_log"')
elif os.path.exists(g_log_file):
if len(args) == 0:
debugger.HandleCommand('log disable gdb-remote packets')
result.PutCString(
"GDB packet logging disabled. Logged packets are in '%s'" %
g_log_file)
parse_gdb_log_file(g_log_file, options)
else:
result.PutCString(usage)
else:
print('error: the GDB packet log file "%s" does not exist' % g_log_file) | [
"def",
"stop_gdb_log",
"(",
"debugger",
",",
"command",
",",
"result",
",",
"dict",
")",
":",
"global",
"g_log_file",
"# Any commands whose names might be followed by more valid C identifier",
"# characters must be listed here",
"command_args",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"usage",
"=",
"\"usage: stop_gdb_log [options]\"",
"description",
"=",
"'''The command stops a previously enabled GDB remote packet logging command. Packet logging must have been previously enabled with a call to start_gdb_log.'''",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"description",
"=",
"description",
",",
"prog",
"=",
"'stop_gdb_log'",
",",
"usage",
"=",
"usage",
")",
"parser",
".",
"add_option",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'verbose'",
",",
"help",
"=",
"'display verbose debug info'",
",",
"default",
"=",
"False",
")",
"parser",
".",
"add_option",
"(",
"'-q'",
",",
"'--quiet'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'quiet'",
",",
"help",
"=",
"'display verbose debug info'",
",",
"default",
"=",
"False",
")",
"parser",
".",
"add_option",
"(",
"'-C'",
",",
"'--color'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'color'",
",",
"help",
"=",
"'add terminal colors'",
",",
"default",
"=",
"False",
")",
"parser",
".",
"add_option",
"(",
"'-c'",
",",
"'--sort-by-count'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'sort_count'",
",",
"help",
"=",
"'display verbose debug info'",
",",
"default",
"=",
"False",
")",
"parser",
".",
"add_option",
"(",
"'-s'",
",",
"'--symbolicate'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'symbolicate'",
",",
"help",
"=",
"'symbolicate addresses in log using current \"lldb.target\"'",
",",
"default",
"=",
"False",
")",
"try",
":",
"(",
"options",
",",
"args",
")",
"=",
"parser",
".",
"parse_args",
"(",
"command_args",
")",
"except",
":",
"return",
"options",
".",
"colors",
"=",
"TerminalColors",
"(",
"options",
".",
"color",
")",
"options",
".",
"symbolicator",
"=",
"None",
"if",
"options",
".",
"symbolicate",
":",
"if",
"lldb",
".",
"target",
":",
"import",
"lldb",
".",
"utils",
".",
"symbolication",
"options",
".",
"symbolicator",
"=",
"lldb",
".",
"utils",
".",
"symbolication",
".",
"Symbolicator",
"(",
")",
"options",
".",
"symbolicator",
".",
"target",
"=",
"lldb",
".",
"target",
"else",
":",
"print",
"(",
"\"error: can't symbolicate without a target\"",
")",
"if",
"not",
"g_log_file",
":",
"result",
".",
"PutCString",
"(",
"'error: logging must have been previously enabled with a call to \"stop_gdb_log\"'",
")",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"g_log_file",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"debugger",
".",
"HandleCommand",
"(",
"'log disable gdb-remote packets'",
")",
"result",
".",
"PutCString",
"(",
"\"GDB packet logging disabled. Logged packets are in '%s'\"",
"%",
"g_log_file",
")",
"parse_gdb_log_file",
"(",
"g_log_file",
",",
"options",
")",
"else",
":",
"result",
".",
"PutCString",
"(",
"usage",
")",
"else",
":",
"print",
"(",
"'error: the GDB packet log file \"%s\" does not exist'",
"%",
"g_log_file",
")"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/examples/python/gdbremote.py#L241-L318 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_presenter.py | python | BasicFittingPresenter.handle_start_x_updated | (self) | Handle when the start X is changed. | Handle when the start X is changed. | [
"Handle",
"when",
"the",
"start",
"X",
"is",
"changed",
"."
] | def handle_start_x_updated(self) -> None:
"""Handle when the start X is changed."""
new_start_x, new_end_x = check_start_x_is_valid(self.model.current_dataset_name, self.view.start_x,
self.view.end_x, self.model.current_start_x)
self.update_start_and_end_x_in_view_and_model(new_start_x, new_end_x) | [
"def",
"handle_start_x_updated",
"(",
"self",
")",
"->",
"None",
":",
"new_start_x",
",",
"new_end_x",
"=",
"check_start_x_is_valid",
"(",
"self",
".",
"model",
".",
"current_dataset_name",
",",
"self",
".",
"view",
".",
"start_x",
",",
"self",
".",
"view",
".",
"end_x",
",",
"self",
".",
"model",
".",
"current_start_x",
")",
"self",
".",
"update_start_and_end_x_in_view_and_model",
"(",
"new_start_x",
",",
"new_end_x",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_presenter.py#L310-L314 | ||
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/ContactStructuralMechanicsApplication/python_scripts/contact_remesh_mmg_process.py | python | ContactRemeshMmgProcess._AuxiliarCallsAfterRemesh | (self) | This method is executed right after execute the remesh
Keyword arguments:
self -- It signifies an instance of a class. | This method is executed right after execute the remesh | [
"This",
"method",
"is",
"executed",
"right",
"after",
"execute",
"the",
"remesh"
] | def _AuxiliarCallsAfterRemesh(self):
""" This method is executed right after execute the remesh
Keyword arguments:
self -- It signifies an instance of a class.
"""
KratosMultiphysics.FastTransferBetweenModelPartsProcess(self.main_model_part, self.main_model_part.GetParentModelPart()).Execute() | [
"def",
"_AuxiliarCallsAfterRemesh",
"(",
"self",
")",
":",
"KratosMultiphysics",
".",
"FastTransferBetweenModelPartsProcess",
"(",
"self",
".",
"main_model_part",
",",
"self",
".",
"main_model_part",
".",
"GetParentModelPart",
"(",
")",
")",
".",
"Execute",
"(",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ContactStructuralMechanicsApplication/python_scripts/contact_remesh_mmg_process.py#L402-L408 | ||
alexgkendall/caffe-posenet | 62aafbd7c45df91acdba14f5d1406d8295c2bc6f | scripts/cpp_lint.py | python | FileInfo.Extension | (self) | return self.Split()[2] | File extension - text following the final period. | File extension - text following the final period. | [
"File",
"extension",
"-",
"text",
"following",
"the",
"final",
"period",
"."
] | def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2] | [
"def",
"Extension",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"2",
"]"
] | https://github.com/alexgkendall/caffe-posenet/blob/62aafbd7c45df91acdba14f5d1406d8295c2bc6f/scripts/cpp_lint.py#L948-L950 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unicode_support.py | python | _Py_ISALPHA | (ch) | return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.ALPHA | Equivalent to the CPython macro `Py_ISALPHA()` | Equivalent to the CPython macro `Py_ISALPHA()` | [
"Equivalent",
"to",
"the",
"CPython",
"macro",
"Py_ISALPHA",
"()"
] | def _Py_ISALPHA(ch):
"""
Equivalent to the CPython macro `Py_ISALPHA()`
"""
return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.ALPHA | [
"def",
"_Py_ISALPHA",
"(",
"ch",
")",
":",
"return",
"_Py_ctype_table",
"[",
"_Py_CHARMASK",
"(",
"ch",
")",
"]",
"&",
"_PY_CTF",
".",
"ALPHA"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unicode_support.py#L695-L699 | |
AojunZhou/Incremental-Network-Quantization | c7f6a609d5817d8424ce224209cf4c50f1e4de50 | scripts/cpp_lint.py | python | ParseNolintSuppressions | (filename, raw_line, linenum, error) | Updates the global list of error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of the input file.
raw_line: str, the line of input text, with comments.
linenum: int, the number of the current line.
error: function, an error handler. | Updates the global list of error-suppressions. | [
"Updates",
"the",
"global",
"list",
"of",
"error",
"-",
"suppressions",
"."
] | def ParseNolintSuppressions(filename, raw_line, linenum, error):
"""Updates the global list of error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of the input file.
raw_line: str, the line of input text, with comments.
linenum: int, the number of the current line.
error: function, an error handler.
"""
# FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
matched = _RE_SUPPRESSION.search(raw_line)
if matched:
if matched.group(1) == '_NEXT_LINE':
linenum += 1
category = matched.group(2)
if category in (None, '(*)'): # => "suppress all"
_error_suppressions.setdefault(None, set()).add(linenum)
else:
if category.startswith('(') and category.endswith(')'):
category = category[1:-1]
if category in _ERROR_CATEGORIES:
_error_suppressions.setdefault(category, set()).add(linenum)
else:
error(filename, linenum, 'readability/nolint', 5,
'Unknown NOLINT error category: %s' % category) | [
"def",
"ParseNolintSuppressions",
"(",
"filename",
",",
"raw_line",
",",
"linenum",
",",
"error",
")",
":",
"# FIXME(adonovan): \"NOLINT(\" is misparsed as NOLINT(*).",
"matched",
"=",
"_RE_SUPPRESSION",
".",
"search",
"(",
"raw_line",
")",
"if",
"matched",
":",
"if",
"matched",
".",
"group",
"(",
"1",
")",
"==",
"'_NEXT_LINE'",
":",
"linenum",
"+=",
"1",
"category",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"if",
"category",
"in",
"(",
"None",
",",
"'(*)'",
")",
":",
"# => \"suppress all\"",
"_error_suppressions",
".",
"setdefault",
"(",
"None",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"linenum",
")",
"else",
":",
"if",
"category",
".",
"startswith",
"(",
"'('",
")",
"and",
"category",
".",
"endswith",
"(",
"')'",
")",
":",
"category",
"=",
"category",
"[",
"1",
":",
"-",
"1",
"]",
"if",
"category",
"in",
"_ERROR_CATEGORIES",
":",
"_error_suppressions",
".",
"setdefault",
"(",
"category",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"linenum",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/nolint'",
",",
"5",
",",
"'Unknown NOLINT error category: %s'",
"%",
"category",
")"
] | https://github.com/AojunZhou/Incremental-Network-Quantization/blob/c7f6a609d5817d8424ce224209cf4c50f1e4de50/scripts/cpp_lint.py#L464-L492 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/importer.py | python | _ParseTensorName | (tensor_name) | Parses a tensor name into an operation name and output index.
This function will canonicalize tensor names as follows:
* "foo:0" -> ("foo", 0)
* "foo:7" -> ("foo", 7)
* "foo" -> ("foo", 0)
* "foo:bar:baz" -> ValueError
Args:
tensor_name: The name of a tensor.
Returns:
A tuple containing the operation name, and the output index.
Raises:
ValueError: If `tensor_name' cannot be interpreted as the name of a tensor. | Parses a tensor name into an operation name and output index. | [
"Parses",
"a",
"tensor",
"name",
"into",
"an",
"operation",
"name",
"and",
"output",
"index",
"."
] | def _ParseTensorName(tensor_name):
"""Parses a tensor name into an operation name and output index.
This function will canonicalize tensor names as follows:
* "foo:0" -> ("foo", 0)
* "foo:7" -> ("foo", 7)
* "foo" -> ("foo", 0)
* "foo:bar:baz" -> ValueError
Args:
tensor_name: The name of a tensor.
Returns:
A tuple containing the operation name, and the output index.
Raises:
ValueError: If `tensor_name' cannot be interpreted as the name of a tensor.
"""
components = tensor_name.split(':')
if len(components) == 2:
# Expected format: 'operation_name:output_index'.
try:
output_index = int(components[1])
except ValueError:
raise ValueError('Cannot convert %r to a tensor name.' % (tensor_name,))
return components[0], output_index
elif len(components) == 1:
# Expected format: 'operation_name' (implicit 0th output).
return components[0], 0
else:
raise ValueError('Cannot convert %r to a tensor name.' % (tensor_name,)) | [
"def",
"_ParseTensorName",
"(",
"tensor_name",
")",
":",
"components",
"=",
"tensor_name",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"components",
")",
"==",
"2",
":",
"# Expected format: 'operation_name:output_index'.",
"try",
":",
"output_index",
"=",
"int",
"(",
"components",
"[",
"1",
"]",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'Cannot convert %r to a tensor name.'",
"%",
"(",
"tensor_name",
",",
")",
")",
"return",
"components",
"[",
"0",
"]",
",",
"output_index",
"elif",
"len",
"(",
"components",
")",
"==",
"1",
":",
"# Expected format: 'operation_name' (implicit 0th output).",
"return",
"components",
"[",
"0",
"]",
",",
"0",
"else",
":",
"raise",
"ValueError",
"(",
"'Cannot convert %r to a tensor name.'",
"%",
"(",
"tensor_name",
",",
")",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/importer.py#L89-L120 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/applications/workbench/workbench/projectrecovery/projectrecoverysaver.py | python | ProjectRecoverySaver._empty_group_workspace | (ws) | Check if the workspace is an empty group workspace
:param ws: Workspace; Workspace to check
:return: True if is an empty group workspace | Check if the workspace is an empty group workspace
:param ws: Workspace; Workspace to check
:return: True if is an empty group workspace | [
"Check",
"if",
"the",
"workspace",
"is",
"an",
"empty",
"group",
"workspace",
":",
"param",
"ws",
":",
"Workspace",
";",
"Workspace",
"to",
"check",
":",
"return",
":",
"True",
"if",
"is",
"an",
"empty",
"group",
"workspace"
] | def _empty_group_workspace(ws):
"""
Check if the workspace is an empty group workspace
:param ws: Workspace; Workspace to check
:return: True if is an empty group workspace
"""
if isinstance(ws, WorkspaceGroup) and len(ws.getNames()) == 0:
return True
else:
return False | [
"def",
"_empty_group_workspace",
"(",
"ws",
")",
":",
"if",
"isinstance",
"(",
"ws",
",",
"WorkspaceGroup",
")",
"and",
"len",
"(",
"ws",
".",
"getNames",
"(",
")",
")",
"==",
"0",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/projectrecovery/projectrecoverysaver.py#L145-L154 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/macosxSupport.py | python | tkVersionWarning | (root) | Returns a string warning message if the Tk version in use appears to
be one known to cause problems with IDLE.
1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable.
2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but
can still crash unexpectedly. | Returns a string warning message if the Tk version in use appears to
be one known to cause problems with IDLE.
1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable.
2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but
can still crash unexpectedly. | [
"Returns",
"a",
"string",
"warning",
"message",
"if",
"the",
"Tk",
"version",
"in",
"use",
"appears",
"to",
"be",
"one",
"known",
"to",
"cause",
"problems",
"with",
"IDLE",
".",
"1",
".",
"Apple",
"Cocoa",
"-",
"based",
"Tk",
"8",
".",
"5",
".",
"7",
"shipped",
"with",
"Mac",
"OS",
"X",
"10",
".",
"6",
"is",
"unusable",
".",
"2",
".",
"Apple",
"Cocoa",
"-",
"based",
"Tk",
"8",
".",
"5",
".",
"9",
"in",
"OS",
"X",
"10",
".",
"7",
"and",
"10",
".",
"8",
"is",
"better",
"but",
"can",
"still",
"crash",
"unexpectedly",
"."
] | def tkVersionWarning(root):
"""
Returns a string warning message if the Tk version in use appears to
be one known to cause problems with IDLE.
1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable.
2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but
can still crash unexpectedly.
"""
if (runningAsOSXApp() and
('AppKit' in root.tk.call('winfo', 'server', '.')) ):
patchlevel = root.tk.call('info', 'patchlevel')
if patchlevel not in ('8.5.7', '8.5.9'):
return False
return (r"WARNING: The version of Tcl/Tk ({0}) in use may"
r" be unstable.\n"
r"Visit http://www.python.org/download/mac/tcltk/"
r" for current information.".format(patchlevel))
else:
return False | [
"def",
"tkVersionWarning",
"(",
"root",
")",
":",
"if",
"(",
"runningAsOSXApp",
"(",
")",
"and",
"(",
"'AppKit'",
"in",
"root",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'server'",
",",
"'.'",
")",
")",
")",
":",
"patchlevel",
"=",
"root",
".",
"tk",
".",
"call",
"(",
"'info'",
",",
"'patchlevel'",
")",
"if",
"patchlevel",
"not",
"in",
"(",
"'8.5.7'",
",",
"'8.5.9'",
")",
":",
"return",
"False",
"return",
"(",
"r\"WARNING: The version of Tcl/Tk ({0}) in use may\"",
"r\" be unstable.\\n\"",
"r\"Visit http://www.python.org/download/mac/tcltk/\"",
"r\" for current information.\"",
".",
"format",
"(",
"patchlevel",
")",
")",
"else",
":",
"return",
"False"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/macosxSupport.py#L37-L56 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tarfile.py | python | filemode | (mode) | return stat.filemode(mode) | Deprecated in this location; use stat.filemode. | Deprecated in this location; use stat.filemode. | [
"Deprecated",
"in",
"this",
"location",
";",
"use",
"stat",
".",
"filemode",
"."
] | def filemode(mode):
"""Deprecated in this location; use stat.filemode."""
import warnings
warnings.warn("deprecated in favor of stat.filemode",
DeprecationWarning, 2)
return stat.filemode(mode) | [
"def",
"filemode",
"(",
"mode",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"deprecated in favor of stat.filemode\"",
",",
"DeprecationWarning",
",",
"2",
")",
"return",
"stat",
".",
"filemode",
"(",
"mode",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tarfile.py#L259-L264 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/io/matlab/mio5.py | python | MatFile5Reader.read_var_header | (self) | return header, next_pos | Read header, return header, next position
Header has to define at least .name and .is_global
Parameters
----------
None
Returns
-------
header : object
object that can be passed to self.read_var_array, and that
has attributes .name and .is_global
next_position : int
position in stream of next variable | Read header, return header, next position | [
"Read",
"header",
"return",
"header",
"next",
"position"
] | def read_var_header(self):
''' Read header, return header, next position
Header has to define at least .name and .is_global
Parameters
----------
None
Returns
-------
header : object
object that can be passed to self.read_var_array, and that
has attributes .name and .is_global
next_position : int
position in stream of next variable
'''
mdtype, byte_count = self._file_reader.read_full_tag()
if not byte_count > 0:
raise ValueError("Did not read any bytes")
next_pos = self.mat_stream.tell() + byte_count
if mdtype == miCOMPRESSED:
# Make new stream from compressed data
stream = ZlibInputStream(self.mat_stream, byte_count)
self._matrix_reader.set_stream(stream)
check_stream_limit = self.verify_compressed_data_integrity
mdtype, byte_count = self._matrix_reader.read_full_tag()
else:
check_stream_limit = False
self._matrix_reader.set_stream(self.mat_stream)
if not mdtype == miMATRIX:
raise TypeError('Expecting miMATRIX type here, got %d' % mdtype)
header = self._matrix_reader.read_header(check_stream_limit)
return header, next_pos | [
"def",
"read_var_header",
"(",
"self",
")",
":",
"mdtype",
",",
"byte_count",
"=",
"self",
".",
"_file_reader",
".",
"read_full_tag",
"(",
")",
"if",
"not",
"byte_count",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"Did not read any bytes\"",
")",
"next_pos",
"=",
"self",
".",
"mat_stream",
".",
"tell",
"(",
")",
"+",
"byte_count",
"if",
"mdtype",
"==",
"miCOMPRESSED",
":",
"# Make new stream from compressed data",
"stream",
"=",
"ZlibInputStream",
"(",
"self",
".",
"mat_stream",
",",
"byte_count",
")",
"self",
".",
"_matrix_reader",
".",
"set_stream",
"(",
"stream",
")",
"check_stream_limit",
"=",
"self",
".",
"verify_compressed_data_integrity",
"mdtype",
",",
"byte_count",
"=",
"self",
".",
"_matrix_reader",
".",
"read_full_tag",
"(",
")",
"else",
":",
"check_stream_limit",
"=",
"False",
"self",
".",
"_matrix_reader",
".",
"set_stream",
"(",
"self",
".",
"mat_stream",
")",
"if",
"not",
"mdtype",
"==",
"miMATRIX",
":",
"raise",
"TypeError",
"(",
"'Expecting miMATRIX type here, got %d'",
"%",
"mdtype",
")",
"header",
"=",
"self",
".",
"_matrix_reader",
".",
"read_header",
"(",
"check_stream_limit",
")",
"return",
"header",
",",
"next_pos"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/io/matlab/mio5.py#L200-L233 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/coverage/coverage/html.py | python | HtmlStatus.index_info | (self, fname) | return self.files.get(fname, {}).get('index', {}) | Get the information for index.html for `fname`. | Get the information for index.html for `fname`. | [
"Get",
"the",
"information",
"for",
"index",
".",
"html",
"for",
"fname",
"."
] | def index_info(self, fname):
"""Get the information for index.html for `fname`."""
return self.files.get(fname, {}).get('index', {}) | [
"def",
"index_info",
"(",
"self",
",",
"fname",
")",
":",
"return",
"self",
".",
"files",
".",
"get",
"(",
"fname",
",",
"{",
"}",
")",
".",
"get",
"(",
"'index'",
",",
"{",
"}",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/html.py#L409-L411 | |
gitahead/gitahead | 711a9633149ef8f9dd0d2d6becfee4e147b6458c | dep/scintilla/scintilla-3.21.0/scripts/FileGenerator.py | python | Generate | (inpath, outpath, commentPrefix, *lists) | Generate 'outpath' from 'inpath'. | Generate 'outpath' from 'inpath'. | [
"Generate",
"outpath",
"from",
"inpath",
"."
] | def Generate(inpath, outpath, commentPrefix, *lists):
"""Generate 'outpath' from 'inpath'.
"""
GenerateFile(inpath, outpath, commentPrefix, inpath == outpath, *lists) | [
"def",
"Generate",
"(",
"inpath",
",",
"outpath",
",",
"commentPrefix",
",",
"*",
"lists",
")",
":",
"GenerateFile",
"(",
"inpath",
",",
"outpath",
",",
"commentPrefix",
",",
"inpath",
"==",
"outpath",
",",
"*",
"lists",
")"
] | https://github.com/gitahead/gitahead/blob/711a9633149ef8f9dd0d2d6becfee4e147b6458c/dep/scintilla/scintilla-3.21.0/scripts/FileGenerator.py#L130-L133 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py | python | _PhysicalConnectionWriter.put_outgoing_data | (self, data) | Puts outgoing data.
Args:
data: _OutgoingData instance.
Raises:
BadOperationException: when the thread has been requested to
terminate. | Puts outgoing data. | [
"Puts",
"outgoing",
"data",
"."
] | def put_outgoing_data(self, data):
"""Puts outgoing data.
Args:
data: _OutgoingData instance.
Raises:
BadOperationException: when the thread has been requested to
terminate.
"""
try:
self._deque_condition.acquire()
if self._stop_requested:
raise BadOperationException('Cannot write data anymore')
self._deque.append(data)
self._deque_condition.notify()
finally:
self._deque_condition.release() | [
"def",
"put_outgoing_data",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"self",
".",
"_deque_condition",
".",
"acquire",
"(",
")",
"if",
"self",
".",
"_stop_requested",
":",
"raise",
"BadOperationException",
"(",
"'Cannot write data anymore'",
")",
"self",
".",
"_deque",
".",
"append",
"(",
"data",
")",
"self",
".",
"_deque_condition",
".",
"notify",
"(",
")",
"finally",
":",
"self",
".",
"_deque_condition",
".",
"release",
"(",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py#L1120-L1139 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py | python | BasicFittingModel.plot_guess_end_x | (self) | return self.fitting_context.plot_guess_start_x | Returns the end x to use in the guess plot. | Returns the end x to use in the guess plot. | [
"Returns",
"the",
"end",
"x",
"to",
"use",
"in",
"the",
"guess",
"plot",
"."
] | def plot_guess_end_x(self) -> float:
"""Returns the end x to use in the guess plot."""
return self.fitting_context.plot_guess_start_x | [
"def",
"plot_guess_end_x",
"(",
"self",
")",
"->",
"float",
":",
"return",
"self",
".",
"fitting_context",
".",
"plot_guess_start_x"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py#L405-L407 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Misc.winfo_containing | (self, rootX, rootY, displayof=0) | return self._nametowidget(name) | Return the widget which is at the root coordinates ROOTX, ROOTY. | Return the widget which is at the root coordinates ROOTX, ROOTY. | [
"Return",
"the",
"widget",
"which",
"is",
"at",
"the",
"root",
"coordinates",
"ROOTX",
"ROOTY",
"."
] | def winfo_containing(self, rootX, rootY, displayof=0):
"""Return the widget which is at the root coordinates ROOTX, ROOTY."""
args = ('winfo', 'containing') \
+ self._displayof(displayof) + (rootX, rootY)
name = self.tk.call(args)
if not name: return None
return self._nametowidget(name) | [
"def",
"winfo_containing",
"(",
"self",
",",
"rootX",
",",
"rootY",
",",
"displayof",
"=",
"0",
")",
":",
"args",
"=",
"(",
"'winfo'",
",",
"'containing'",
")",
"+",
"self",
".",
"_displayof",
"(",
"displayof",
")",
"+",
"(",
"rootX",
",",
"rootY",
")",
"name",
"=",
"self",
".",
"tk",
".",
"call",
"(",
"args",
")",
"if",
"not",
"name",
":",
"return",
"None",
"return",
"self",
".",
"_nametowidget",
"(",
"name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L975-L981 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/jinja2/utils.py | python | consume | (iterable) | Consumes an iterable without doing anything with it. | Consumes an iterable without doing anything with it. | [
"Consumes",
"an",
"iterable",
"without",
"doing",
"anything",
"with",
"it",
"."
] | def consume(iterable):
"""Consumes an iterable without doing anything with it."""
for event in iterable:
pass | [
"def",
"consume",
"(",
"iterable",
")",
":",
"for",
"event",
"in",
"iterable",
":",
"pass"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/utils.py#L105-L108 | ||
facebook/bistro | db9eff7e92f5cedcc917a440d5c88064c7980e40 | build/fbcode_builder/getdeps/cache.py | python | create_cache | () | return None | This function is monkey patchable to provide an actual
implementation | This function is monkey patchable to provide an actual
implementation | [
"This",
"function",
"is",
"monkey",
"patchable",
"to",
"provide",
"an",
"actual",
"implementation"
] | def create_cache():
"""This function is monkey patchable to provide an actual
implementation"""
return None | [
"def",
"create_cache",
"(",
")",
":",
"return",
"None"
] | https://github.com/facebook/bistro/blob/db9eff7e92f5cedcc917a440d5c88064c7980e40/build/fbcode_builder/getdeps/cache.py#L34-L37 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | util/gem5art/run/gem5art/run.py | python | gem5Run.createSERun | (
cls,
name: str,
run_script: str,
outdir: str,
gem5_artifact: Artifact,
gem5_git_artifact: Artifact,
run_script_git_artifact: Artifact,
*params: str,
timeout: int = 60 * 15,
check_failure: Callable[["gem5Run"], bool] = lambda run: False,
) | return run | name is the name of the run. The name is not necessarily unique. The
name could be used to query the results of the run.
run_script is the path to the run script to pass to gem5.
The artifact parameters (gem5_artifact, gem5_git_artifact, and
run_script_git_artifact) are used to ensure this is reproducible run.
Further parameters can be passed via extra arguments. These
parameters will be passed in order to the gem5 run script.
timeout is the time in seconds to run the subprocess before killing it.
Note: When instantiating this class for the first time, it will create
a file `info.json` in the outdir which contains a serialized version
of this class. | name is the name of the run. The name is not necessarily unique. The
name could be used to query the results of the run. | [
"name",
"is",
"the",
"name",
"of",
"the",
"run",
".",
"The",
"name",
"is",
"not",
"necessarily",
"unique",
".",
"The",
"name",
"could",
"be",
"used",
"to",
"query",
"the",
"results",
"of",
"the",
"run",
"."
] | def createSERun(
cls,
name: str,
run_script: str,
outdir: str,
gem5_artifact: Artifact,
gem5_git_artifact: Artifact,
run_script_git_artifact: Artifact,
*params: str,
timeout: int = 60 * 15,
check_failure: Callable[["gem5Run"], bool] = lambda run: False,
) -> "gem5Run":
"""
name is the name of the run. The name is not necessarily unique. The
name could be used to query the results of the run.
run_script is the path to the run script to pass to gem5.
The artifact parameters (gem5_artifact, gem5_git_artifact, and
run_script_git_artifact) are used to ensure this is reproducible run.
Further parameters can be passed via extra arguments. These
parameters will be passed in order to the gem5 run script.
timeout is the time in seconds to run the subprocess before killing it.
Note: When instantiating this class for the first time, it will create
a file `info.json` in the outdir which contains a serialized version
of this class.
"""
run = cls._create(
name,
Path(run_script),
Path(outdir),
gem5_artifact,
gem5_git_artifact,
run_script_git_artifact,
params,
timeout,
check_failure,
)
run.artifacts = [
gem5_artifact,
gem5_git_artifact,
run_script_git_artifact,
]
run.string = f"{run.gem5_name} {run.script_name}"
run.string += " ".join(run.params)
run.command = [
str(run.gem5_binary_path),
"-re",
f"--outdir={run.outdir}",
str(run.run_script),
]
run.command += list(params)
run.hash = run._getHash()
run.type = "gem5 run"
# Make the directory if it doesn't exist
os.makedirs(run.outdir, exist_ok=True)
run.dumpJson("info.json")
return run | [
"def",
"createSERun",
"(",
"cls",
",",
"name",
":",
"str",
",",
"run_script",
":",
"str",
",",
"outdir",
":",
"str",
",",
"gem5_artifact",
":",
"Artifact",
",",
"gem5_git_artifact",
":",
"Artifact",
",",
"run_script_git_artifact",
":",
"Artifact",
",",
"*",
"params",
":",
"str",
",",
"timeout",
":",
"int",
"=",
"60",
"*",
"15",
",",
"check_failure",
":",
"Callable",
"[",
"[",
"\"gem5Run\"",
"]",
",",
"bool",
"]",
"=",
"lambda",
"run",
":",
"False",
",",
")",
"->",
"\"gem5Run\"",
":",
"run",
"=",
"cls",
".",
"_create",
"(",
"name",
",",
"Path",
"(",
"run_script",
")",
",",
"Path",
"(",
"outdir",
")",
",",
"gem5_artifact",
",",
"gem5_git_artifact",
",",
"run_script_git_artifact",
",",
"params",
",",
"timeout",
",",
"check_failure",
",",
")",
"run",
".",
"artifacts",
"=",
"[",
"gem5_artifact",
",",
"gem5_git_artifact",
",",
"run_script_git_artifact",
",",
"]",
"run",
".",
"string",
"=",
"f\"{run.gem5_name} {run.script_name}\"",
"run",
".",
"string",
"+=",
"\" \"",
".",
"join",
"(",
"run",
".",
"params",
")",
"run",
".",
"command",
"=",
"[",
"str",
"(",
"run",
".",
"gem5_binary_path",
")",
",",
"\"-re\"",
",",
"f\"--outdir={run.outdir}\"",
",",
"str",
"(",
"run",
".",
"run_script",
")",
",",
"]",
"run",
".",
"command",
"+=",
"list",
"(",
"params",
")",
"run",
".",
"hash",
"=",
"run",
".",
"_getHash",
"(",
")",
"run",
".",
"type",
"=",
"\"gem5 run\"",
"# Make the directory if it doesn't exist",
"os",
".",
"makedirs",
"(",
"run",
".",
"outdir",
",",
"exist_ok",
"=",
"True",
")",
"run",
".",
"dumpJson",
"(",
"\"info.json\"",
")",
"return",
"run"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/gem5art/run/gem5art/run.py#L156-L222 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/RemoteDebugger.py | python | start_remote_debugger | (rpcclt, pyshell) | return gui | Start the subprocess debugger, initialize the debugger GUI and RPC link
Request the RPCServer start the Python subprocess debugger and link. Set
up the Idle side of the split debugger by instantiating the IdbProxy,
debugger GUI, and debugger GUIAdapter objects and linking them together.
Register the GUIAdapter with the RPCClient to handle debugger GUI
interaction requests coming from the subprocess debugger via the GUIProxy.
The IdbAdapter will pass execution and environment requests coming from the
Idle debugger GUI to the subprocess debugger via the IdbProxy. | Start the subprocess debugger, initialize the debugger GUI and RPC link | [
"Start",
"the",
"subprocess",
"debugger",
"initialize",
"the",
"debugger",
"GUI",
"and",
"RPC",
"link"
] | def start_remote_debugger(rpcclt, pyshell):
"""Start the subprocess debugger, initialize the debugger GUI and RPC link
Request the RPCServer start the Python subprocess debugger and link. Set
up the Idle side of the split debugger by instantiating the IdbProxy,
debugger GUI, and debugger GUIAdapter objects and linking them together.
Register the GUIAdapter with the RPCClient to handle debugger GUI
interaction requests coming from the subprocess debugger via the GUIProxy.
The IdbAdapter will pass execution and environment requests coming from the
Idle debugger GUI to the subprocess debugger via the IdbProxy.
"""
global idb_adap_oid
idb_adap_oid = rpcclt.remotecall("exec", "start_the_debugger",\
(gui_adap_oid,), {})
idb_proxy = IdbProxy(rpcclt, pyshell, idb_adap_oid)
gui = Debugger.Debugger(pyshell, idb_proxy)
gui_adap = GUIAdapter(rpcclt, gui)
rpcclt.register(gui_adap_oid, gui_adap)
return gui | [
"def",
"start_remote_debugger",
"(",
"rpcclt",
",",
"pyshell",
")",
":",
"global",
"idb_adap_oid",
"idb_adap_oid",
"=",
"rpcclt",
".",
"remotecall",
"(",
"\"exec\"",
",",
"\"start_the_debugger\"",
",",
"(",
"gui_adap_oid",
",",
")",
",",
"{",
"}",
")",
"idb_proxy",
"=",
"IdbProxy",
"(",
"rpcclt",
",",
"pyshell",
",",
"idb_adap_oid",
")",
"gui",
"=",
"Debugger",
".",
"Debugger",
"(",
"pyshell",
",",
"idb_proxy",
")",
"gui_adap",
"=",
"GUIAdapter",
"(",
"rpcclt",
",",
"gui",
")",
"rpcclt",
".",
"register",
"(",
"gui_adap_oid",
",",
"gui_adap",
")",
"return",
"gui"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/RemoteDebugger.py#L338-L360 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/examples/speech_commands/recognize_commands.py | python | RecognizeCommands.__init__ | (self, labels, average_window_duration_ms, detection_threshold,
suppression_ms, minimum_count) | Init the RecognizeCommands with parameters used for smoothing. | Init the RecognizeCommands with parameters used for smoothing. | [
"Init",
"the",
"RecognizeCommands",
"with",
"parameters",
"used",
"for",
"smoothing",
"."
] | def __init__(self, labels, average_window_duration_ms, detection_threshold,
suppression_ms, minimum_count):
"""Init the RecognizeCommands with parameters used for smoothing."""
# Configuration
self._labels = labels
self._average_window_duration_ms = average_window_duration_ms
self._detection_threshold = detection_threshold
self._suppression_ms = suppression_ms
self._minimum_count = minimum_count
# Working Variable
self._previous_results = collections.deque()
self._label_count = len(labels)
self._previous_top_label = "_silence_"
self._previous_top_time = -np.inf | [
"def",
"__init__",
"(",
"self",
",",
"labels",
",",
"average_window_duration_ms",
",",
"detection_threshold",
",",
"suppression_ms",
",",
"minimum_count",
")",
":",
"# Configuration",
"self",
".",
"_labels",
"=",
"labels",
"self",
".",
"_average_window_duration_ms",
"=",
"average_window_duration_ms",
"self",
".",
"_detection_threshold",
"=",
"detection_threshold",
"self",
".",
"_suppression_ms",
"=",
"suppression_ms",
"self",
".",
"_minimum_count",
"=",
"minimum_count",
"# Working Variable",
"self",
".",
"_previous_results",
"=",
"collections",
".",
"deque",
"(",
")",
"self",
".",
"_label_count",
"=",
"len",
"(",
"labels",
")",
"self",
".",
"_previous_top_label",
"=",
"\"_silence_\"",
"self",
".",
"_previous_top_time",
"=",
"-",
"np",
".",
"inf"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/examples/speech_commands/recognize_commands.py#L98-L111 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/python_gflags/gflags.py | python | FlagValues.__setattr__ | (self, name, value) | return value | Sets the 'value' attribute of the flag --name. | Sets the 'value' attribute of the flag --name. | [
"Sets",
"the",
"value",
"attribute",
"of",
"the",
"flag",
"--",
"name",
"."
] | def __setattr__(self, name, value):
"""Sets the 'value' attribute of the flag --name."""
fl = self.FlagDict()
fl[name].value = value
self._AssertValidators(fl[name].validators)
return value | [
"def",
"__setattr__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"fl",
"=",
"self",
".",
"FlagDict",
"(",
")",
"fl",
"[",
"name",
"]",
".",
"value",
"=",
"value",
"self",
".",
"_AssertValidators",
"(",
"fl",
"[",
"name",
"]",
".",
"validators",
")",
"return",
"value"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/python_gflags/gflags.py#L1062-L1067 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/coverage/coverage/annotate.py | python | AnnotateReporter.annotate_file | (self, fr, analysis) | Annotate a single file.
`fr` is the FileReporter for the file to annotate. | Annotate a single file. | [
"Annotate",
"a",
"single",
"file",
"."
] | def annotate_file(self, fr, analysis):
"""Annotate a single file.
`fr` is the FileReporter for the file to annotate.
"""
statements = sorted(analysis.statements)
missing = sorted(analysis.missing)
excluded = sorted(analysis.excluded)
if self.directory:
dest_file = os.path.join(self.directory, flat_rootname(fr.relative_filename()))
if dest_file.endswith("_py"):
dest_file = dest_file[:-3] + ".py"
dest_file += ",cover"
else:
dest_file = fr.filename + ",cover"
with io.open(dest_file, 'w', encoding='utf8') as dest:
i = 0
j = 0
covered = True
source = fr.source()
for lineno, line in enumerate(source.splitlines(True), start=1):
while i < len(statements) and statements[i] < lineno:
i += 1
while j < len(missing) and missing[j] < lineno:
j += 1
if i < len(statements) and statements[i] == lineno:
covered = j >= len(missing) or missing[j] > lineno
if self.blank_re.match(line):
dest.write(u' ')
elif self.else_re.match(line):
# Special logic for lines containing only 'else:'.
if i >= len(statements) and j >= len(missing):
dest.write(u'! ')
elif i >= len(statements) or j >= len(missing):
dest.write(u'> ')
elif statements[i] == missing[j]:
dest.write(u'! ')
else:
dest.write(u'> ')
elif lineno in excluded:
dest.write(u'- ')
elif covered:
dest.write(u'> ')
else:
dest.write(u'! ')
dest.write(line) | [
"def",
"annotate_file",
"(",
"self",
",",
"fr",
",",
"analysis",
")",
":",
"statements",
"=",
"sorted",
"(",
"analysis",
".",
"statements",
")",
"missing",
"=",
"sorted",
"(",
"analysis",
".",
"missing",
")",
"excluded",
"=",
"sorted",
"(",
"analysis",
".",
"excluded",
")",
"if",
"self",
".",
"directory",
":",
"dest_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"flat_rootname",
"(",
"fr",
".",
"relative_filename",
"(",
")",
")",
")",
"if",
"dest_file",
".",
"endswith",
"(",
"\"_py\"",
")",
":",
"dest_file",
"=",
"dest_file",
"[",
":",
"-",
"3",
"]",
"+",
"\".py\"",
"dest_file",
"+=",
"\",cover\"",
"else",
":",
"dest_file",
"=",
"fr",
".",
"filename",
"+",
"\",cover\"",
"with",
"io",
".",
"open",
"(",
"dest_file",
",",
"'w'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"dest",
":",
"i",
"=",
"0",
"j",
"=",
"0",
"covered",
"=",
"True",
"source",
"=",
"fr",
".",
"source",
"(",
")",
"for",
"lineno",
",",
"line",
"in",
"enumerate",
"(",
"source",
".",
"splitlines",
"(",
"True",
")",
",",
"start",
"=",
"1",
")",
":",
"while",
"i",
"<",
"len",
"(",
"statements",
")",
"and",
"statements",
"[",
"i",
"]",
"<",
"lineno",
":",
"i",
"+=",
"1",
"while",
"j",
"<",
"len",
"(",
"missing",
")",
"and",
"missing",
"[",
"j",
"]",
"<",
"lineno",
":",
"j",
"+=",
"1",
"if",
"i",
"<",
"len",
"(",
"statements",
")",
"and",
"statements",
"[",
"i",
"]",
"==",
"lineno",
":",
"covered",
"=",
"j",
">=",
"len",
"(",
"missing",
")",
"or",
"missing",
"[",
"j",
"]",
">",
"lineno",
"if",
"self",
".",
"blank_re",
".",
"match",
"(",
"line",
")",
":",
"dest",
".",
"write",
"(",
"u' '",
")",
"elif",
"self",
".",
"else_re",
".",
"match",
"(",
"line",
")",
":",
"# Special logic for lines containing only 'else:'.",
"if",
"i",
">=",
"len",
"(",
"statements",
")",
"and",
"j",
">=",
"len",
"(",
"missing",
")",
":",
"dest",
".",
"write",
"(",
"u'! '",
")",
"elif",
"i",
">=",
"len",
"(",
"statements",
")",
"or",
"j",
">=",
"len",
"(",
"missing",
")",
":",
"dest",
".",
"write",
"(",
"u'> '",
")",
"elif",
"statements",
"[",
"i",
"]",
"==",
"missing",
"[",
"j",
"]",
":",
"dest",
".",
"write",
"(",
"u'! '",
")",
"else",
":",
"dest",
".",
"write",
"(",
"u'> '",
")",
"elif",
"lineno",
"in",
"excluded",
":",
"dest",
".",
"write",
"(",
"u'- '",
")",
"elif",
"covered",
":",
"dest",
".",
"write",
"(",
"u'> '",
")",
"else",
":",
"dest",
".",
"write",
"(",
"u'! '",
")",
"dest",
".",
"write",
"(",
"line",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/annotate.py#L54-L103 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | QueryLayoutInfoEvent.SetFlags | (*args, **kwargs) | return _windows_.QueryLayoutInfoEvent_SetFlags(*args, **kwargs) | SetFlags(self, int flags) | SetFlags(self, int flags) | [
"SetFlags",
"(",
"self",
"int",
"flags",
")"
] | def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _windows_.QueryLayoutInfoEvent_SetFlags(*args, **kwargs) | [
"def",
"SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"QueryLayoutInfoEvent_SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L1965-L1967 | |
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | Tools/mavlink_px4.py | python | MAVLink.mission_item_send | (self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z) | return self.send(self.mission_item_encode(target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z)) | Message encoding a mission item. This message is emitted to announce
the presence of a mission item and to set a mission
item on the system. The mission item can be either in
x, y, z meters (type: LOCAL) or x:lat, y:lon,
z:altitude. Local frame is Z-down, right handed (NED),
global frame is Z-up, right handed (ENU). See also
http://qgroundcontrol.org/mavlink/waypoint_protocol.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seq : Sequence (uint16_t)
frame : The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h (uint8_t)
command : The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs (uint16_t)
current : false:0, true:1 (uint8_t)
autocontinue : autocontinue to next wp (uint8_t)
param1 : PARAM1 / For NAV command MISSIONs: Radius in which the MISSION is accepted as reached, in meters (float)
param2 : PARAM2 / For NAV command MISSIONs: Time that the MAV should stay inside the PARAM1 radius before advancing, in milliseconds (float)
param3 : PARAM3 / For LOITER command MISSIONs: Orbit to circle around the MISSION, in meters. If positive the orbit direction should be clockwise, if negative the orbit direction should be counter-clockwise. (float)
param4 : PARAM4 / For NAV and LOITER command MISSIONs: Yaw orientation in degrees, [0..360] 0 = NORTH (float)
x : PARAM5 / local: x position, global: latitude (float)
y : PARAM6 / y position: global: longitude (float)
z : PARAM7 / z position: global: altitude (float) | Message encoding a mission item. This message is emitted to announce
the presence of a mission item and to set a mission
item on the system. The mission item can be either in
x, y, z meters (type: LOCAL) or x:lat, y:lon,
z:altitude. Local frame is Z-down, right handed (NED),
global frame is Z-up, right handed (ENU). See also
http://qgroundcontrol.org/mavlink/waypoint_protocol. | [
"Message",
"encoding",
"a",
"mission",
"item",
".",
"This",
"message",
"is",
"emitted",
"to",
"announce",
"the",
"presence",
"of",
"a",
"mission",
"item",
"and",
"to",
"set",
"a",
"mission",
"item",
"on",
"the",
"system",
".",
"The",
"mission",
"item",
"can",
"be",
"either",
"in",
"x",
"y",
"z",
"meters",
"(",
"type",
":",
"LOCAL",
")",
"or",
"x",
":",
"lat",
"y",
":",
"lon",
"z",
":",
"altitude",
".",
"Local",
"frame",
"is",
"Z",
"-",
"down",
"right",
"handed",
"(",
"NED",
")",
"global",
"frame",
"is",
"Z",
"-",
"up",
"right",
"handed",
"(",
"ENU",
")",
".",
"See",
"also",
"http",
":",
"//",
"qgroundcontrol",
".",
"org",
"/",
"mavlink",
"/",
"waypoint_protocol",
"."
] | def mission_item_send(self, target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z):
'''
Message encoding a mission item. This message is emitted to announce
the presence of a mission item and to set a mission
item on the system. The mission item can be either in
x, y, z meters (type: LOCAL) or x:lat, y:lon,
z:altitude. Local frame is Z-down, right handed (NED),
global frame is Z-up, right handed (ENU). See also
http://qgroundcontrol.org/mavlink/waypoint_protocol.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
seq : Sequence (uint16_t)
frame : The coordinate system of the MISSION. see MAV_FRAME in mavlink_types.h (uint8_t)
command : The scheduled action for the MISSION. see MAV_CMD in common.xml MAVLink specs (uint16_t)
current : false:0, true:1 (uint8_t)
autocontinue : autocontinue to next wp (uint8_t)
param1 : PARAM1 / For NAV command MISSIONs: Radius in which the MISSION is accepted as reached, in meters (float)
param2 : PARAM2 / For NAV command MISSIONs: Time that the MAV should stay inside the PARAM1 radius before advancing, in milliseconds (float)
param3 : PARAM3 / For LOITER command MISSIONs: Orbit to circle around the MISSION, in meters. If positive the orbit direction should be clockwise, if negative the orbit direction should be counter-clockwise. (float)
param4 : PARAM4 / For NAV and LOITER command MISSIONs: Yaw orientation in degrees, [0..360] 0 = NORTH (float)
x : PARAM5 / local: x position, global: latitude (float)
y : PARAM6 / y position: global: longitude (float)
z : PARAM7 / z position: global: altitude (float)
'''
return self.send(self.mission_item_encode(target_system, target_component, seq, frame, command, current, autocontinue, param1, param2, param3, param4, x, y, z)) | [
"def",
"mission_item_send",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"seq",
",",
"frame",
",",
"command",
",",
"current",
",",
"autocontinue",
",",
"param1",
",",
"param2",
",",
"param3",
",",
"param4",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"mission_item_encode",
"(",
"target_system",
",",
"target_component",
",",
"seq",
",",
"frame",
",",
"command",
",",
"current",
",",
"autocontinue",
",",
"param1",
",",
"param2",
",",
"param3",
",",
"param4",
",",
"x",
",",
"y",
",",
"z",
")",
")"
] | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L3421-L3447 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/gs/lifecycle.py | python | Rule.validateStartTag | (self, tag, parent) | Verify parent of the start tag. | Verify parent of the start tag. | [
"Verify",
"parent",
"of",
"the",
"start",
"tag",
"."
] | def validateStartTag(self, tag, parent):
"""Verify parent of the start tag."""
if self.current_tag != parent:
raise InvalidLifecycleConfigError(
'Invalid tag %s found inside %s tag' % (tag, self.current_tag)) | [
"def",
"validateStartTag",
"(",
"self",
",",
"tag",
",",
"parent",
")",
":",
"if",
"self",
".",
"current_tag",
"!=",
"parent",
":",
"raise",
"InvalidLifecycleConfigError",
"(",
"'Invalid tag %s found inside %s tag'",
"%",
"(",
"tag",
",",
"self",
".",
"current_tag",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/gs/lifecycle.py#L68-L72 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | DELnHandler.WriteImmediateCmdComputeSize | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteImmediateCmdComputeSize(self, func, file):
"""Overrriden from TypeHandler."""
file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
file.Write(
" return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
file.Write(" }\n")
file.Write("\n")
file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
file.Write(" return static_cast<uint32>(\n")
file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
file.Write(" }\n")
file.Write("\n") | [
"def",
"WriteImmediateCmdComputeSize",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"file",
".",
"Write",
"(",
"\" static uint32 ComputeDataSize(GLsizei n) {\\n\"",
")",
"file",
".",
"Write",
"(",
"\" return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\\n\"",
")",
"file",
".",
"Write",
"(",
"\" }\\n\"",
")",
"file",
".",
"Write",
"(",
"\"\\n\"",
")",
"file",
".",
"Write",
"(",
"\" static uint32 ComputeSize(GLsizei n) {\\n\"",
")",
"file",
".",
"Write",
"(",
"\" return static_cast<uint32>(\\n\"",
")",
"file",
".",
"Write",
"(",
"\" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\\n\"",
")",
"file",
".",
"Write",
"(",
"\" }\\n\"",
")",
"file",
".",
"Write",
"(",
"\"\\n\"",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L3242-L3253 | ||
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/generator/cmake.py | python | StringToCMakeTargetName | (a) | return a.translate(string.maketrans(' /():.', '______')) | Converts the given string 'a' to a valid CMake target name.
All invalid characters are replaced by '_'.
Invalid for cmake: ' ', '/', '(', ')'
Invalid for make: ':'
Invalid for unknown reasons but cause failures: '.' | Converts the given string 'a' to a valid CMake target name. | [
"Converts",
"the",
"given",
"string",
"a",
"to",
"a",
"valid",
"CMake",
"target",
"name",
"."
] | def StringToCMakeTargetName(a):
"""Converts the given string 'a' to a valid CMake target name.
All invalid characters are replaced by '_'.
Invalid for cmake: ' ', '/', '(', ')'
Invalid for make: ':'
Invalid for unknown reasons but cause failures: '.'
"""
return a.translate(string.maketrans(' /():.', '______')) | [
"def",
"StringToCMakeTargetName",
"(",
"a",
")",
":",
"return",
"a",
".",
"translate",
"(",
"string",
".",
"maketrans",
"(",
"' /():.'",
",",
"'______'",
")",
")"
] | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/generator/cmake.py#L235-L243 | |
nlohmann/json | eb2182414749825be086c825edb5229e5c28503d | third_party/cpplint/cpplint.py | python | FileInfo.BaseName | (self) | return self.Split()[1] | File base name - text after the final slash, before the final period. | File base name - text after the final slash, before the final period. | [
"File",
"base",
"name",
"-",
"text",
"after",
"the",
"final",
"slash",
"before",
"the",
"final",
"period",
"."
] | def BaseName(self):
"""File base name - text after the final slash, before the final period."""
return self.Split()[1] | [
"def",
"BaseName",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"1",
"]"
] | https://github.com/nlohmann/json/blob/eb2182414749825be086c825edb5229e5c28503d/third_party/cpplint/cpplint.py#L1638-L1640 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/generator/cmake.py | python | WriteActions | (target_name, actions, extra_sources, extra_deps,
path_to_gyp, output) | Write CMake for the 'actions' in the target.
Args:
target_name: the name of the CMake target being generated.
actions: the Gyp 'actions' dict for this target.
extra_sources: [(<cmake_src>, <src>)] to append with generated source files.
extra_deps: [<cmake_taget>] to append with generated targets.
path_to_gyp: relative path from CMakeLists.txt being generated to
the Gyp file in which the target being generated is defined. | Write CMake for the 'actions' in the target. | [
"Write",
"CMake",
"for",
"the",
"actions",
"in",
"the",
"target",
"."
] | def WriteActions(target_name, actions, extra_sources, extra_deps,
path_to_gyp, output):
"""Write CMake for the 'actions' in the target.
Args:
target_name: the name of the CMake target being generated.
actions: the Gyp 'actions' dict for this target.
extra_sources: [(<cmake_src>, <src>)] to append with generated source files.
extra_deps: [<cmake_taget>] to append with generated targets.
path_to_gyp: relative path from CMakeLists.txt being generated to
the Gyp file in which the target being generated is defined.
"""
for action in actions:
action_name = StringToCMakeTargetName(action['action_name'])
action_target_name = '%s__%s' % (target_name, action_name)
inputs = action['inputs']
inputs_name = action_target_name + '__input'
SetVariableList(output, inputs_name,
[NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs])
outputs = action['outputs']
cmake_outputs = [NormjoinPathForceCMakeSource(path_to_gyp, out)
for out in outputs]
outputs_name = action_target_name + '__output'
SetVariableList(output, outputs_name, cmake_outputs)
# Build up a list of outputs.
# Collect the output dirs we'll need.
dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir)
if int(action.get('process_outputs_as_sources', False)):
extra_sources.extend(zip(cmake_outputs, outputs))
# add_custom_command
output.write('add_custom_command(OUTPUT ')
WriteVariable(output, outputs_name)
output.write('\n')
if len(dirs) > 0:
for directory in dirs:
output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ')
output.write(directory)
output.write('\n')
output.write(' COMMAND ')
output.write(gyp.common.EncodePOSIXShellList(action['action']))
output.write('\n')
output.write(' DEPENDS ')
WriteVariable(output, inputs_name)
output.write('\n')
output.write(' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/')
output.write(path_to_gyp)
output.write('\n')
output.write(' COMMENT ')
if 'message' in action:
output.write(action['message'])
else:
output.write(action_target_name)
output.write('\n')
output.write(' VERBATIM\n')
output.write(')\n')
# add_custom_target
output.write('add_custom_target(')
output.write(action_target_name)
output.write('\n DEPENDS ')
WriteVariable(output, outputs_name)
output.write('\n SOURCES ')
WriteVariable(output, inputs_name)
output.write('\n)\n')
extra_deps.append(action_target_name) | [
"def",
"WriteActions",
"(",
"target_name",
",",
"actions",
",",
"extra_sources",
",",
"extra_deps",
",",
"path_to_gyp",
",",
"output",
")",
":",
"for",
"action",
"in",
"actions",
":",
"action_name",
"=",
"StringToCMakeTargetName",
"(",
"action",
"[",
"'action_name'",
"]",
")",
"action_target_name",
"=",
"'%s__%s'",
"%",
"(",
"target_name",
",",
"action_name",
")",
"inputs",
"=",
"action",
"[",
"'inputs'",
"]",
"inputs_name",
"=",
"action_target_name",
"+",
"'__input'",
"SetVariableList",
"(",
"output",
",",
"inputs_name",
",",
"[",
"NormjoinPathForceCMakeSource",
"(",
"path_to_gyp",
",",
"dep",
")",
"for",
"dep",
"in",
"inputs",
"]",
")",
"outputs",
"=",
"action",
"[",
"'outputs'",
"]",
"cmake_outputs",
"=",
"[",
"NormjoinPathForceCMakeSource",
"(",
"path_to_gyp",
",",
"out",
")",
"for",
"out",
"in",
"outputs",
"]",
"outputs_name",
"=",
"action_target_name",
"+",
"'__output'",
"SetVariableList",
"(",
"output",
",",
"outputs_name",
",",
"cmake_outputs",
")",
"# Build up a list of outputs.",
"# Collect the output dirs we'll need.",
"dirs",
"=",
"set",
"(",
"dir",
"for",
"dir",
"in",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"o",
")",
"for",
"o",
"in",
"outputs",
")",
"if",
"dir",
")",
"if",
"int",
"(",
"action",
".",
"get",
"(",
"'process_outputs_as_sources'",
",",
"False",
")",
")",
":",
"extra_sources",
".",
"extend",
"(",
"zip",
"(",
"cmake_outputs",
",",
"outputs",
")",
")",
"# add_custom_command",
"output",
".",
"write",
"(",
"'add_custom_command(OUTPUT '",
")",
"WriteVariable",
"(",
"output",
",",
"outputs_name",
")",
"output",
".",
"write",
"(",
"'\\n'",
")",
"if",
"len",
"(",
"dirs",
")",
">",
"0",
":",
"for",
"directory",
"in",
"dirs",
":",
"output",
".",
"write",
"(",
"' COMMAND ${CMAKE_COMMAND} -E make_directory '",
")",
"output",
".",
"write",
"(",
"directory",
")",
"output",
".",
"write",
"(",
"'\\n'",
")",
"output",
".",
"write",
"(",
"' COMMAND '",
")",
"output",
".",
"write",
"(",
"gyp",
".",
"common",
".",
"EncodePOSIXShellList",
"(",
"action",
"[",
"'action'",
"]",
")",
")",
"output",
".",
"write",
"(",
"'\\n'",
")",
"output",
".",
"write",
"(",
"' DEPENDS '",
")",
"WriteVariable",
"(",
"output",
",",
"inputs_name",
")",
"output",
".",
"write",
"(",
"'\\n'",
")",
"output",
".",
"write",
"(",
"' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/'",
")",
"output",
".",
"write",
"(",
"path_to_gyp",
")",
"output",
".",
"write",
"(",
"'\\n'",
")",
"output",
".",
"write",
"(",
"' COMMENT '",
")",
"if",
"'message'",
"in",
"action",
":",
"output",
".",
"write",
"(",
"action",
"[",
"'message'",
"]",
")",
"else",
":",
"output",
".",
"write",
"(",
"action_target_name",
")",
"output",
".",
"write",
"(",
"'\\n'",
")",
"output",
".",
"write",
"(",
"' VERBATIM\\n'",
")",
"output",
".",
"write",
"(",
"')\\n'",
")",
"# add_custom_target",
"output",
".",
"write",
"(",
"'add_custom_target('",
")",
"output",
".",
"write",
"(",
"action_target_name",
")",
"output",
".",
"write",
"(",
"'\\n DEPENDS '",
")",
"WriteVariable",
"(",
"output",
",",
"outputs_name",
")",
"output",
".",
"write",
"(",
"'\\n SOURCES '",
")",
"WriteVariable",
"(",
"output",
",",
"inputs_name",
")",
"output",
".",
"write",
"(",
"'\\n)\\n'",
")",
"extra_deps",
".",
"append",
"(",
"action_target_name",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/cmake.py#L249-L325 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/customtreectrl.py | python | GenericTreeItem.SetData | (self, data) | Sets the data associated to this item.
:param object `data`: can be any Python object. | Sets the data associated to this item. | [
"Sets",
"the",
"data",
"associated",
"to",
"this",
"item",
"."
] | def SetData(self, data):
"""
Sets the data associated to this item.
:param object `data`: can be any Python object.
"""
self._data = data | [
"def",
"SetData",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_data",
"=",
"data"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L1805-L1812 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/integrate/_ivp/common.py | python | OdeSolution.__call__ | (self, t) | return ys | Evaluate the solution.
Parameters
----------
t : float or array_like with shape (n_points,)
Points to evaluate at.
Returns
-------
y : ndarray, shape (n_states,) or (n_states, n_points)
Computed values. Shape depends on whether `t` is a scalar or a
1-d array. | Evaluate the solution. | [
"Evaluate",
"the",
"solution",
"."
] | def __call__(self, t):
"""Evaluate the solution.
Parameters
----------
t : float or array_like with shape (n_points,)
Points to evaluate at.
Returns
-------
y : ndarray, shape (n_states,) or (n_states, n_points)
Computed values. Shape depends on whether `t` is a scalar or a
1-d array.
"""
t = np.asarray(t)
if t.ndim == 0:
return self._call_single(t)
order = np.argsort(t)
reverse = np.empty_like(order)
reverse[order] = np.arange(order.shape[0])
t_sorted = t[order]
# See comment in self._call_single.
if self.ascending:
segments = np.searchsorted(self.ts_sorted, t_sorted, side='left')
else:
segments = np.searchsorted(self.ts_sorted, t_sorted, side='right')
segments -= 1
segments[segments < 0] = 0
segments[segments > self.n_segments - 1] = self.n_segments - 1
if not self.ascending:
segments = self.n_segments - 1 - segments
ys = []
group_start = 0
for segment, group in groupby(segments):
group_end = group_start + len(list(group))
y = self.interpolants[segment](t_sorted[group_start:group_end])
ys.append(y)
group_start = group_end
ys = np.hstack(ys)
ys = ys[:, reverse]
return ys | [
"def",
"__call__",
"(",
"self",
",",
"t",
")",
":",
"t",
"=",
"np",
".",
"asarray",
"(",
"t",
")",
"if",
"t",
".",
"ndim",
"==",
"0",
":",
"return",
"self",
".",
"_call_single",
"(",
"t",
")",
"order",
"=",
"np",
".",
"argsort",
"(",
"t",
")",
"reverse",
"=",
"np",
".",
"empty_like",
"(",
"order",
")",
"reverse",
"[",
"order",
"]",
"=",
"np",
".",
"arange",
"(",
"order",
".",
"shape",
"[",
"0",
"]",
")",
"t_sorted",
"=",
"t",
"[",
"order",
"]",
"# See comment in self._call_single.",
"if",
"self",
".",
"ascending",
":",
"segments",
"=",
"np",
".",
"searchsorted",
"(",
"self",
".",
"ts_sorted",
",",
"t_sorted",
",",
"side",
"=",
"'left'",
")",
"else",
":",
"segments",
"=",
"np",
".",
"searchsorted",
"(",
"self",
".",
"ts_sorted",
",",
"t_sorted",
",",
"side",
"=",
"'right'",
")",
"segments",
"-=",
"1",
"segments",
"[",
"segments",
"<",
"0",
"]",
"=",
"0",
"segments",
"[",
"segments",
">",
"self",
".",
"n_segments",
"-",
"1",
"]",
"=",
"self",
".",
"n_segments",
"-",
"1",
"if",
"not",
"self",
".",
"ascending",
":",
"segments",
"=",
"self",
".",
"n_segments",
"-",
"1",
"-",
"segments",
"ys",
"=",
"[",
"]",
"group_start",
"=",
"0",
"for",
"segment",
",",
"group",
"in",
"groupby",
"(",
"segments",
")",
":",
"group_end",
"=",
"group_start",
"+",
"len",
"(",
"list",
"(",
"group",
")",
")",
"y",
"=",
"self",
".",
"interpolants",
"[",
"segment",
"]",
"(",
"t_sorted",
"[",
"group_start",
":",
"group_end",
"]",
")",
"ys",
".",
"append",
"(",
"y",
")",
"group_start",
"=",
"group_end",
"ys",
"=",
"np",
".",
"hstack",
"(",
"ys",
")",
"ys",
"=",
"ys",
"[",
":",
",",
"reverse",
"]",
"return",
"ys"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/integrate/_ivp/common.py#L191-L237 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/smtplib.py | python | quotedata | (data) | return re.sub(r'(?m)^\.', '..',
re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) | Quote data for email.
Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
Internet CRLF end-of-line. | Quote data for email. | [
"Quote",
"data",
"for",
"email",
"."
] | def quotedata(data):
"""Quote data for email.
Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
Internet CRLF end-of-line.
"""
return re.sub(r'(?m)^\.', '..',
re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) | [
"def",
"quotedata",
"(",
"data",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'(?m)^\\.'",
",",
"'..'",
",",
"re",
".",
"sub",
"(",
"r'(?:\\r\\n|\\n|\\r(?!\\n))'",
",",
"CRLF",
",",
"data",
")",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/smtplib.py#L150-L157 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | uCSIsHighPrivateUseSurrogates | (code) | return ret | Check whether the character is part of
HighPrivateUseSurrogates UCS Block | Check whether the character is part of
HighPrivateUseSurrogates UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"HighPrivateUseSurrogates",
"UCS",
"Block"
] | def uCSIsHighPrivateUseSurrogates(code):
"""Check whether the character is part of
HighPrivateUseSurrogates UCS Block """
ret = libxml2mod.xmlUCSIsHighPrivateUseSurrogates(code)
return ret | [
"def",
"uCSIsHighPrivateUseSurrogates",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsHighPrivateUseSurrogates",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1810-L1814 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/packages.py | python | find_package_paths | (basepath, exclude_paths=None, exclude_subspaces=False) | return paths | Crawls the filesystem to find package manifest files.
When a subfolder contains a file ``CATKIN_IGNORE`` it is ignored.
:param basepath: The path to search in, ``str``
:param exclude_paths: A list of paths which should not be searched, ``list``
:param exclude_subspaces: The flag is subfolders containing a .catkin file should not be
searched, ``bool``
:returns: A list of relative paths containing package manifest files ``list`` | Crawls the filesystem to find package manifest files. | [
"Crawls",
"the",
"filesystem",
"to",
"find",
"package",
"manifest",
"files",
"."
] | def find_package_paths(basepath, exclude_paths=None, exclude_subspaces=False):
"""
Crawls the filesystem to find package manifest files.
When a subfolder contains a file ``CATKIN_IGNORE`` it is ignored.
:param basepath: The path to search in, ``str``
:param exclude_paths: A list of paths which should not be searched, ``list``
:param exclude_subspaces: The flag is subfolders containing a .catkin file should not be
searched, ``bool``
:returns: A list of relative paths containing package manifest files ``list``
"""
paths = []
real_exclude_paths = [os.path.realpath(p) for p in exclude_paths] if exclude_paths is not None else []
for dirpath, dirnames, filenames in os.walk(basepath, followlinks=True):
if 'CATKIN_IGNORE' in filenames or \
os.path.realpath(dirpath) in real_exclude_paths or \
(exclude_subspaces and '.catkin' in filenames):
del dirnames[:]
continue
elif PACKAGE_MANIFEST_FILENAME in filenames:
paths.append(os.path.relpath(dirpath, basepath))
del dirnames[:]
continue
for dirname in dirnames:
if dirname.startswith('.'):
dirnames.remove(dirname)
return paths | [
"def",
"find_package_paths",
"(",
"basepath",
",",
"exclude_paths",
"=",
"None",
",",
"exclude_subspaces",
"=",
"False",
")",
":",
"paths",
"=",
"[",
"]",
"real_exclude_paths",
"=",
"[",
"os",
".",
"path",
".",
"realpath",
"(",
"p",
")",
"for",
"p",
"in",
"exclude_paths",
"]",
"if",
"exclude_paths",
"is",
"not",
"None",
"else",
"[",
"]",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"basepath",
",",
"followlinks",
"=",
"True",
")",
":",
"if",
"'CATKIN_IGNORE'",
"in",
"filenames",
"or",
"os",
".",
"path",
".",
"realpath",
"(",
"dirpath",
")",
"in",
"real_exclude_paths",
"or",
"(",
"exclude_subspaces",
"and",
"'.catkin'",
"in",
"filenames",
")",
":",
"del",
"dirnames",
"[",
":",
"]",
"continue",
"elif",
"PACKAGE_MANIFEST_FILENAME",
"in",
"filenames",
":",
"paths",
".",
"append",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"dirpath",
",",
"basepath",
")",
")",
"del",
"dirnames",
"[",
":",
"]",
"continue",
"for",
"dirname",
"in",
"dirnames",
":",
"if",
"dirname",
".",
"startswith",
"(",
"'.'",
")",
":",
"dirnames",
".",
"remove",
"(",
"dirname",
")",
"return",
"paths"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/packages.py#L41-L68 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | Contrib/Glare/glare.py | python | RGroups.__init__ | (self, sidechains) | Sidechains -> RGroups
sidechains: the list of Sidechains that make up the potential
sidechains at this rgroup position | Sidechains -> RGroups
sidechains: the list of Sidechains that make up the potential
sidechains at this rgroup position | [
"Sidechains",
"-",
">",
"RGroups",
"sidechains",
":",
"the",
"list",
"of",
"Sidechains",
"that",
"make",
"up",
"the",
"potential",
"sidechains",
"at",
"this",
"rgroup",
"position"
] | def __init__(self, sidechains):
"""Sidechains -> RGroups
sidechains: the list of Sidechains that make up the potential
sidechains at this rgroup position"""
self.sidechains = sidechains
self.rejected = [] # list of rejected sidechains
self.initial_size = len(sidechains) | [
"def",
"__init__",
"(",
"self",
",",
"sidechains",
")",
":",
"self",
".",
"sidechains",
"=",
"sidechains",
"self",
".",
"rejected",
"=",
"[",
"]",
"# list of rejected sidechains",
"self",
".",
"initial_size",
"=",
"len",
"(",
"sidechains",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/Contrib/Glare/glare.py#L103-L110 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | Indigo.version | (self) | return self._checkResultString(Indigo._lib.indigoVersion()) | Returns Indigo version
Returns:
str: version string | Returns Indigo version | [
"Returns",
"Indigo",
"version"
] | def version(self):
"""Returns Indigo version
Returns:
str: version string
"""
self._setSessionId()
return self._checkResultString(Indigo._lib.indigoVersion()) | [
"def",
"version",
"(",
"self",
")",
":",
"self",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"_checkResultString",
"(",
"Indigo",
".",
"_lib",
".",
"indigoVersion",
"(",
")",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L5422-L5429 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/generic.py | python | NDFrame.ndim | (self) | return self._mgr.ndim | Return an int representing the number of axes / array dimensions.
Return 1 if Series. Otherwise return 2 if DataFrame.
See Also
--------
ndarray.ndim : Number of array dimensions.
Examples
--------
>>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})
>>> s.ndim
1
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df.ndim
2 | Return an int representing the number of axes / array dimensions. | [
"Return",
"an",
"int",
"representing",
"the",
"number",
"of",
"axes",
"/",
"array",
"dimensions",
"."
] | def ndim(self) -> int:
"""
Return an int representing the number of axes / array dimensions.
Return 1 if Series. Otherwise return 2 if DataFrame.
See Also
--------
ndarray.ndim : Number of array dimensions.
Examples
--------
>>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})
>>> s.ndim
1
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df.ndim
2
"""
return self._mgr.ndim | [
"def",
"ndim",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_mgr",
".",
"ndim"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L656-L676 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/cgi.py | python | FieldStorage.read_single | (self) | Internal: read an atomic part. | Internal: read an atomic part. | [
"Internal",
":",
"read",
"an",
"atomic",
"part",
"."
] | def read_single(self):
"""Internal: read an atomic part."""
if self.length >= 0:
self.read_binary()
self.skip_lines()
else:
self.read_lines()
self.file.seek(0) | [
"def",
"read_single",
"(",
"self",
")",
":",
"if",
"self",
".",
"length",
">=",
"0",
":",
"self",
".",
"read_binary",
"(",
")",
"self",
".",
"skip_lines",
"(",
")",
"else",
":",
"self",
".",
"read_lines",
"(",
")",
"self",
".",
"file",
".",
"seek",
"(",
"0",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/cgi.py#L689-L696 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | ScrollBar.GetThumbSize | (*args, **kwargs) | return _controls_.ScrollBar_GetThumbSize(*args, **kwargs) | GetThumbSize(self) -> int | GetThumbSize(self) -> int | [
"GetThumbSize",
"(",
"self",
")",
"-",
">",
"int"
] | def GetThumbSize(*args, **kwargs):
"""GetThumbSize(self) -> int"""
return _controls_.ScrollBar_GetThumbSize(*args, **kwargs) | [
"def",
"GetThumbSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ScrollBar_GetThumbSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2159-L2161 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/packaging/specifiers.py | python | BaseSpecifier.contains | (self, item, prereleases=None) | Determines if the given item is contained within this specifier. | Determines if the given item is contained within this specifier. | [
"Determines",
"if",
"the",
"given",
"item",
"is",
"contained",
"within",
"this",
"specifier",
"."
] | def contains(self, item, prereleases=None):
"""
Determines if the given item is contained within this specifier.
""" | [
"def",
"contains",
"(",
"self",
",",
"item",
",",
"prereleases",
"=",
"None",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/packaging/specifiers.py#L65-L68 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/command/install_lib.py | python | install_lib._all_packages | (pkg_name) | >>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo'] | >>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo'] | [
">>>",
"list",
"(",
"install_lib",
".",
"_all_packages",
"(",
"foo",
".",
"bar",
".",
"baz",
"))",
"[",
"foo",
".",
"bar",
".",
"baz",
"foo",
".",
"bar",
"foo",
"]"
] | def _all_packages(pkg_name):
"""
>>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo']
"""
while pkg_name:
yield pkg_name
pkg_name, sep, child = pkg_name.rpartition('.') | [
"def",
"_all_packages",
"(",
"pkg_name",
")",
":",
"while",
"pkg_name",
":",
"yield",
"pkg_name",
"pkg_name",
",",
"sep",
",",
"child",
"=",
"pkg_name",
".",
"rpartition",
"(",
"'.'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/command/install_lib.py#L40-L47 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/serialupdi/nvm.py | python | NvmUpdi.write_fuse | (self, address, data) | Writes one fuse value
:param address: address to write to
:param data: data to write | Writes one fuse value
:param address: address to write to
:param data: data to write | [
"Writes",
"one",
"fuse",
"value",
":",
"param",
"address",
":",
"address",
"to",
"write",
"to",
":",
"param",
"data",
":",
"data",
"to",
"write"
] | def write_fuse(self, address, data):
"""
Writes one fuse value
:param address: address to write to
:param data: data to write
"""
raise NotImplementedError("NVM stack not ready") | [
"def",
"write_fuse",
"(",
"self",
",",
"address",
",",
"data",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"NVM stack not ready\"",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/serialupdi/nvm.py#L43-L49 | ||
mitsuba-renderer/mitsuba | cfeb7766e7a1513492451f35dc65b86409655a7b | data/scons/qt5.py | python | _detect | (env) | return None | Not really safe, but fast method to detect the QT library | Not really safe, but fast method to detect the QT library | [
"Not",
"really",
"safe",
"but",
"fast",
"method",
"to",
"detect",
"the",
"QT",
"library"
] | def _detect(env):
"""Not really safe, but fast method to detect the QT library"""
try: return env['QTDIR']
except KeyError: pass
try: return os.environ['QTDIR']
except KeyError: pass
moc = env.WhereIs('moc-qt5') or env.WhereIs('moc5') or env.WhereIs('moc')
if moc:
QTDIR = os.path.dirname(os.path.dirname(moc))
# SCons.Warnings.warn(
# QtdirNotFound,
# "QTDIR variable is not defined, using moc executable as a hint (QTDIR=%s)" % QTDIR)
return QTDIR
raise SCons.Errors.StopError(
QtdirNotFound,
"Could not detect Qt 5 installation")
return None | [
"def",
"_detect",
"(",
"env",
")",
":",
"try",
":",
"return",
"env",
"[",
"'QTDIR'",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"os",
".",
"environ",
"[",
"'QTDIR'",
"]",
"except",
"KeyError",
":",
"pass",
"moc",
"=",
"env",
".",
"WhereIs",
"(",
"'moc-qt5'",
")",
"or",
"env",
".",
"WhereIs",
"(",
"'moc5'",
")",
"or",
"env",
".",
"WhereIs",
"(",
"'moc'",
")",
"if",
"moc",
":",
"QTDIR",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"moc",
")",
")",
"# SCons.Warnings.warn(",
"# QtdirNotFound,",
"# \"QTDIR variable is not defined, using moc executable as a hint (QTDIR=%s)\" % QTDIR)",
"return",
"QTDIR",
"raise",
"SCons",
".",
"Errors",
".",
"StopError",
"(",
"QtdirNotFound",
",",
"\"Could not detect Qt 5 installation\"",
")",
"return",
"None"
] | https://github.com/mitsuba-renderer/mitsuba/blob/cfeb7766e7a1513492451f35dc65b86409655a7b/data/scons/qt5.py#L195-L214 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | TextAttr.HasFontWeight | (*args, **kwargs) | return _controls_.TextAttr_HasFontWeight(*args, **kwargs) | HasFontWeight(self) -> bool | HasFontWeight(self) -> bool | [
"HasFontWeight",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasFontWeight(*args, **kwargs):
"""HasFontWeight(self) -> bool"""
return _controls_.TextAttr_HasFontWeight(*args, **kwargs) | [
"def",
"HasFontWeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_HasFontWeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L1792-L1794 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/arrayobj.py | python | get_array_memory_extents | (context, builder, arrty, arr, shapes, strides,
data) | return compute_memory_extents(context, builder, lower, upper, data) | Compute a half-open range [start, end) of pointer-sized integers
which fully contain the array data. | Compute a half-open range [start, end) of pointer-sized integers
which fully contain the array data. | [
"Compute",
"a",
"half",
"-",
"open",
"range",
"[",
"start",
"end",
")",
"of",
"pointer",
"-",
"sized",
"integers",
"which",
"fully",
"contain",
"the",
"array",
"data",
"."
] | def get_array_memory_extents(context, builder, arrty, arr, shapes, strides,
data):
"""
Compute a half-open range [start, end) of pointer-sized integers
which fully contain the array data.
"""
lower, upper = offset_bounds_from_strides(context, builder, arrty, arr,
shapes, strides)
return compute_memory_extents(context, builder, lower, upper, data) | [
"def",
"get_array_memory_extents",
"(",
"context",
",",
"builder",
",",
"arrty",
",",
"arr",
",",
"shapes",
",",
"strides",
",",
"data",
")",
":",
"lower",
",",
"upper",
"=",
"offset_bounds_from_strides",
"(",
"context",
",",
"builder",
",",
"arrty",
",",
"arr",
",",
"shapes",
",",
"strides",
")",
"return",
"compute_memory_extents",
"(",
"context",
",",
"builder",
",",
"lower",
",",
"upper",
",",
"data",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/arrayobj.py#L1124-L1132 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py | python | _RerouteMode.check | (cls, mode) | Check swap mode.
Args:
mode: an integer representing one of the modes.
Returns:
True if a is rerouted to b (mode is swap or a2b).
True if b is rerouted to a (mode is swap or b2a).
Raises:
ValueError: if mode is outside the enum range. | Check swap mode. | [
"Check",
"swap",
"mode",
"."
] | def check(cls, mode):
"""Check swap mode.
Args:
mode: an integer representing one of the modes.
Returns:
True if a is rerouted to b (mode is swap or a2b).
True if b is rerouted to a (mode is swap or b2a).
Raises:
ValueError: if mode is outside the enum range.
"""
if mode == cls.swap:
return True, True
elif mode == cls.b2a:
return False, True
elif mode == cls.a2b:
return True, False
else:
raise ValueError("Unknown _RerouteMode: {}".format(mode)) | [
"def",
"check",
"(",
"cls",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"cls",
".",
"swap",
":",
"return",
"True",
",",
"True",
"elif",
"mode",
"==",
"cls",
".",
"b2a",
":",
"return",
"False",
",",
"True",
"elif",
"mode",
"==",
"cls",
".",
"a2b",
":",
"return",
"True",
",",
"False",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown _RerouteMode: {}\"",
".",
"format",
"(",
"mode",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py#L66-L84 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/optim/optimizer.py | python | Optimizer.broadcast_params | (self, optim_result) | return new_param_group | Apply Broadcast operations in the sequential order of parameter groups.
Args:
optim_result(bool): The results of updating parameters. This input is used to ensure that the parameters are
updated before they are broadcast.
Returns:
bool, the status flag. | Apply Broadcast operations in the sequential order of parameter groups. | [
"Apply",
"Broadcast",
"operations",
"in",
"the",
"sequential",
"order",
"of",
"parameter",
"groups",
"."
] | def broadcast_params(self, optim_result):
"""
Apply Broadcast operations in the sequential order of parameter groups.
Args:
optim_result(bool): The results of updating parameters. This input is used to ensure that the parameters are
updated before they are broadcast.
Returns:
bool, the status flag.
"""
param_group = []
key_group = []
for _ in range(self.dev_num):
param_group.append(F.make_tuple())
key_group.append(F.make_tuple())
for i in range(self.param_length):
param_group[self.param_rank[i]] = param_group[self.param_rank[i]] + (self.parameters[i],)
key = P.MakeRefKey(self.param_names[i])()
key_group[self.param_rank[i]] = key_group[self.param_rank[i]] + (key,)
new_param_group = []
for root in range(self.dev_num):
ops = P.Broadcast(root)
if root > 0:
param_group[root] = F.depend(param_group[root], new_param_group[root-1])
else:
param_group[root] = F.depend(param_group[root], optim_result)
next_params = ops(param_group[root])
new_param_group.append(next_params)
for i in range(F.tuple_len(next_params)):
F.assign(key_group[root][i], next_params[i])
return new_param_group | [
"def",
"broadcast_params",
"(",
"self",
",",
"optim_result",
")",
":",
"param_group",
"=",
"[",
"]",
"key_group",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"dev_num",
")",
":",
"param_group",
".",
"append",
"(",
"F",
".",
"make_tuple",
"(",
")",
")",
"key_group",
".",
"append",
"(",
"F",
".",
"make_tuple",
"(",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"param_length",
")",
":",
"param_group",
"[",
"self",
".",
"param_rank",
"[",
"i",
"]",
"]",
"=",
"param_group",
"[",
"self",
".",
"param_rank",
"[",
"i",
"]",
"]",
"+",
"(",
"self",
".",
"parameters",
"[",
"i",
"]",
",",
")",
"key",
"=",
"P",
".",
"MakeRefKey",
"(",
"self",
".",
"param_names",
"[",
"i",
"]",
")",
"(",
")",
"key_group",
"[",
"self",
".",
"param_rank",
"[",
"i",
"]",
"]",
"=",
"key_group",
"[",
"self",
".",
"param_rank",
"[",
"i",
"]",
"]",
"+",
"(",
"key",
",",
")",
"new_param_group",
"=",
"[",
"]",
"for",
"root",
"in",
"range",
"(",
"self",
".",
"dev_num",
")",
":",
"ops",
"=",
"P",
".",
"Broadcast",
"(",
"root",
")",
"if",
"root",
">",
"0",
":",
"param_group",
"[",
"root",
"]",
"=",
"F",
".",
"depend",
"(",
"param_group",
"[",
"root",
"]",
",",
"new_param_group",
"[",
"root",
"-",
"1",
"]",
")",
"else",
":",
"param_group",
"[",
"root",
"]",
"=",
"F",
".",
"depend",
"(",
"param_group",
"[",
"root",
"]",
",",
"optim_result",
")",
"next_params",
"=",
"ops",
"(",
"param_group",
"[",
"root",
"]",
")",
"new_param_group",
".",
"append",
"(",
"next_params",
")",
"for",
"i",
"in",
"range",
"(",
"F",
".",
"tuple_len",
"(",
"next_params",
")",
")",
":",
"F",
".",
"assign",
"(",
"key_group",
"[",
"root",
"]",
"[",
"i",
"]",
",",
"next_params",
"[",
"i",
"]",
")",
"return",
"new_param_group"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/optim/optimizer.py#L668-L698 | |
nasa/trick | 7b85aa66329d62fe8816462627c09a353aac8299 | share/trick/trickops/TrickWorkflow.py | python | TrickWorkflow.get_sims | (self, labels=None) | return sims_found | Get a list of Sim() instances by label or labels listed in self.config_file
>>> tw = TrickWorkflow(project_top_level=this_trick, log_dir='/tmp/', trick_dir=this_trick, config_file=os.path.join(this_trick,"share/trick/trickops/tests/trick_sims.yml"))
>>> sims = tw.get_sims(['unit_test'])
Parameters
----------
labels : str or list or None
label or labels that each sim must have to be returned by this functionr.
If None, return all sims
Returns
-------
list
List of Sim() instances matching the label(s) given or [] if none can be
found
Raises
------
TypeError
If labels is not a str or list | Get a list of Sim() instances by label or labels listed in self.config_file | [
"Get",
"a",
"list",
"of",
"Sim",
"()",
"instances",
"by",
"label",
"or",
"labels",
"listed",
"in",
"self",
".",
"config_file"
] | def get_sims(self, labels=None):
"""
Get a list of Sim() instances by label or labels listed in self.config_file
>>> tw = TrickWorkflow(project_top_level=this_trick, log_dir='/tmp/', trick_dir=this_trick, config_file=os.path.join(this_trick,"share/trick/trickops/tests/trick_sims.yml"))
>>> sims = tw.get_sims(['unit_test'])
Parameters
----------
labels : str or list or None
label or labels that each sim must have to be returned by this functionr.
If None, return all sims
Returns
-------
list
List of Sim() instances matching the label(s) given or [] if none can be
found
Raises
------
TypeError
If labels is not a str or list
"""
# If no labels given, just return the full list
if not labels:
return self.sims
sims_found = []
ls = []
if type(labels) == str:
ls = [labels]
elif type(labels) == list:
ls = [str(l) for l in labels]
else:
raise TypeError('get_sims() only accepts a label string or list of label strings')
for sim in self.sims:
if all(l in sim.labels for l in ls):
sims_found.append(sim)
return sims_found | [
"def",
"get_sims",
"(",
"self",
",",
"labels",
"=",
"None",
")",
":",
"# If no labels given, just return the full list",
"if",
"not",
"labels",
":",
"return",
"self",
".",
"sims",
"sims_found",
"=",
"[",
"]",
"ls",
"=",
"[",
"]",
"if",
"type",
"(",
"labels",
")",
"==",
"str",
":",
"ls",
"=",
"[",
"labels",
"]",
"elif",
"type",
"(",
"labels",
")",
"==",
"list",
":",
"ls",
"=",
"[",
"str",
"(",
"l",
")",
"for",
"l",
"in",
"labels",
"]",
"else",
":",
"raise",
"TypeError",
"(",
"'get_sims() only accepts a label string or list of label strings'",
")",
"for",
"sim",
"in",
"self",
".",
"sims",
":",
"if",
"all",
"(",
"l",
"in",
"sim",
".",
"labels",
"for",
"l",
"in",
"ls",
")",
":",
"sims_found",
".",
"append",
"(",
"sim",
")",
"return",
"sims_found"
] | https://github.com/nasa/trick/blob/7b85aa66329d62fe8816462627c09a353aac8299/share/trick/trickops/TrickWorkflow.py#L188-L226 | |
apache/madlib | be297fe6beada0640f93317e8948834032718e32 | src/madpack/upgrade_util.py | python | ScriptCleaner._get_all_aggregate_patterns | (self) | return aggregate_patterns | Creates a list of string patterns that represent all possible
'CREATE AGGREGATE' statements except ones that are being
replaced/introduced as part of this upgrade. | Creates a list of string patterns that represent all possible
'CREATE AGGREGATE' statements except ones that are being
replaced/introduced as part of this upgrade. | [
"Creates",
"a",
"list",
"of",
"string",
"patterns",
"that",
"represent",
"all",
"possible",
"CREATE",
"AGGREGATE",
"statements",
"except",
"ones",
"that",
"are",
"being",
"replaced",
"/",
"introduced",
"as",
"part",
"of",
"this",
"upgrade",
"."
] | def _get_all_aggregate_patterns(self):
"""
Creates a list of string patterns that represent all possible
'CREATE AGGREGATE' statements except ones that are being
replaced/introduced as part of this upgrade.
"""
self._get_existing_uda()
aggregate_patterns = []
for each_uda, uda_details in self._existing_uda.iteritems():
for each_item in uda_details:
if each_uda in self._ch.uda:
if each_item in self._ch.uda[each_uda]:
continue
p_arg_str = ''
argument = each_item['argument']
args = argument.split(',')
for arg in args:
arg = self._rewrite_type_in(arg.strip())
if p_arg_str == '':
p_arg_str += '%s\s*' % arg
else:
p_arg_str += ',\s*%s\s*' % arg
p_str = "CREATE\s+(ORDERED\s)*\s*AGGREGATE" \
"\s+%s\.(%s)\s*\(\s*%s\)(.*?);" % (self._schema,
each_uda,
p_arg_str)
aggregate_patterns.append(p_str)
return aggregate_patterns | [
"def",
"_get_all_aggregate_patterns",
"(",
"self",
")",
":",
"self",
".",
"_get_existing_uda",
"(",
")",
"aggregate_patterns",
"=",
"[",
"]",
"for",
"each_uda",
",",
"uda_details",
"in",
"self",
".",
"_existing_uda",
".",
"iteritems",
"(",
")",
":",
"for",
"each_item",
"in",
"uda_details",
":",
"if",
"each_uda",
"in",
"self",
".",
"_ch",
".",
"uda",
":",
"if",
"each_item",
"in",
"self",
".",
"_ch",
".",
"uda",
"[",
"each_uda",
"]",
":",
"continue",
"p_arg_str",
"=",
"''",
"argument",
"=",
"each_item",
"[",
"'argument'",
"]",
"args",
"=",
"argument",
".",
"split",
"(",
"','",
")",
"for",
"arg",
"in",
"args",
":",
"arg",
"=",
"self",
".",
"_rewrite_type_in",
"(",
"arg",
".",
"strip",
"(",
")",
")",
"if",
"p_arg_str",
"==",
"''",
":",
"p_arg_str",
"+=",
"'%s\\s*'",
"%",
"arg",
"else",
":",
"p_arg_str",
"+=",
"',\\s*%s\\s*'",
"%",
"arg",
"p_str",
"=",
"\"CREATE\\s+(ORDERED\\s)*\\s*AGGREGATE\"",
"\"\\s+%s\\.(%s)\\s*\\(\\s*%s\\)(.*?);\"",
"%",
"(",
"self",
".",
"_schema",
",",
"each_uda",
",",
"p_arg_str",
")",
"aggregate_patterns",
".",
"append",
"(",
"p_str",
")",
"return",
"aggregate_patterns"
] | https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/upgrade_util.py#L1115-L1144 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/ceph_manager.py | python | CephManager.list_pools | (self) | return [str(i['pool_name']) for i in osd_dump['pools']] | list all pool names | list all pool names | [
"list",
"all",
"pool",
"names"
] | def list_pools(self):
"""
list all pool names
"""
osd_dump = self.get_osd_dump_json()
self.log(osd_dump['pools'])
return [str(i['pool_name']) for i in osd_dump['pools']] | [
"def",
"list_pools",
"(",
"self",
")",
":",
"osd_dump",
"=",
"self",
".",
"get_osd_dump_json",
"(",
")",
"self",
".",
"log",
"(",
"osd_dump",
"[",
"'pools'",
"]",
")",
"return",
"[",
"str",
"(",
"i",
"[",
"'pool_name'",
"]",
")",
"for",
"i",
"in",
"osd_dump",
"[",
"'pools'",
"]",
"]"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph_manager.py#L1919-L1925 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/integration/AsyncStateMachine.py | python | AsyncStateMachine.outReadEvent | (self, readBuffer) | Called when a read operation completes.
May be overridden in subclass. | Called when a read operation completes. | [
"Called",
"when",
"a",
"read",
"operation",
"completes",
"."
] | def outReadEvent(self, readBuffer):
"""Called when a read operation completes.
May be overridden in subclass."""
pass | [
"def",
"outReadEvent",
"(",
"self",
",",
"readBuffer",
")",
":",
"pass"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/integration/AsyncStateMachine.py#L106-L110 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | AuiNotebook.OnChildFocusNotebook | (self, event) | Handles the ``wx.EVT_CHILD_FOCUS`` event for :class:`AuiNotebook`.
:param `event`: a :class:`ChildFocusEvent` event to be processed. | Handles the ``wx.EVT_CHILD_FOCUS`` event for :class:`AuiNotebook`. | [
"Handles",
"the",
"wx",
".",
"EVT_CHILD_FOCUS",
"event",
"for",
":",
"class",
":",
"AuiNotebook",
"."
] | def OnChildFocusNotebook(self, event):
"""
Handles the ``wx.EVT_CHILD_FOCUS`` event for :class:`AuiNotebook`.
:param `event`: a :class:`ChildFocusEvent` event to be processed.
"""
# if we're dragging a tab, don't change the current selection.
# This code prevents a bug that used to happen when the hint window
# was hidden. In the bug, the focus would return to the notebook
# child, which would then enter this handler and call
# SetSelection, which is not desired turn tab dragging.
event.Skip()
all_panes = self._mgr.GetAllPanes()
for pane in all_panes:
if pane.name == "dummy":
continue
tabframe = pane.window
if tabframe._tabs.IsDragging():
return | [
"def",
"OnChildFocusNotebook",
"(",
"self",
",",
"event",
")",
":",
"# if we're dragging a tab, don't change the current selection.",
"# This code prevents a bug that used to happen when the hint window",
"# was hidden. In the bug, the focus would return to the notebook",
"# child, which would then enter this handler and call",
"# SetSelection, which is not desired turn tab dragging.",
"event",
".",
"Skip",
"(",
")",
"all_panes",
"=",
"self",
".",
"_mgr",
".",
"GetAllPanes",
"(",
")",
"for",
"pane",
"in",
"all_panes",
":",
"if",
"pane",
".",
"name",
"==",
"\"dummy\"",
":",
"continue",
"tabframe",
"=",
"pane",
".",
"window",
"if",
"tabframe",
".",
"_tabs",
".",
"IsDragging",
"(",
")",
":",
"return"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L5197-L5218 | ||
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | python/caffe/draw.py | python | get_pydot_graph | (caffe_net, rankdir, label_edges=True, phase=None) | return pydot_graph | Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_net : object
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
label_edges : boolean, optional
Label the edges (default is True).
phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional
Include layers from this network phase. If None, include all layers.
(the default is None)
Returns
-------
pydot graph object | Create a data structure which represents the `caffe_net`. | [
"Create",
"a",
"data",
"structure",
"which",
"represents",
"the",
"caffe_net",
"."
] | def get_pydot_graph(caffe_net, rankdir, label_edges=True, phase=None):
"""Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_net : object
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
label_edges : boolean, optional
Label the edges (default is True).
phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional
Include layers from this network phase. If None, include all layers.
(the default is None)
Returns
-------
pydot graph object
"""
pydot_graph = pydot.Dot(caffe_net.name if caffe_net.name else 'Net',
graph_type='digraph',
rankdir=rankdir)
pydot_nodes = {}
pydot_edges = []
for layer in caffe_net.layer:
if phase is not None:
included = False
if len(layer.include) == 0:
included = True
if len(layer.include) > 0 and len(layer.exclude) > 0:
raise ValueError('layer ' + layer.name + ' has both include '
'and exclude specified.')
for layer_phase in layer.include:
included = included or layer_phase.phase == phase
for layer_phase in layer.exclude:
included = included and not layer_phase.phase == phase
if not included:
continue
node_label = get_layer_label(layer, rankdir)
node_name = "%s_%s" % (layer.name, layer.type)
if (len(layer.bottom) == 1 and len(layer.top) == 1 and
layer.bottom[0] == layer.top[0]):
# We have an in-place neuron layer.
pydot_nodes[node_name] = pydot.Node(node_label,
**NEURON_LAYER_STYLE)
else:
layer_style = LAYER_STYLE_DEFAULT
layer_style['fillcolor'] = choose_color_by_layertype(layer.type)
pydot_nodes[node_name] = pydot.Node(node_label, **layer_style)
for bottom_blob in layer.bottom:
pydot_nodes[bottom_blob + '_blob'] = pydot.Node('%s' % bottom_blob,
**BLOB_STYLE)
edge_label = '""'
pydot_edges.append({'src': bottom_blob + '_blob',
'dst': node_name,
'label': edge_label})
for top_blob in layer.top:
pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob))
if label_edges:
edge_label = get_edge_label(layer)
else:
edge_label = '""'
pydot_edges.append({'src': node_name,
'dst': top_blob + '_blob',
'label': edge_label})
# Now, add the nodes and edges to the graph.
for node in pydot_nodes.values():
pydot_graph.add_node(node)
for edge in pydot_edges:
pydot_graph.add_edge(
pydot.Edge(pydot_nodes[edge['src']],
pydot_nodes[edge['dst']],
label=edge['label']))
return pydot_graph | [
"def",
"get_pydot_graph",
"(",
"caffe_net",
",",
"rankdir",
",",
"label_edges",
"=",
"True",
",",
"phase",
"=",
"None",
")",
":",
"pydot_graph",
"=",
"pydot",
".",
"Dot",
"(",
"caffe_net",
".",
"name",
"if",
"caffe_net",
".",
"name",
"else",
"'Net'",
",",
"graph_type",
"=",
"'digraph'",
",",
"rankdir",
"=",
"rankdir",
")",
"pydot_nodes",
"=",
"{",
"}",
"pydot_edges",
"=",
"[",
"]",
"for",
"layer",
"in",
"caffe_net",
".",
"layer",
":",
"if",
"phase",
"is",
"not",
"None",
":",
"included",
"=",
"False",
"if",
"len",
"(",
"layer",
".",
"include",
")",
"==",
"0",
":",
"included",
"=",
"True",
"if",
"len",
"(",
"layer",
".",
"include",
")",
">",
"0",
"and",
"len",
"(",
"layer",
".",
"exclude",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'layer '",
"+",
"layer",
".",
"name",
"+",
"' has both include '",
"'and exclude specified.'",
")",
"for",
"layer_phase",
"in",
"layer",
".",
"include",
":",
"included",
"=",
"included",
"or",
"layer_phase",
".",
"phase",
"==",
"phase",
"for",
"layer_phase",
"in",
"layer",
".",
"exclude",
":",
"included",
"=",
"included",
"and",
"not",
"layer_phase",
".",
"phase",
"==",
"phase",
"if",
"not",
"included",
":",
"continue",
"node_label",
"=",
"get_layer_label",
"(",
"layer",
",",
"rankdir",
")",
"node_name",
"=",
"\"%s_%s\"",
"%",
"(",
"layer",
".",
"name",
",",
"layer",
".",
"type",
")",
"if",
"(",
"len",
"(",
"layer",
".",
"bottom",
")",
"==",
"1",
"and",
"len",
"(",
"layer",
".",
"top",
")",
"==",
"1",
"and",
"layer",
".",
"bottom",
"[",
"0",
"]",
"==",
"layer",
".",
"top",
"[",
"0",
"]",
")",
":",
"# We have an in-place neuron layer.",
"pydot_nodes",
"[",
"node_name",
"]",
"=",
"pydot",
".",
"Node",
"(",
"node_label",
",",
"*",
"*",
"NEURON_LAYER_STYLE",
")",
"else",
":",
"layer_style",
"=",
"LAYER_STYLE_DEFAULT",
"layer_style",
"[",
"'fillcolor'",
"]",
"=",
"choose_color_by_layertype",
"(",
"layer",
".",
"type",
")",
"pydot_nodes",
"[",
"node_name",
"]",
"=",
"pydot",
".",
"Node",
"(",
"node_label",
",",
"*",
"*",
"layer_style",
")",
"for",
"bottom_blob",
"in",
"layer",
".",
"bottom",
":",
"pydot_nodes",
"[",
"bottom_blob",
"+",
"'_blob'",
"]",
"=",
"pydot",
".",
"Node",
"(",
"'%s'",
"%",
"bottom_blob",
",",
"*",
"*",
"BLOB_STYLE",
")",
"edge_label",
"=",
"'\"\"'",
"pydot_edges",
".",
"append",
"(",
"{",
"'src'",
":",
"bottom_blob",
"+",
"'_blob'",
",",
"'dst'",
":",
"node_name",
",",
"'label'",
":",
"edge_label",
"}",
")",
"for",
"top_blob",
"in",
"layer",
".",
"top",
":",
"pydot_nodes",
"[",
"top_blob",
"+",
"'_blob'",
"]",
"=",
"pydot",
".",
"Node",
"(",
"'%s'",
"%",
"(",
"top_blob",
")",
")",
"if",
"label_edges",
":",
"edge_label",
"=",
"get_edge_label",
"(",
"layer",
")",
"else",
":",
"edge_label",
"=",
"'\"\"'",
"pydot_edges",
".",
"append",
"(",
"{",
"'src'",
":",
"node_name",
",",
"'dst'",
":",
"top_blob",
"+",
"'_blob'",
",",
"'label'",
":",
"edge_label",
"}",
")",
"# Now, add the nodes and edges to the graph.",
"for",
"node",
"in",
"pydot_nodes",
".",
"values",
"(",
")",
":",
"pydot_graph",
".",
"add_node",
"(",
"node",
")",
"for",
"edge",
"in",
"pydot_edges",
":",
"pydot_graph",
".",
"add_edge",
"(",
"pydot",
".",
"Edge",
"(",
"pydot_nodes",
"[",
"edge",
"[",
"'src'",
"]",
"]",
",",
"pydot_nodes",
"[",
"edge",
"[",
"'dst'",
"]",
"]",
",",
"label",
"=",
"edge",
"[",
"'label'",
"]",
")",
")",
"return",
"pydot_graph"
] | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/caffe/draw.py#L130-L202 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/build/android/pylib/android_commands.py | python | AndroidCommands.CloseApplication | (self, package) | Attempt to close down the application, using increasing violence.
Args:
package: Name of the process to kill off, e.g.
com.google.android.apps.chrome | Attempt to close down the application, using increasing violence. | [
"Attempt",
"to",
"close",
"down",
"the",
"application",
"using",
"increasing",
"violence",
"."
] | def CloseApplication(self, package):
"""Attempt to close down the application, using increasing violence.
Args:
package: Name of the process to kill off, e.g.
com.google.android.apps.chrome
"""
self.RunShellCommand('am force-stop ' + package) | [
"def",
"CloseApplication",
"(",
"self",
",",
"package",
")",
":",
"self",
".",
"RunShellCommand",
"(",
"'am force-stop '",
"+",
"package",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/pylib/android_commands.py#L549-L556 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/indexes/base.py | python | Index.is_unique | (self) | return self._engine.is_unique | Return if the index has unique values. | Return if the index has unique values. | [
"Return",
"if",
"the",
"index",
"has",
"unique",
"values",
"."
] | def is_unique(self):
"""
Return if the index has unique values.
"""
return self._engine.is_unique | [
"def",
"is_unique",
"(",
"self",
")",
":",
"return",
"self",
".",
"_engine",
".",
"is_unique"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/base.py#L1659-L1663 | |
ku-nlp/jumanpp | 008e73b9cf876ce50ba5e751ac7108e68796cb1f | script/git-clang-format.py | python | print_diff | (old_tree, new_tree) | Print the diff between the two trees to stdout. | Print the diff between the two trees to stdout. | [
"Print",
"the",
"diff",
"between",
"the",
"two",
"trees",
"to",
"stdout",
"."
] | def print_diff(old_tree, new_tree):
"""Print the diff between the two trees to stdout."""
# We use the porcelain 'diff' and not plumbing 'diff-tree' because the output
# is expected to be viewed by the user, and only the former does nice things
# like color and pagination.
#
# We also only print modified files since `new_tree` only contains the files
# that were modified, so unmodified files would show as deleted without the
# filter.
subprocess.check_call(['git', 'diff', '--diff-filter=M', old_tree, new_tree,
'--']) | [
"def",
"print_diff",
"(",
"old_tree",
",",
"new_tree",
")",
":",
"# We use the porcelain 'diff' and not plumbing 'diff-tree' because the output",
"# is expected to be viewed by the user, and only the former does nice things",
"# like color and pagination.",
"#",
"# We also only print modified files since `new_tree` only contains the files",
"# that were modified, so unmodified files would show as deleted without the",
"# filter.",
"subprocess",
".",
"check_call",
"(",
"[",
"'git'",
",",
"'diff'",
",",
"'--diff-filter=M'",
",",
"old_tree",
",",
"new_tree",
",",
"'--'",
"]",
")"
] | https://github.com/ku-nlp/jumanpp/blob/008e73b9cf876ce50ba5e751ac7108e68796cb1f/script/git-clang-format.py#L479-L489 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/common.py | python | is_bool_indexer | (key: Any) | return False | Check whether `key` is a valid boolean indexer.
Parameters
----------
key : Any
Only list-likes may be considered boolean indexers.
All other types are not considered a boolean indexer.
For array-like input, boolean ndarrays or ExtensionArrays
with ``_is_boolean`` set are considered boolean indexers.
Returns
-------
bool
Whether `key` is a valid boolean indexer.
Raises
------
ValueError
When the array is an object-dtype ndarray or ExtensionArray
and contains missing values.
See Also
--------
check_array_indexer : Check that `key` is a valid array to index,
and convert to an ndarray. | Check whether `key` is a valid boolean indexer. | [
"Check",
"whether",
"key",
"is",
"a",
"valid",
"boolean",
"indexer",
"."
] | def is_bool_indexer(key: Any) -> bool:
"""
Check whether `key` is a valid boolean indexer.
Parameters
----------
key : Any
Only list-likes may be considered boolean indexers.
All other types are not considered a boolean indexer.
For array-like input, boolean ndarrays or ExtensionArrays
with ``_is_boolean`` set are considered boolean indexers.
Returns
-------
bool
Whether `key` is a valid boolean indexer.
Raises
------
ValueError
When the array is an object-dtype ndarray or ExtensionArray
and contains missing values.
See Also
--------
check_array_indexer : Check that `key` is a valid array to index,
and convert to an ndarray.
"""
if isinstance(key, (ABCSeries, np.ndarray, ABCIndex)) or (
is_array_like(key) and is_extension_array_dtype(key.dtype)
):
if key.dtype == np.object_:
key = np.asarray(values_from_object(key))
if not lib.is_bool_array(key):
na_msg = "Cannot mask with non-boolean array containing NA / NaN values"
if isna(key).any():
raise ValueError(na_msg)
return False
return True
elif is_bool_dtype(key.dtype):
return True
elif isinstance(key, list):
try:
arr = np.asarray(key)
return arr.dtype == np.bool_ and len(arr) == len(key)
except TypeError: # pragma: no cover
return False
return False | [
"def",
"is_bool_indexer",
"(",
"key",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"key",
",",
"(",
"ABCSeries",
",",
"np",
".",
"ndarray",
",",
"ABCIndex",
")",
")",
"or",
"(",
"is_array_like",
"(",
"key",
")",
"and",
"is_extension_array_dtype",
"(",
"key",
".",
"dtype",
")",
")",
":",
"if",
"key",
".",
"dtype",
"==",
"np",
".",
"object_",
":",
"key",
"=",
"np",
".",
"asarray",
"(",
"values_from_object",
"(",
"key",
")",
")",
"if",
"not",
"lib",
".",
"is_bool_array",
"(",
"key",
")",
":",
"na_msg",
"=",
"\"Cannot mask with non-boolean array containing NA / NaN values\"",
"if",
"isna",
"(",
"key",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"na_msg",
")",
"return",
"False",
"return",
"True",
"elif",
"is_bool_dtype",
"(",
"key",
".",
"dtype",
")",
":",
"return",
"True",
"elif",
"isinstance",
"(",
"key",
",",
"list",
")",
":",
"try",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"key",
")",
"return",
"arr",
".",
"dtype",
"==",
"np",
".",
"bool_",
"and",
"len",
"(",
"arr",
")",
"==",
"len",
"(",
"key",
")",
"except",
"TypeError",
":",
"# pragma: no cover",
"return",
"False",
"return",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/common.py#L99-L148 | |
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/tomviz/io/dm.py | python | FileDM.getSlice | (self, index, sliceZ, sliceZ2=0) | return outputDict | Retrieve a slice of a dataset from the DM file.
The data set will have a shape according to:
3D = [sliceZ,Y,X] or 4D: [sliceZ2,sliceZ,Y,X]
Note: Most DM3 and DM4 files contain a small "thumbnail" as the
first dataset written as RGB data. This function ignores that dataset
if it exists. To retrieve the thumbnail use the getThumbnail() function
Warning: DM4 files with 4D data sets are written as [X,Y,Z1,Z2].
This code currently gets the [X,Y] slice. Getting the [Z1,Z2] slice
is not yet implemented. Use the getMemmap() function to
retrieve arbitrary slices of large data sets.
Parameters
----------
index : int
The number of the dataset in the DM file.
sliceZ : int
The slice to get along the first dimension (C-ordering)
for 3D datasets or 4D datasets.
sliceZ2 : int
For 4D dataset
Returns
-------
: dict
A dictionary containing meta data and the data. | Retrieve a slice of a dataset from the DM file.
The data set will have a shape according to:
3D = [sliceZ,Y,X] or 4D: [sliceZ2,sliceZ,Y,X] | [
"Retrieve",
"a",
"slice",
"of",
"a",
"dataset",
"from",
"the",
"DM",
"file",
".",
"The",
"data",
"set",
"will",
"have",
"a",
"shape",
"according",
"to",
":",
"3D",
"=",
"[",
"sliceZ",
"Y",
"X",
"]",
"or",
"4D",
":",
"[",
"sliceZ2",
"sliceZ",
"Y",
"X",
"]"
] | def getSlice(self, index, sliceZ, sliceZ2=0):
"""Retrieve a slice of a dataset from the DM file.
The data set will have a shape according to:
3D = [sliceZ,Y,X] or 4D: [sliceZ2,sliceZ,Y,X]
Note: Most DM3 and DM4 files contain a small "thumbnail" as the
first dataset written as RGB data. This function ignores that dataset
if it exists. To retrieve the thumbnail use the getThumbnail() function
Warning: DM4 files with 4D data sets are written as [X,Y,Z1,Z2].
This code currently gets the [X,Y] slice. Getting the [Z1,Z2] slice
is not yet implemented. Use the getMemmap() function to
retrieve arbitrary slices of large data sets.
Parameters
----------
index : int
The number of the dataset in the DM file.
sliceZ : int
The slice to get along the first dimension (C-ordering)
for 3D datasets or 4D datasets.
sliceZ2 : int
For 4D dataset
Returns
-------
: dict
A dictionary containing meta data and the data.
"""
# The first dataset is usually a thumbnail.
# Test for this and skip the thumbnail automatically
if self.numObjects == 1:
ii = index
else:
ii = index + 1
# Check that the dataset exists.
try:
self._checkIndex(ii)
except Exception:
raise
# Check sliceZ and sliceZ2 are within the data array size bounds
if sliceZ > (self.zSize[ii] - 1):
raise IndexError(
'Index out of range, trying to access element {} of {} \
valid elements'.format(sliceZ, self.zSize))
if sliceZ2 > (self.zSize2[ii] - 1):
raise IndexError(
'Index out of range, trying to access element {} of {} \
valid elements'.format(sliceZ2, self.zSize2))
# Seek to start of dataset from beginning of the file
self.seek(self.fid, self.dataOffset[ii], 0)
outputDict = {'filename': os_basename(self.filename)}
# Parse the dataset to see what type it is (image, 3D image series,
# spectra, 4D, etc.)
if self.xSize[ii] > 0:
# determine the number of bytes to skip
pixelCount = int(self.xSize[ii]) * int(self.ySize[ii])
byteCount = pixelCount * np.dtype(self._DM2NPDataType(
self.dataType[ii])).itemsize
jj = 0 # counter to determine where the first scale value starts
for nn in self.dataShape[0:ii]:
# sum up all number of dimensions for previous datasets
jj += nn
if self.zSize[ii] == 1: # 2D data
outputDict['data'] = self.fromfile(self.fid, count=pixelCount,
dtype=self._DM2NPDataType(
self.dataType[ii])
).reshape(
(self.ySize[ii],
self.xSize[ii]))
elif self.zSize2[ii] > 1: # 4D data
# skip ahead from current position
self.seek(self.fid, sliceZ * sliceZ2 * byteCount, 1)
outputDict['data'] = self.fromfile(self.fid, count=pixelCount,
dtype=self._DM2NPDataType(
self.dataType[ii])
).reshape(
(self.ySize[ii],
self.xSize[ii]))
else: # 3D array
# skip ahead from current position
self.seek(self.fid, sliceZ * byteCount, 1)
outputDict['data'] = self.fromfile(self.fid, count=pixelCount,
dtype=self._DM2NPDataType(
self.dataType[ii])
).reshape(
(self.ySize[ii],
self.xSize[ii]))
# Return the proper meta data for this one image
# need to reverse the order to match the C-ordering of the data
outputDict['pixelUnit'] = self.scaleUnit[jj:jj + 2][::-1]
outputDict['pixelSize'] = self.scale[jj:jj + 2][::-1]
outputDict['pixelOrigin'] = self.origin[jj:jj + 2][::-1]
# Ensure the data is loaded into memory from the buffer
if self._on_memory:
outputDict['data'] = np.array(outputDict['data'])
return outputDict | [
"def",
"getSlice",
"(",
"self",
",",
"index",
",",
"sliceZ",
",",
"sliceZ2",
"=",
"0",
")",
":",
"# The first dataset is usually a thumbnail.",
"# Test for this and skip the thumbnail automatically",
"if",
"self",
".",
"numObjects",
"==",
"1",
":",
"ii",
"=",
"index",
"else",
":",
"ii",
"=",
"index",
"+",
"1",
"# Check that the dataset exists.",
"try",
":",
"self",
".",
"_checkIndex",
"(",
"ii",
")",
"except",
"Exception",
":",
"raise",
"# Check sliceZ and sliceZ2 are within the data array size bounds",
"if",
"sliceZ",
">",
"(",
"self",
".",
"zSize",
"[",
"ii",
"]",
"-",
"1",
")",
":",
"raise",
"IndexError",
"(",
"'Index out of range, trying to access element {} of {} \\\n valid elements'",
".",
"format",
"(",
"sliceZ",
",",
"self",
".",
"zSize",
")",
")",
"if",
"sliceZ2",
">",
"(",
"self",
".",
"zSize2",
"[",
"ii",
"]",
"-",
"1",
")",
":",
"raise",
"IndexError",
"(",
"'Index out of range, trying to access element {} of {} \\\n valid elements'",
".",
"format",
"(",
"sliceZ2",
",",
"self",
".",
"zSize2",
")",
")",
"# Seek to start of dataset from beginning of the file",
"self",
".",
"seek",
"(",
"self",
".",
"fid",
",",
"self",
".",
"dataOffset",
"[",
"ii",
"]",
",",
"0",
")",
"outputDict",
"=",
"{",
"'filename'",
":",
"os_basename",
"(",
"self",
".",
"filename",
")",
"}",
"# Parse the dataset to see what type it is (image, 3D image series,",
"# spectra, 4D, etc.)",
"if",
"self",
".",
"xSize",
"[",
"ii",
"]",
">",
"0",
":",
"# determine the number of bytes to skip",
"pixelCount",
"=",
"int",
"(",
"self",
".",
"xSize",
"[",
"ii",
"]",
")",
"*",
"int",
"(",
"self",
".",
"ySize",
"[",
"ii",
"]",
")",
"byteCount",
"=",
"pixelCount",
"*",
"np",
".",
"dtype",
"(",
"self",
".",
"_DM2NPDataType",
"(",
"self",
".",
"dataType",
"[",
"ii",
"]",
")",
")",
".",
"itemsize",
"jj",
"=",
"0",
"# counter to determine where the first scale value starts",
"for",
"nn",
"in",
"self",
".",
"dataShape",
"[",
"0",
":",
"ii",
"]",
":",
"# sum up all number of dimensions for previous datasets",
"jj",
"+=",
"nn",
"if",
"self",
".",
"zSize",
"[",
"ii",
"]",
"==",
"1",
":",
"# 2D data",
"outputDict",
"[",
"'data'",
"]",
"=",
"self",
".",
"fromfile",
"(",
"self",
".",
"fid",
",",
"count",
"=",
"pixelCount",
",",
"dtype",
"=",
"self",
".",
"_DM2NPDataType",
"(",
"self",
".",
"dataType",
"[",
"ii",
"]",
")",
")",
".",
"reshape",
"(",
"(",
"self",
".",
"ySize",
"[",
"ii",
"]",
",",
"self",
".",
"xSize",
"[",
"ii",
"]",
")",
")",
"elif",
"self",
".",
"zSize2",
"[",
"ii",
"]",
">",
"1",
":",
"# 4D data",
"# skip ahead from current position",
"self",
".",
"seek",
"(",
"self",
".",
"fid",
",",
"sliceZ",
"*",
"sliceZ2",
"*",
"byteCount",
",",
"1",
")",
"outputDict",
"[",
"'data'",
"]",
"=",
"self",
".",
"fromfile",
"(",
"self",
".",
"fid",
",",
"count",
"=",
"pixelCount",
",",
"dtype",
"=",
"self",
".",
"_DM2NPDataType",
"(",
"self",
".",
"dataType",
"[",
"ii",
"]",
")",
")",
".",
"reshape",
"(",
"(",
"self",
".",
"ySize",
"[",
"ii",
"]",
",",
"self",
".",
"xSize",
"[",
"ii",
"]",
")",
")",
"else",
":",
"# 3D array",
"# skip ahead from current position",
"self",
".",
"seek",
"(",
"self",
".",
"fid",
",",
"sliceZ",
"*",
"byteCount",
",",
"1",
")",
"outputDict",
"[",
"'data'",
"]",
"=",
"self",
".",
"fromfile",
"(",
"self",
".",
"fid",
",",
"count",
"=",
"pixelCount",
",",
"dtype",
"=",
"self",
".",
"_DM2NPDataType",
"(",
"self",
".",
"dataType",
"[",
"ii",
"]",
")",
")",
".",
"reshape",
"(",
"(",
"self",
".",
"ySize",
"[",
"ii",
"]",
",",
"self",
".",
"xSize",
"[",
"ii",
"]",
")",
")",
"# Return the proper meta data for this one image",
"# need to reverse the order to match the C-ordering of the data",
"outputDict",
"[",
"'pixelUnit'",
"]",
"=",
"self",
".",
"scaleUnit",
"[",
"jj",
":",
"jj",
"+",
"2",
"]",
"[",
":",
":",
"-",
"1",
"]",
"outputDict",
"[",
"'pixelSize'",
"]",
"=",
"self",
".",
"scale",
"[",
"jj",
":",
"jj",
"+",
"2",
"]",
"[",
":",
":",
"-",
"1",
"]",
"outputDict",
"[",
"'pixelOrigin'",
"]",
"=",
"self",
".",
"origin",
"[",
"jj",
":",
"jj",
"+",
"2",
"]",
"[",
":",
":",
"-",
"1",
"]",
"# Ensure the data is loaded into memory from the buffer",
"if",
"self",
".",
"_on_memory",
":",
"outputDict",
"[",
"'data'",
"]",
"=",
"np",
".",
"array",
"(",
"outputDict",
"[",
"'data'",
"]",
")",
"return",
"outputDict"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/io/dm.py#L1103-L1207 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/training/saver.py | python | Saver.__init__ | (self,
var_list=None,
reshape=False,
sharded=False,
max_to_keep=5,
keep_checkpoint_every_n_hours=10000.0,
name=None,
restore_sequentially=False,
saver_def=None,
builder=None) | Creates a `Saver`.
The constructor adds ops to save and restore variables.
`var_list` specifies the variables that will be saved and restored. It can
be passed as a `dict` or a list:
* A `dict` of names to variables: The keys are the names that will be
used to save or restore the variables in the checkpoint files.
* A list of variables: The variables will be keyed with their op name in
the checkpoint files.
For example:
```python
v1 = tf.Variable(..., name='v1')
v2 = tf.Variable(..., name='v2')
# Pass the variables as a dict:
saver = tf.train.Saver({'v1': v1, 'v2': v2})
# Or pass them as a list.
saver = tf.train.Saver([v1, v2])
# Passing a list is equivalent to passing a dict with the variable op names
# as keys:
saver = tf.train.Saver({v.op.name: v for v in [v1, v2]})
```
The optional `reshape` argument, if `True`, allows restoring a variable from
a save file where the variable had a different shape, but the same number
of elements and type. This is useful if you have reshaped a variable and
want to reload it from an older checkpoint.
The optional `sharded` argument, if `True`, instructs the saver to shard
checkpoints per device.
Args:
var_list: A list of `Variable` objects or a dictionary mapping names to
variables. If `None`, defaults to the list of all variables.
reshape: If `True`, allows restoring parameters from a checkpoint
where the variables have a different shape.
sharded: If `True`, shard the checkpoints, one per device.
max_to_keep: Maximum number of recent checkpoints to keep.
Defaults to 5.
keep_checkpoint_every_n_hours: How often to keep checkpoints.
Defaults to 10,000 hours.
name: String. Optional name to use as a prefix when adding operations.
restore_sequentially: A `Bool`, which if true, causes restore of different
variables to happen sequentially within each device. This can lower
memory usage when restoring very large models.
saver_def: Optional `SaverDef` proto to use instead of running the
builder. This is only useful for specialty code that wants to recreate
a `Saver` object for a previously built `Graph` that had a `Saver`.
The `saver_def` proto should be the one returned by the
`as_saver_def()` call of the `Saver` that was created for that `Graph`.
builder: Optional `SaverBuilder` to use if a `saver_def` was not provided.
Defaults to `BaseSaverBuilder()`.
Raises:
TypeError: If `var_list` is invalid.
ValueError: If any of the keys or values in `var_list` are not unique. | Creates a `Saver`. | [
"Creates",
"a",
"Saver",
"."
] | def __init__(self,
var_list=None,
reshape=False,
sharded=False,
max_to_keep=5,
keep_checkpoint_every_n_hours=10000.0,
name=None,
restore_sequentially=False,
saver_def=None,
builder=None):
"""Creates a `Saver`.
The constructor adds ops to save and restore variables.
`var_list` specifies the variables that will be saved and restored. It can
be passed as a `dict` or a list:
* A `dict` of names to variables: The keys are the names that will be
used to save or restore the variables in the checkpoint files.
* A list of variables: The variables will be keyed with their op name in
the checkpoint files.
For example:
```python
v1 = tf.Variable(..., name='v1')
v2 = tf.Variable(..., name='v2')
# Pass the variables as a dict:
saver = tf.train.Saver({'v1': v1, 'v2': v2})
# Or pass them as a list.
saver = tf.train.Saver([v1, v2])
# Passing a list is equivalent to passing a dict with the variable op names
# as keys:
saver = tf.train.Saver({v.op.name: v for v in [v1, v2]})
```
The optional `reshape` argument, if `True`, allows restoring a variable from
a save file where the variable had a different shape, but the same number
of elements and type. This is useful if you have reshaped a variable and
want to reload it from an older checkpoint.
The optional `sharded` argument, if `True`, instructs the saver to shard
checkpoints per device.
Args:
var_list: A list of `Variable` objects or a dictionary mapping names to
variables. If `None`, defaults to the list of all variables.
reshape: If `True`, allows restoring parameters from a checkpoint
where the variables have a different shape.
sharded: If `True`, shard the checkpoints, one per device.
max_to_keep: Maximum number of recent checkpoints to keep.
Defaults to 5.
keep_checkpoint_every_n_hours: How often to keep checkpoints.
Defaults to 10,000 hours.
name: String. Optional name to use as a prefix when adding operations.
restore_sequentially: A `Bool`, which if true, causes restore of different
variables to happen sequentially within each device. This can lower
memory usage when restoring very large models.
saver_def: Optional `SaverDef` proto to use instead of running the
builder. This is only useful for specialty code that wants to recreate
a `Saver` object for a previously built `Graph` that had a `Saver`.
The `saver_def` proto should be the one returned by the
`as_saver_def()` call of the `Saver` that was created for that `Graph`.
builder: Optional `SaverBuilder` to use if a `saver_def` was not provided.
Defaults to `BaseSaverBuilder()`.
Raises:
TypeError: If `var_list` is invalid.
ValueError: If any of the keys or values in `var_list` are not unique.
"""
if not saver_def:
if builder is None:
builder = BaseSaverBuilder()
if var_list is None:
var_list = variables.all_variables()
if not var_list:
raise ValueError("No variables to save")
saver_def = builder.build(
var_list,
reshape=reshape,
sharded=sharded,
max_to_keep=max_to_keep,
keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours,
name=name,
restore_sequentially=restore_sequentially)
if not isinstance(saver_def, saver_pb2.SaverDef):
raise ValueError("saver_def must if a saver_pb2.SaverDef: %s" % saver_def)
if not saver_def.save_tensor_name:
raise ValueError("saver_def must specify the save_tensor_name: %s"
% str(saver_def))
if not saver_def.restore_op_name:
raise ValueError("saver_def must specify the restore_op_name: %s"
% str(saver_def))
# Assigns saver_def.
self.saver_def = saver_def
# Updates next checkpoint time.
self._next_checkpoint_time = (
time.time() + self.saver_def.keep_checkpoint_every_n_hours * 3600)
self._last_checkpoints = [] | [
"def",
"__init__",
"(",
"self",
",",
"var_list",
"=",
"None",
",",
"reshape",
"=",
"False",
",",
"sharded",
"=",
"False",
",",
"max_to_keep",
"=",
"5",
",",
"keep_checkpoint_every_n_hours",
"=",
"10000.0",
",",
"name",
"=",
"None",
",",
"restore_sequentially",
"=",
"False",
",",
"saver_def",
"=",
"None",
",",
"builder",
"=",
"None",
")",
":",
"if",
"not",
"saver_def",
":",
"if",
"builder",
"is",
"None",
":",
"builder",
"=",
"BaseSaverBuilder",
"(",
")",
"if",
"var_list",
"is",
"None",
":",
"var_list",
"=",
"variables",
".",
"all_variables",
"(",
")",
"if",
"not",
"var_list",
":",
"raise",
"ValueError",
"(",
"\"No variables to save\"",
")",
"saver_def",
"=",
"builder",
".",
"build",
"(",
"var_list",
",",
"reshape",
"=",
"reshape",
",",
"sharded",
"=",
"sharded",
",",
"max_to_keep",
"=",
"max_to_keep",
",",
"keep_checkpoint_every_n_hours",
"=",
"keep_checkpoint_every_n_hours",
",",
"name",
"=",
"name",
",",
"restore_sequentially",
"=",
"restore_sequentially",
")",
"if",
"not",
"isinstance",
"(",
"saver_def",
",",
"saver_pb2",
".",
"SaverDef",
")",
":",
"raise",
"ValueError",
"(",
"\"saver_def must if a saver_pb2.SaverDef: %s\"",
"%",
"saver_def",
")",
"if",
"not",
"saver_def",
".",
"save_tensor_name",
":",
"raise",
"ValueError",
"(",
"\"saver_def must specify the save_tensor_name: %s\"",
"%",
"str",
"(",
"saver_def",
")",
")",
"if",
"not",
"saver_def",
".",
"restore_op_name",
":",
"raise",
"ValueError",
"(",
"\"saver_def must specify the restore_op_name: %s\"",
"%",
"str",
"(",
"saver_def",
")",
")",
"# Assigns saver_def.",
"self",
".",
"saver_def",
"=",
"saver_def",
"# Updates next checkpoint time.",
"self",
".",
"_next_checkpoint_time",
"=",
"(",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"saver_def",
".",
"keep_checkpoint_every_n_hours",
"*",
"3600",
")",
"self",
".",
"_last_checkpoints",
"=",
"[",
"]"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/saver.py#L775-L876 | ||
carla-simulator/carla | 8854804f4d7748e14d937ec763a2912823a7e5f5 | PythonAPI/examples/client_bounding_boxes.py | python | ClientSideBoundingBoxes.get_bounding_boxes | (vehicles, camera) | return bounding_boxes | Creates 3D bounding boxes based on carla vehicle list and camera. | Creates 3D bounding boxes based on carla vehicle list and camera. | [
"Creates",
"3D",
"bounding",
"boxes",
"based",
"on",
"carla",
"vehicle",
"list",
"and",
"camera",
"."
] | def get_bounding_boxes(vehicles, camera):
"""
Creates 3D bounding boxes based on carla vehicle list and camera.
"""
bounding_boxes = [ClientSideBoundingBoxes.get_bounding_box(vehicle, camera) for vehicle in vehicles]
# filter objects behind camera
bounding_boxes = [bb for bb in bounding_boxes if all(bb[:, 2] > 0)]
return bounding_boxes | [
"def",
"get_bounding_boxes",
"(",
"vehicles",
",",
"camera",
")",
":",
"bounding_boxes",
"=",
"[",
"ClientSideBoundingBoxes",
".",
"get_bounding_box",
"(",
"vehicle",
",",
"camera",
")",
"for",
"vehicle",
"in",
"vehicles",
"]",
"# filter objects behind camera",
"bounding_boxes",
"=",
"[",
"bb",
"for",
"bb",
"in",
"bounding_boxes",
"if",
"all",
"(",
"bb",
"[",
":",
",",
"2",
"]",
">",
"0",
")",
"]",
"return",
"bounding_boxes"
] | https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/examples/client_bounding_boxes.py#L82-L90 | |
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | tools/onnx-graphsurgeon/onnx_graphsurgeon/ir/graph.py | python | Graph.register | (opsets=None) | return register_func | Registers a function with the Graph class for the specified group of opsets.
After registering the function, it can be accessed like a normal member function.
For example:
::
@Graph.register()
def add(self, a, b):
return self.layer(op="Add", inputs=[a, b], outputs=["add_out_gs"])
graph.add(a, b)
Args:
opsets (Sequence[int]):
A group of opsets for which to register the function. Multiple functions with the same
name may be registered simultaneously if they are registered for different opsets.
Registering a function with a duplicate name for the same opsets will overwrite any
function previously registered for those opsets. By default, the function is
registered for all opsets. | Registers a function with the Graph class for the specified group of opsets.
After registering the function, it can be accessed like a normal member function. | [
"Registers",
"a",
"function",
"with",
"the",
"Graph",
"class",
"for",
"the",
"specified",
"group",
"of",
"opsets",
".",
"After",
"registering",
"the",
"function",
"it",
"can",
"be",
"accessed",
"like",
"a",
"normal",
"member",
"function",
"."
] | def register(opsets=None):
"""
Registers a function with the Graph class for the specified group of opsets.
After registering the function, it can be accessed like a normal member function.
For example:
::
@Graph.register()
def add(self, a, b):
return self.layer(op="Add", inputs=[a, b], outputs=["add_out_gs"])
graph.add(a, b)
Args:
opsets (Sequence[int]):
A group of opsets for which to register the function. Multiple functions with the same
name may be registered simultaneously if they are registered for different opsets.
Registering a function with a duplicate name for the same opsets will overwrite any
function previously registered for those opsets. By default, the function is
registered for all opsets.
"""
def register_func(func):
if hasattr(Graph, func.__name__):
G_LOGGER.warning(
"Registered function: {:} is hidden by a Graph attribute or function with the same name. "
"This function will never be called!".format(func.__name__)
)
# Default behavior is to register functions for all opsets.
if opsets is None:
Graph.GLOBAL_FUNC_MAP[func.__name__] = func
else:
for opset in opsets:
Graph.OPSET_FUNC_MAP[opset][func.__name__] = func
return func
return register_func | [
"def",
"register",
"(",
"opsets",
"=",
"None",
")",
":",
"def",
"register_func",
"(",
"func",
")",
":",
"if",
"hasattr",
"(",
"Graph",
",",
"func",
".",
"__name__",
")",
":",
"G_LOGGER",
".",
"warning",
"(",
"\"Registered function: {:} is hidden by a Graph attribute or function with the same name. \"",
"\"This function will never be called!\"",
".",
"format",
"(",
"func",
".",
"__name__",
")",
")",
"# Default behavior is to register functions for all opsets.",
"if",
"opsets",
"is",
"None",
":",
"Graph",
".",
"GLOBAL_FUNC_MAP",
"[",
"func",
".",
"__name__",
"]",
"=",
"func",
"else",
":",
"for",
"opset",
"in",
"opsets",
":",
"Graph",
".",
"OPSET_FUNC_MAP",
"[",
"opset",
"]",
"[",
"func",
".",
"__name__",
"]",
"=",
"func",
"return",
"func",
"return",
"register_func"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/onnx-graphsurgeon/onnx_graphsurgeon/ir/graph.py#L53-L91 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/util/url.py | python | Url.netloc | (self) | return self.host | Network location including host and port | Network location including host and port | [
"Network",
"location",
"including",
"host",
"and",
"port"
] | def netloc(self):
"""Network location including host and port"""
if self.port:
return "%s:%d" % (self.host, self.port)
return self.host | [
"def",
"netloc",
"(",
"self",
")",
":",
"if",
"self",
".",
"port",
":",
"return",
"\"%s:%d\"",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"return",
"self",
".",
"host"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/util/url.py#L125-L129 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/statisticalEstimator.py | python | StatisticalEstimator.value | (self) | Returns the current estimation. | Returns the current estimation. | [
"Returns",
"the",
"current",
"estimation",
"."
] | def value(self):
"""
Returns the current estimation.
""" | [
"def",
"value",
"(",
"self",
")",
":"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/statisticalEstimator.py#L31-L34 | ||
facebookresearch/ELF | 1f790173095cd910976d9f651b80beb872ec5d12 | rlpytorch/runner/parameter_server.py | python | ParameterServer.__init__ | (self, n_processes) | Initialization.
Args:
n_processes: number of processes. | Initialization. | [
"Initialization",
"."
] | def __init__(self, n_processes):
''' Initialization.
Args:
n_processes: number of processes.
'''
self.queue = mp.Queue()
self.n_processes = n_processes
self.barrier = mp.Barrier(n_processes)
# For update signal.
self.send_done = Cond()
self.recv_done = Cond() | [
"def",
"__init__",
"(",
"self",
",",
"n_processes",
")",
":",
"self",
".",
"queue",
"=",
"mp",
".",
"Queue",
"(",
")",
"self",
".",
"n_processes",
"=",
"n_processes",
"self",
".",
"barrier",
"=",
"mp",
".",
"Barrier",
"(",
"n_processes",
")",
"# For update signal.",
"self",
".",
"send_done",
"=",
"Cond",
"(",
")",
"self",
".",
"recv_done",
"=",
"Cond",
"(",
")"
] | https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/rlpytorch/runner/parameter_server.py#L53-L64 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/distutils/command/config.py | python | config.check_header | (self, header, include_dirs=None, library_dirs=None,
lang="c") | return self.try_cpp(body="/* No body */", headers=[header],
include_dirs=include_dirs) | Determine if the system header file named by 'header_file'
exists and can be found by the preprocessor; return true if so,
false otherwise. | Determine if the system header file named by 'header_file'
exists and can be found by the preprocessor; return true if so,
false otherwise. | [
"Determine",
"if",
"the",
"system",
"header",
"file",
"named",
"by",
"header_file",
"exists",
"and",
"can",
"be",
"found",
"by",
"the",
"preprocessor",
";",
"return",
"true",
"if",
"so",
"false",
"otherwise",
"."
] | def check_header(self, header, include_dirs=None, library_dirs=None,
lang="c"):
"""Determine if the system header file named by 'header_file'
exists and can be found by the preprocessor; return true if so,
false otherwise.
"""
return self.try_cpp(body="/* No body */", headers=[header],
include_dirs=include_dirs) | [
"def",
"check_header",
"(",
"self",
",",
"header",
",",
"include_dirs",
"=",
"None",
",",
"library_dirs",
"=",
"None",
",",
"lang",
"=",
"\"c\"",
")",
":",
"return",
"self",
".",
"try_cpp",
"(",
"body",
"=",
"\"/* No body */\"",
",",
"headers",
"=",
"[",
"header",
"]",
",",
"include_dirs",
"=",
"include_dirs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/command/config.py#L334-L341 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/BASIC/basparse.py | python | p_plist | (p) | plist : plist COMMA pitem
| pitem | plist : plist COMMA pitem
| pitem | [
"plist",
":",
"plist",
"COMMA",
"pitem",
"|",
"pitem"
] | def p_plist(p):
'''plist : plist COMMA pitem
| pitem'''
if len(p) > 3:
p[0] = p[1]
p[0].append(p[3])
else:
p[0] = [p[1]] | [
"def",
"p_plist",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
">",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"p",
"[",
"0",
"]",
".",
"append",
"(",
"p",
"[",
"3",
"]",
")",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/BASIC/basparse.py#L373-L380 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/aggregate.py | python | DISTINCT | (src_column) | return ("__builtin__distinct__", [src_column]) | Builtin distinct values for groupby. Returns a list of distinct values.
>>> sf.groupby("user",
... {'rating_distinct':tc.aggregate.DISTINCT('rating')}) | Builtin distinct values for groupby. Returns a list of distinct values. | [
"Builtin",
"distinct",
"values",
"for",
"groupby",
".",
"Returns",
"a",
"list",
"of",
"distinct",
"values",
"."
] | def DISTINCT(src_column):
"""
Builtin distinct values for groupby. Returns a list of distinct values.
>>> sf.groupby("user",
... {'rating_distinct':tc.aggregate.DISTINCT('rating')})
"""
return ("__builtin__distinct__", [src_column]) | [
"def",
"DISTINCT",
"(",
"src_column",
")",
":",
"return",
"(",
"\"__builtin__distinct__\"",
",",
"[",
"src_column",
"]",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/aggregate.py#L270-L277 | |
apache/parquet-cpp | 642da055adf009652689b20e68a198cffb857651 | build-support/cpplint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=[]) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
if file_extension == 'h':
CheckForHeaderGuard(filename, clean_lines, error)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
FlagCxx11Features(filename, clean_lines, line, error)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# Check that the .cc file has included its header if it exists.
if file_extension == 'cc':
CheckHeaderFileIncluded(filename, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// marker so line numbers end in a known way'",
"]",
")",
"include_state",
"=",
"_IncludeState",
"(",
")",
"function_state",
"=",
"_FunctionState",
"(",
")",
"nesting_state",
"=",
"NestingState",
"(",
")",
"ResetNolintSuppressions",
"(",
")",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"clean_lines",
"=",
"CleansedLines",
"(",
"lines",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"CheckForHeaderGuard",
"(",
"filename",
",",
"clean_lines",
",",
"error",
")",
"for",
"line",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
")",
"FlagCxx11Features",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"nesting_state",
".",
"CheckCompletedBlocks",
"(",
"filename",
",",
"error",
")",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
")",
"# Check that the .cc file has included its header if it exists.",
"if",
"file_extension",
"==",
"'cc'",
":",
"CheckHeaderFileIncluded",
"(",
"filename",
",",
"include_state",
",",
"error",
")",
"# We check here rather than inside ProcessLine so that we see raw",
"# lines rather than \"cleaned\" lines.",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")"
] | https://github.com/apache/parquet-cpp/blob/642da055adf009652689b20e68a198cffb857651/build-support/cpplint.py#L5997-L6046 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/__init__.py | python | curve_in_figure | (fig) | return False | Return True if there is an ErrobarContainer or Line2D in fig | Return True if there is an ErrobarContainer or Line2D in fig | [
"Return",
"True",
"if",
"there",
"is",
"an",
"ErrobarContainer",
"or",
"Line2D",
"in",
"fig"
] | def curve_in_figure(fig):
"""Return True if there is an ErrobarContainer or Line2D in fig"""
for ax in fig.get_axes():
if line_in_ax(ax) or errorbars_in_ax(ax):
return True
return False | [
"def",
"curve_in_figure",
"(",
"fig",
")",
":",
"for",
"ax",
"in",
"fig",
".",
"get_axes",
"(",
")",
":",
"if",
"line_in_ax",
"(",
"ax",
")",
"or",
"errorbars_in_ax",
"(",
"ax",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/__init__.py#L51-L56 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/data_structures/sframe.py | python | SFrame.export_json | (self, filename, orient="records") | Writes an SFrame to a JSON file.
Parameters
----------
filename : string
The location to save the JSON file.
orient : string, optional. Either "records" or "lines"
If orient="records" the file is saved as a single JSON array.
If orient="lines", the file is saves as a JSON value per line.
Examples
--------
The orient parameter describes the expected input format of the JSON
file.
If orient="records", the output will be a single JSON Array where
each array element is a dictionary describing the row.
>>> g
Columns:
a int
b int
Rows: 3
Data:
+---+---+
| a | b |
+---+---+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
+---+---+
>>> g.export('output.json', orient='records')
>>> !cat output.json
[
{'a':1,'b':1},
{'a':2,'b':2},
{'a':3,'b':3},
]
If orient="rows", each row will be emitted as a JSON dictionary to
each file line.
>>> g
Columns:
a int
b int
Rows: 3
Data:
+---+---+
| a | b |
+---+---+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
+---+---+
>>> g.export('output.json', orient='rows')
>>> !cat output.json
{'a':1,'b':1}
{'a':2,'b':2}
{'a':3,'b':3} | Writes an SFrame to a JSON file. | [
"Writes",
"an",
"SFrame",
"to",
"a",
"JSON",
"file",
"."
] | def export_json(self, filename, orient="records"):
"""
Writes an SFrame to a JSON file.
Parameters
----------
filename : string
The location to save the JSON file.
orient : string, optional. Either "records" or "lines"
If orient="records" the file is saved as a single JSON array.
If orient="lines", the file is saves as a JSON value per line.
Examples
--------
The orient parameter describes the expected input format of the JSON
file.
If orient="records", the output will be a single JSON Array where
each array element is a dictionary describing the row.
>>> g
Columns:
a int
b int
Rows: 3
Data:
+---+---+
| a | b |
+---+---+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
+---+---+
>>> g.export('output.json', orient='records')
>>> !cat output.json
[
{'a':1,'b':1},
{'a':2,'b':2},
{'a':3,'b':3},
]
If orient="rows", each row will be emitted as a JSON dictionary to
each file line.
>>> g
Columns:
a int
b int
Rows: 3
Data:
+---+---+
| a | b |
+---+---+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
+---+---+
>>> g.export('output.json', orient='rows')
>>> !cat output.json
{'a':1,'b':1}
{'a':2,'b':2}
{'a':3,'b':3}
"""
if orient == "records":
self.pack_columns(dtype=dict).export_csv(
filename,
file_header="[",
file_footer="]",
header=False,
double_quote=False,
quote_level=csv.QUOTE_NONE,
line_prefix=",",
_no_prefix_on_first_value=True,
)
elif orient == "lines":
self.pack_columns(dtype=dict).export_csv(
filename, header=False, double_quote=False, quote_level=csv.QUOTE_NONE
)
else:
raise ValueError("Invalid value for orient parameter (" + str(orient) + ")") | [
"def",
"export_json",
"(",
"self",
",",
"filename",
",",
"orient",
"=",
"\"records\"",
")",
":",
"if",
"orient",
"==",
"\"records\"",
":",
"self",
".",
"pack_columns",
"(",
"dtype",
"=",
"dict",
")",
".",
"export_csv",
"(",
"filename",
",",
"file_header",
"=",
"\"[\"",
",",
"file_footer",
"=",
"\"]\"",
",",
"header",
"=",
"False",
",",
"double_quote",
"=",
"False",
",",
"quote_level",
"=",
"csv",
".",
"QUOTE_NONE",
",",
"line_prefix",
"=",
"\",\"",
",",
"_no_prefix_on_first_value",
"=",
"True",
",",
")",
"elif",
"orient",
"==",
"\"lines\"",
":",
"self",
".",
"pack_columns",
"(",
"dtype",
"=",
"dict",
")",
".",
"export_csv",
"(",
"filename",
",",
"header",
"=",
"False",
",",
"double_quote",
"=",
"False",
",",
"quote_level",
"=",
"csv",
".",
"QUOTE_NONE",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for orient parameter (\"",
"+",
"str",
"(",
"orient",
")",
"+",
"\")\"",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sframe.py#L3173-L3253 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | XView.xview | (self, *args) | Query and change the horizontal position of the view. | Query and change the horizontal position of the view. | [
"Query",
"and",
"change",
"the",
"horizontal",
"position",
"of",
"the",
"view",
"."
] | def xview(self, *args):
"""Query and change the horizontal position of the view."""
res = self.tk.call(self._w, 'xview', *args)
if not args:
return self._getdoubles(res) | [
"def",
"xview",
"(",
"self",
",",
"*",
"args",
")",
":",
"res",
"=",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'xview'",
",",
"*",
"args",
")",
"if",
"not",
"args",
":",
"return",
"self",
".",
"_getdoubles",
"(",
"res",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L1558-L1562 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/prettytable.py | python | PrettyTable._get_end | (self) | return self._end | End index of the range of rows to print
Arguments:
end - index of last data row to include in output PLUS ONE (list slice style) | End index of the range of rows to print | [
"End",
"index",
"of",
"the",
"range",
"of",
"rows",
"to",
"print"
] | def _get_end(self):
"""End index of the range of rows to print
Arguments:
end - index of last data row to include in output PLUS ONE (list slice style)"""
return self._end | [
"def",
"_get_end",
"(",
"self",
")",
":",
"return",
"self",
".",
"_end"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/prettytable.py#L485-L491 | |
plumonito/dtslam | 5994bb9cf7a11981b830370db206bceb654c085d | 3rdparty/opencv-git/3rdparty/jinja2/lexer.py | python | count_newlines | (value) | return len(newline_re.findall(value)) | Count the number of newline characters in the string. This is
useful for extensions that filter a stream. | Count the number of newline characters in the string. This is
useful for extensions that filter a stream. | [
"Count",
"the",
"number",
"of",
"newline",
"characters",
"in",
"the",
"string",
".",
"This",
"is",
"useful",
"for",
"extensions",
"that",
"filter",
"a",
"stream",
"."
] | def count_newlines(value):
"""Count the number of newline characters in the string. This is
useful for extensions that filter a stream.
"""
return len(newline_re.findall(value)) | [
"def",
"count_newlines",
"(",
"value",
")",
":",
"return",
"len",
"(",
"newline_re",
".",
"findall",
"(",
"value",
")",
")"
] | https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/lexer.py#L182-L186 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py | python | JIRA.delete_issue_link | (self, id) | return self._session.delete(url) | Delete a link between two issues.
:param id: ID of the issue link to delete | Delete a link between two issues. | [
"Delete",
"a",
"link",
"between",
"two",
"issues",
"."
] | def delete_issue_link(self, id):
"""Delete a link between two issues.
:param id: ID of the issue link to delete
"""
url = self._get_url('issueLink') + "/" + id
return self._session.delete(url) | [
"def",
"delete_issue_link",
"(",
"self",
",",
"id",
")",
":",
"url",
"=",
"self",
".",
"_get_url",
"(",
"'issueLink'",
")",
"+",
"\"/\"",
"+",
"id",
"return",
"self",
".",
"_session",
".",
"delete",
"(",
"url",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py#L1735-L1741 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/bsr.py | python | bsr_matrix.sum_duplicates | (self) | Eliminate duplicate matrix entries by adding them together
The is an *in place* operation | Eliminate duplicate matrix entries by adding them together | [
"Eliminate",
"duplicate",
"matrix",
"entries",
"by",
"adding",
"them",
"together"
] | def sum_duplicates(self):
"""Eliminate duplicate matrix entries by adding them together
The is an *in place* operation
"""
if self.has_canonical_format:
return
self.sort_indices()
R, C = self.blocksize
M, N = self.shape
# port of _sparsetools.csr_sum_duplicates
n_row = M // R
nnz = 0
row_end = 0
for i in range(n_row):
jj = row_end
row_end = self.indptr[i+1]
while jj < row_end:
j = self.indices[jj]
x = self.data[jj]
jj += 1
while jj < row_end and self.indices[jj] == j:
x += self.data[jj]
jj += 1
self.indices[nnz] = j
self.data[nnz] = x
nnz += 1
self.indptr[i+1] = nnz
self.prune() # nnz may have changed
self.has_canonical_format = True | [
"def",
"sum_duplicates",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_canonical_format",
":",
"return",
"self",
".",
"sort_indices",
"(",
")",
"R",
",",
"C",
"=",
"self",
".",
"blocksize",
"M",
",",
"N",
"=",
"self",
".",
"shape",
"# port of _sparsetools.csr_sum_duplicates",
"n_row",
"=",
"M",
"//",
"R",
"nnz",
"=",
"0",
"row_end",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"n_row",
")",
":",
"jj",
"=",
"row_end",
"row_end",
"=",
"self",
".",
"indptr",
"[",
"i",
"+",
"1",
"]",
"while",
"jj",
"<",
"row_end",
":",
"j",
"=",
"self",
".",
"indices",
"[",
"jj",
"]",
"x",
"=",
"self",
".",
"data",
"[",
"jj",
"]",
"jj",
"+=",
"1",
"while",
"jj",
"<",
"row_end",
"and",
"self",
".",
"indices",
"[",
"jj",
"]",
"==",
"j",
":",
"x",
"+=",
"self",
".",
"data",
"[",
"jj",
"]",
"jj",
"+=",
"1",
"self",
".",
"indices",
"[",
"nnz",
"]",
"=",
"j",
"self",
".",
"data",
"[",
"nnz",
"]",
"=",
"x",
"nnz",
"+=",
"1",
"self",
".",
"indptr",
"[",
"i",
"+",
"1",
"]",
"=",
"nnz",
"self",
".",
"prune",
"(",
")",
"# nnz may have changed",
"self",
".",
"has_canonical_format",
"=",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/bsr.py#L562-L593 | ||
microsoft/LightGBM | 904b2d5158703c4900b68008617951dd2f9ff21b | python-package/lightgbm/engine.py | python | CVBooster.__init__ | (self) | Initialize the CVBooster.
Generally, no need to instantiate manually. | Initialize the CVBooster. | [
"Initialize",
"the",
"CVBooster",
"."
] | def __init__(self):
"""Initialize the CVBooster.
Generally, no need to instantiate manually.
"""
self.boosters = []
self.best_iteration = -1 | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"boosters",
"=",
"[",
"]",
"self",
".",
"best_iteration",
"=",
"-",
"1"
] | https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/engine.py#L281-L287 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/command.py | python | Command.RunCommand | (self) | Abstract function in base class. Subclasses must implement this.
The return value of this function will be used as the exit status of the
process, so subclass commands should return an integer exit code (0 for
success, a value in [1,255] for failure). | Abstract function in base class. Subclasses must implement this. | [
"Abstract",
"function",
"in",
"base",
"class",
".",
"Subclasses",
"must",
"implement",
"this",
"."
] | def RunCommand(self):
"""Abstract function in base class. Subclasses must implement this.
The return value of this function will be used as the exit status of the
process, so subclass commands should return an integer exit code (0 for
success, a value in [1,255] for failure).
"""
raise CommandException('Command %s is missing its RunCommand() '
'implementation' % self.command_name) | [
"def",
"RunCommand",
"(",
"self",
")",
":",
"raise",
"CommandException",
"(",
"'Command %s is missing its RunCommand() '",
"'implementation'",
"%",
"self",
".",
"command_name",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/command.py#L578-L586 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/command/build_ext.py | python | build_ext.check_extensions_list | (self, extensions) | Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here.
Raise DistutilsSetupError if the structure is invalid anywhere;
just returns otherwise. | Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here. | [
"Ensure",
"that",
"the",
"list",
"of",
"extensions",
"(",
"presumably",
"provided",
"as",
"a",
"command",
"option",
"extensions",
")",
"is",
"valid",
"i",
".",
"e",
".",
"it",
"is",
"a",
"list",
"of",
"Extension",
"objects",
".",
"We",
"also",
"support",
"the",
"old",
"-",
"style",
"list",
"of",
"2",
"-",
"tuples",
"where",
"the",
"tuples",
"are",
"(",
"ext_name",
"build_info",
")",
"which",
"are",
"converted",
"to",
"Extension",
"instances",
"here",
"."
] | def check_extensions_list(self, extensions):
"""Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here.
Raise DistutilsSetupError if the structure is invalid anywhere;
just returns otherwise.
"""
if not isinstance(extensions, list):
raise DistutilsSetupError, \
"'ext_modules' option must be a list of Extension instances"
for i, ext in enumerate(extensions):
if isinstance(ext, Extension):
continue # OK! (assume type-checking done
# by Extension constructor)
if not isinstance(ext, tuple) or len(ext) != 2:
raise DistutilsSetupError, \
("each element of 'ext_modules' option must be an "
"Extension instance or 2-tuple")
ext_name, build_info = ext
log.warn(("old-style (ext_name, build_info) tuple found in "
"ext_modules for extension '%s'"
"-- please convert to Extension instance" % ext_name))
if not (isinstance(ext_name, str) and
extension_name_re.match(ext_name)):
raise DistutilsSetupError, \
("first element of each tuple in 'ext_modules' "
"must be the extension name (a string)")
if not isinstance(build_info, dict):
raise DistutilsSetupError, \
("second element of each tuple in 'ext_modules' "
"must be a dictionary (build info)")
# OK, the (ext_name, build_info) dict is type-safe: convert it
# to an Extension instance.
ext = Extension(ext_name, build_info['sources'])
# Easy stuff: one-to-one mapping from dict elements to
# instance attributes.
for key in ('include_dirs', 'library_dirs', 'libraries',
'extra_objects', 'extra_compile_args',
'extra_link_args'):
val = build_info.get(key)
if val is not None:
setattr(ext, key, val)
# Medium-easy stuff: same syntax/semantics, different names.
ext.runtime_library_dirs = build_info.get('rpath')
if 'def_file' in build_info:
log.warn("'def_file' element of build info dict "
"no longer supported")
# Non-trivial stuff: 'macros' split into 'define_macros'
# and 'undef_macros'.
macros = build_info.get('macros')
if macros:
ext.define_macros = []
ext.undef_macros = []
for macro in macros:
if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
raise DistutilsSetupError, \
("'macros' element of build info dict "
"must be 1- or 2-tuple")
if len(macro) == 1:
ext.undef_macros.append(macro[0])
elif len(macro) == 2:
ext.define_macros.append(macro)
extensions[i] = ext | [
"def",
"check_extensions_list",
"(",
"self",
",",
"extensions",
")",
":",
"if",
"not",
"isinstance",
"(",
"extensions",
",",
"list",
")",
":",
"raise",
"DistutilsSetupError",
",",
"\"'ext_modules' option must be a list of Extension instances\"",
"for",
"i",
",",
"ext",
"in",
"enumerate",
"(",
"extensions",
")",
":",
"if",
"isinstance",
"(",
"ext",
",",
"Extension",
")",
":",
"continue",
"# OK! (assume type-checking done",
"# by Extension constructor)",
"if",
"not",
"isinstance",
"(",
"ext",
",",
"tuple",
")",
"or",
"len",
"(",
"ext",
")",
"!=",
"2",
":",
"raise",
"DistutilsSetupError",
",",
"(",
"\"each element of 'ext_modules' option must be an \"",
"\"Extension instance or 2-tuple\"",
")",
"ext_name",
",",
"build_info",
"=",
"ext",
"log",
".",
"warn",
"(",
"(",
"\"old-style (ext_name, build_info) tuple found in \"",
"\"ext_modules for extension '%s'\"",
"\"-- please convert to Extension instance\"",
"%",
"ext_name",
")",
")",
"if",
"not",
"(",
"isinstance",
"(",
"ext_name",
",",
"str",
")",
"and",
"extension_name_re",
".",
"match",
"(",
"ext_name",
")",
")",
":",
"raise",
"DistutilsSetupError",
",",
"(",
"\"first element of each tuple in 'ext_modules' \"",
"\"must be the extension name (a string)\"",
")",
"if",
"not",
"isinstance",
"(",
"build_info",
",",
"dict",
")",
":",
"raise",
"DistutilsSetupError",
",",
"(",
"\"second element of each tuple in 'ext_modules' \"",
"\"must be a dictionary (build info)\"",
")",
"# OK, the (ext_name, build_info) dict is type-safe: convert it",
"# to an Extension instance.",
"ext",
"=",
"Extension",
"(",
"ext_name",
",",
"build_info",
"[",
"'sources'",
"]",
")",
"# Easy stuff: one-to-one mapping from dict elements to",
"# instance attributes.",
"for",
"key",
"in",
"(",
"'include_dirs'",
",",
"'library_dirs'",
",",
"'libraries'",
",",
"'extra_objects'",
",",
"'extra_compile_args'",
",",
"'extra_link_args'",
")",
":",
"val",
"=",
"build_info",
".",
"get",
"(",
"key",
")",
"if",
"val",
"is",
"not",
"None",
":",
"setattr",
"(",
"ext",
",",
"key",
",",
"val",
")",
"# Medium-easy stuff: same syntax/semantics, different names.",
"ext",
".",
"runtime_library_dirs",
"=",
"build_info",
".",
"get",
"(",
"'rpath'",
")",
"if",
"'def_file'",
"in",
"build_info",
":",
"log",
".",
"warn",
"(",
"\"'def_file' element of build info dict \"",
"\"no longer supported\"",
")",
"# Non-trivial stuff: 'macros' split into 'define_macros'",
"# and 'undef_macros'.",
"macros",
"=",
"build_info",
".",
"get",
"(",
"'macros'",
")",
"if",
"macros",
":",
"ext",
".",
"define_macros",
"=",
"[",
"]",
"ext",
".",
"undef_macros",
"=",
"[",
"]",
"for",
"macro",
"in",
"macros",
":",
"if",
"not",
"(",
"isinstance",
"(",
"macro",
",",
"tuple",
")",
"and",
"len",
"(",
"macro",
")",
"in",
"(",
"1",
",",
"2",
")",
")",
":",
"raise",
"DistutilsSetupError",
",",
"(",
"\"'macros' element of build info dict \"",
"\"must be 1- or 2-tuple\"",
")",
"if",
"len",
"(",
"macro",
")",
"==",
"1",
":",
"ext",
".",
"undef_macros",
".",
"append",
"(",
"macro",
"[",
"0",
"]",
")",
"elif",
"len",
"(",
"macro",
")",
"==",
"2",
":",
"ext",
".",
"define_macros",
".",
"append",
"(",
"macro",
")",
"extensions",
"[",
"i",
"]",
"=",
"ext"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/command/build_ext.py#L344-L420 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/nn/layer/transformer.py | python | MultiHeadAttention.gen_cache | (self, key, value=None, type=Cache) | Generates cache for `forward` usage in inference accroding to arguments.
The generated cache is an instance of `MultiHeadAttention.Cache` or an
instance of `MultiHeadAttention.StaticCache`.
`Cache` or `StaticCache` is namedtuple with `k` and `v` as fields,
and it stores tensors shaped `[batch_size, num_heads, length, embed_dim]`
which are results of linear projection, reshape and transpose calculations
in MultiHeadAttention.
If the generated cache is an instance of `Cache`, `k` and `v` fields
reserve intermediate result tensors of previous positions, and the tensors
are incremental among decoding steps, which mostly are used for decoder
decoder self attention.
If the generated cache is an instance of `StaticCache`, `k` and `v` fields
would be used as calculated result tensors on keys an values in `forward`,
and the tensors keep unchanged among decoding steps, which are mostly used
for decoder-encoder cross attention.
The cache is generated as follows:
1. If `type` is `StaticCache`, apply `compute_kv(key, value)` and use the
results to create an instance of `StaticCache`.
2. If `type` is `Cache` and `value` is None, generate empty tensors shaped
`[batch_size, num_heads, 0, embed_dim // num_heads]` and use the results
to create an instance of `Cache`, where `batch_size` is from the first
dimension of `key`.
3. If `type` is `Cache` and `value` is not None, use `key`, `value` to create
an instance of `Cache`.
Parameters:
key (Tensor): The keys for multi-head attention. It is
a tensor with shape `[batch_size, key_length, kdim]`. The
data type should be float32 or float64. If `value` is None,
it is only for batch size and data type reference.
value (Tensor, optional): The values for multi-head attention. It
is a tensor with shape `[batch_size, value_length, vdim]`.
The data type should be float32 or float64. If None, `key` is only
for batch size reference. Default None.
type (type): It should be `MultiHeadAttention.StaticCache` or
`MultiHeadAttention.Cache` to indicate the cache type to generate.
Returns:
namedtuple: an instance of `Cache` or `StaticCache` accordingly. | Generates cache for `forward` usage in inference accroding to arguments.
The generated cache is an instance of `MultiHeadAttention.Cache` or an
instance of `MultiHeadAttention.StaticCache`. | [
"Generates",
"cache",
"for",
"forward",
"usage",
"in",
"inference",
"accroding",
"to",
"arguments",
".",
"The",
"generated",
"cache",
"is",
"an",
"instance",
"of",
"MultiHeadAttention",
".",
"Cache",
"or",
"an",
"instance",
"of",
"MultiHeadAttention",
".",
"StaticCache",
"."
] | def gen_cache(self, key, value=None, type=Cache):
"""
Generates cache for `forward` usage in inference accroding to arguments.
The generated cache is an instance of `MultiHeadAttention.Cache` or an
instance of `MultiHeadAttention.StaticCache`.
`Cache` or `StaticCache` is namedtuple with `k` and `v` as fields,
and it stores tensors shaped `[batch_size, num_heads, length, embed_dim]`
which are results of linear projection, reshape and transpose calculations
in MultiHeadAttention.
If the generated cache is an instance of `Cache`, `k` and `v` fields
reserve intermediate result tensors of previous positions, and the tensors
are incremental among decoding steps, which mostly are used for decoder
decoder self attention.
If the generated cache is an instance of `StaticCache`, `k` and `v` fields
would be used as calculated result tensors on keys an values in `forward`,
and the tensors keep unchanged among decoding steps, which are mostly used
for decoder-encoder cross attention.
The cache is generated as follows:
1. If `type` is `StaticCache`, apply `compute_kv(key, value)` and use the
results to create an instance of `StaticCache`.
2. If `type` is `Cache` and `value` is None, generate empty tensors shaped
`[batch_size, num_heads, 0, embed_dim // num_heads]` and use the results
to create an instance of `Cache`, where `batch_size` is from the first
dimension of `key`.
3. If `type` is `Cache` and `value` is not None, use `key`, `value` to create
an instance of `Cache`.
Parameters:
key (Tensor): The keys for multi-head attention. It is
a tensor with shape `[batch_size, key_length, kdim]`. The
data type should be float32 or float64. If `value` is None,
it is only for batch size and data type reference.
value (Tensor, optional): The values for multi-head attention. It
is a tensor with shape `[batch_size, value_length, vdim]`.
The data type should be float32 or float64. If None, `key` is only
for batch size reference. Default None.
type (type): It should be `MultiHeadAttention.StaticCache` or
`MultiHeadAttention.Cache` to indicate the cache type to generate.
Returns:
namedtuple: an instance of `Cache` or `StaticCache` accordingly.
"""
if type == MultiHeadAttention.StaticCache: # static_kv
k, v = self.compute_kv(key, value)
return self.StaticCache(k, v)
elif value is None: # incremental_state
k = layers.fill_constant_batch_size_like(
input=key,
shape=[-1, self.num_heads, 0, self.head_dim],
dtype=key.dtype,
value=0)
v = layers.fill_constant_batch_size_like(
input=key,
shape=[-1, self.num_heads, 0, self.head_dim],
dtype=key.dtype,
value=0)
return self.Cache(k, v)
else:
# incremental_state with initial value, mainly for usage like UniLM
return self.Cache(key, value) | [
"def",
"gen_cache",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
",",
"type",
"=",
"Cache",
")",
":",
"if",
"type",
"==",
"MultiHeadAttention",
".",
"StaticCache",
":",
"# static_kv",
"k",
",",
"v",
"=",
"self",
".",
"compute_kv",
"(",
"key",
",",
"value",
")",
"return",
"self",
".",
"StaticCache",
"(",
"k",
",",
"v",
")",
"elif",
"value",
"is",
"None",
":",
"# incremental_state",
"k",
"=",
"layers",
".",
"fill_constant_batch_size_like",
"(",
"input",
"=",
"key",
",",
"shape",
"=",
"[",
"-",
"1",
",",
"self",
".",
"num_heads",
",",
"0",
",",
"self",
".",
"head_dim",
"]",
",",
"dtype",
"=",
"key",
".",
"dtype",
",",
"value",
"=",
"0",
")",
"v",
"=",
"layers",
".",
"fill_constant_batch_size_like",
"(",
"input",
"=",
"key",
",",
"shape",
"=",
"[",
"-",
"1",
",",
"self",
".",
"num_heads",
",",
"0",
",",
"self",
".",
"head_dim",
"]",
",",
"dtype",
"=",
"key",
".",
"dtype",
",",
"value",
"=",
"0",
")",
"return",
"self",
".",
"Cache",
"(",
"k",
",",
"v",
")",
"else",
":",
"# incremental_state with initial value, mainly for usage like UniLM",
"return",
"self",
".",
"Cache",
"(",
"key",
",",
"value",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/layer/transformer.py#L276-L342 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.