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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/rnn_cell_impl.py | python | _RNNCellWrapperV1._call_wrapped_cell | (self, inputs, state, cell_call_fn, **kwargs) | Calls the wrapped cell and performs the wrapping logic.
This method is called from the wrapper's `call` or `__call__` methods.
Args:
inputs: A tensor with wrapped cell's input.
state: A tensor or tuple of tensors with wrapped cell's state.
cell_call_fn: Wrapped cell's method to use for step computation (cell's
`__call__` or 'call' method).
**kwargs: Additional arguments.
Returns:
A pair containing:
- Output: A tensor with cell's output.
- New state: A tensor or tuple of tensors with new wrapped cell's state. | Calls the wrapped cell and performs the wrapping logic. | [
"Calls",
"the",
"wrapped",
"cell",
"and",
"performs",
"the",
"wrapping",
"logic",
"."
] | def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs):
"""Calls the wrapped cell and performs the wrapping logic.
This method is called from the wrapper's `call` or `__call__` methods.
Args:
inputs: A tensor with wrapped cell's input.
state: A tensor or tuple of tensors with wrapped cell's state.
cell_call_fn: Wrapped cell's method to use for step computation (cell's
`__call__` or 'call' method).
**kwargs: Additional arguments.
Returns:
A pair containing:
- Output: A tensor with cell's output.
- New state: A tensor or tuple of tensors with new wrapped cell's state.
"""
raise NotImplementedError | [
"def",
"_call_wrapped_cell",
"(",
"self",
",",
"inputs",
",",
"state",
",",
"cell_call_fn",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/rnn_cell_impl.py#L1098-L1115 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/sysconfig.py | python | _init_posix | (vars) | Initialize the module as appropriate for POSIX systems. | Initialize the module as appropriate for POSIX systems. | [
"Initialize",
"the",
"module",
"as",
"appropriate",
"for",
"POSIX",
"systems",
"."
] | def _init_posix(vars):
"""Initialize the module as appropriate for POSIX systems."""
# load the installed Makefile:
makefile = get_makefile_filename()
try:
_parse_makefile(makefile, vars)
except IOError as e:
msg = "invalid Python installation: unable to open %s" % makefile
if hasattr(e, "strerror"):
msg = msg + " (%s)" % e.strerror
raise IOError(msg)
# load the installed pyconfig.h:
config_h = get_config_h_filename()
try:
with open(config_h) as f:
parse_config_h(f, vars)
except IOError as e:
msg = "invalid Python installation: unable to open %s" % config_h
if hasattr(e, "strerror"):
msg = msg + " (%s)" % e.strerror
raise IOError(msg)
# On AIX, there are wrong paths to the linker scripts in the Makefile
# -- these paths are relative to the Python source, but when installed
# the scripts are in another directory.
if _PYTHON_BUILD:
vars['LDSHARED'] = vars['BLDSHARED'] | [
"def",
"_init_posix",
"(",
"vars",
")",
":",
"# load the installed Makefile:",
"makefile",
"=",
"get_makefile_filename",
"(",
")",
"try",
":",
"_parse_makefile",
"(",
"makefile",
",",
"vars",
")",
"except",
"IOError",
"as",
"e",
":",
"msg",
"=",
"\"invalid Python installation: unable to open %s\"",
"%",
"makefile",
"if",
"hasattr",
"(",
"e",
",",
"\"strerror\"",
")",
":",
"msg",
"=",
"msg",
"+",
"\" (%s)\"",
"%",
"e",
".",
"strerror",
"raise",
"IOError",
"(",
"msg",
")",
"# load the installed pyconfig.h:",
"config_h",
"=",
"get_config_h_filename",
"(",
")",
"try",
":",
"with",
"open",
"(",
"config_h",
")",
"as",
"f",
":",
"parse_config_h",
"(",
"f",
",",
"vars",
")",
"except",
"IOError",
"as",
"e",
":",
"msg",
"=",
"\"invalid Python installation: unable to open %s\"",
"%",
"config_h",
"if",
"hasattr",
"(",
"e",
",",
"\"strerror\"",
")",
":",
"msg",
"=",
"msg",
"+",
"\" (%s)\"",
"%",
"e",
".",
"strerror",
"raise",
"IOError",
"(",
"msg",
")",
"# On AIX, there are wrong paths to the linker scripts in the Makefile",
"# -- these paths are relative to the Python source, but when installed",
"# the scripts are in another directory.",
"if",
"_PYTHON_BUILD",
":",
"vars",
"[",
"'LDSHARED'",
"]",
"=",
"vars",
"[",
"'BLDSHARED'",
"]"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/sysconfig.py#L344-L369 | ||
google/mediapipe | e6c19885c6d3c6f410c730952aeed2852790d306 | mediapipe/examples/desktop/media_sequence/charades_dataset.py | python | Charades.as_dataset | (self, split, shuffle=False, repeat=False,
serialized_prefetch_size=32, decoded_prefetch_size=32) | return dataset | Returns Charades as a tf.data.Dataset.
After running this function, calling padded_batch() on the Dataset object
will produce batches of data, but additional preprocessing may be desired.
If using padded_batch, the indicator_matrix output distinguishes valid
from padded frames.
Args:
split: either "train" or "test"
shuffle: if true, shuffles both files and examples.
repeat: if true, repeats the data set forever.
serialized_prefetch_size: the buffer size for reading from disk.
decoded_prefetch_size: the buffer size after decoding.
Returns:
A tf.data.Dataset object with the following structure: {
"images": uint8 tensor, shape [time, height, width, channels]
"segment_matrix": binary tensor of segments, shape [time, num_segments].
See one_hot_segments() for details.
"indicator_matrix": binary tensor indicating valid frames,
shape [time, 1]. If padded with zeros to align sizes, the indicator
marks where segments is valid.
"classification_target": binary tensor of classification targets,
shape [time, 158 classes]. More than one value in a row can be 1.0 if
segments overlap.
"example_id": a unique string id for each example, shape [].
"sampling_rate": the frame rate for each sequence, shape [].
"gt_segment_seconds": the start and end time of each segment,
shape [num_segments, 2].
"gt_segment_classes": the class labels for each segment,
shape [num_segments].
"num_segments": the number of segments in the example, shape [].
"num_timesteps": the number of timesteps in the example, shape []. | Returns Charades as a tf.data.Dataset. | [
"Returns",
"Charades",
"as",
"a",
"tf",
".",
"data",
".",
"Dataset",
"."
] | def as_dataset(self, split, shuffle=False, repeat=False,
serialized_prefetch_size=32, decoded_prefetch_size=32):
"""Returns Charades as a tf.data.Dataset.
After running this function, calling padded_batch() on the Dataset object
will produce batches of data, but additional preprocessing may be desired.
If using padded_batch, the indicator_matrix output distinguishes valid
from padded frames.
Args:
split: either "train" or "test"
shuffle: if true, shuffles both files and examples.
repeat: if true, repeats the data set forever.
serialized_prefetch_size: the buffer size for reading from disk.
decoded_prefetch_size: the buffer size after decoding.
Returns:
A tf.data.Dataset object with the following structure: {
"images": uint8 tensor, shape [time, height, width, channels]
"segment_matrix": binary tensor of segments, shape [time, num_segments].
See one_hot_segments() for details.
"indicator_matrix": binary tensor indicating valid frames,
shape [time, 1]. If padded with zeros to align sizes, the indicator
marks where segments is valid.
"classification_target": binary tensor of classification targets,
shape [time, 158 classes]. More than one value in a row can be 1.0 if
segments overlap.
"example_id": a unique string id for each example, shape [].
"sampling_rate": the frame rate for each sequence, shape [].
"gt_segment_seconds": the start and end time of each segment,
shape [num_segments, 2].
"gt_segment_classes": the class labels for each segment,
shape [num_segments].
"num_segments": the number of segments in the example, shape [].
"num_timesteps": the number of timesteps in the example, shape [].
"""
def parse_fn(sequence_example):
"""Parses a Charades example."""
context_features = {
ms.get_example_id_key(): ms.get_example_id_default_parser(),
ms.get_segment_start_index_key(): (
ms.get_segment_start_index_default_parser()),
ms.get_segment_end_index_key(): (
ms.get_segment_end_index_default_parser()),
ms.get_segment_label_index_key(): (
ms.get_segment_label_index_default_parser()),
ms.get_segment_label_string_key(): (
ms.get_segment_label_string_default_parser()),
ms.get_segment_start_timestamp_key(): (
ms.get_segment_start_timestamp_default_parser()),
ms.get_segment_end_timestamp_key(): (
ms.get_segment_end_timestamp_default_parser()),
ms.get_image_frame_rate_key(): (
ms.get_image_frame_rate_default_parser()),
}
sequence_features = {
ms.get_image_encoded_key(): ms.get_image_encoded_default_parser()
}
parsed_context, parsed_sequence = tf.io.parse_single_sequence_example(
sequence_example, context_features, sequence_features)
sequence_length = tf.shape(parsed_sequence[ms.get_image_encoded_key()])[0]
num_segments = tf.shape(
parsed_context[ms.get_segment_label_index_key()])[0]
# segments matrix and targets for training.
segments_matrix, indicator = one_hot_segments(
tf.sparse_tensor_to_dense(
parsed_context[ms.get_segment_start_index_key()]),
tf.sparse_tensor_to_dense(
parsed_context[ms.get_segment_end_index_key()]),
sequence_length)
classification_target = timepoint_classification_target(
segments_matrix,
tf.sparse_tensor_to_dense(
parsed_context[ms.get_segment_label_index_key()]
) + CLASS_LABEL_OFFSET,
NUM_CLASSES + CLASS_LABEL_OFFSET)
# [segments, 2] start and end time in seconds.
gt_segment_seconds = tf.to_float(tf.concat(
[tf.expand_dims(tf.sparse_tensor_to_dense(parsed_context[
ms.get_segment_start_timestamp_key()]), 1),
tf.expand_dims(tf.sparse_tensor_to_dense(parsed_context[
ms.get_segment_end_timestamp_key()]), 1)],
1)) / float(SECONDS_TO_MICROSECONDS)
gt_segment_classes = tf.sparse_tensor_to_dense(parsed_context[
ms.get_segment_label_index_key()]) + CLASS_LABEL_OFFSET
example_id = parsed_context[ms.get_example_id_key()]
sampling_rate = parsed_context[ms.get_image_frame_rate_key()]
images = tf.map_fn(tf.image.decode_jpeg,
parsed_sequence[ms.get_image_encoded_key()],
back_prop=False,
dtype=tf.uint8)
output_dict = {
"segment_matrix": segments_matrix,
"indicator_matrix": indicator,
"classification_target": classification_target,
"example_id": example_id,
"sampling_rate": sampling_rate,
"gt_segment_seconds": gt_segment_seconds,
"gt_segment_classes": gt_segment_classes,
"num_segments": num_segments,
"num_timesteps": sequence_length,
"images": images,
}
return output_dict
if split not in SPLITS:
raise ValueError("Split %s not in %s" % split, str(list(SPLITS.keys())))
all_shards = tf.io.gfile.glob(
os.path.join(self.path_to_data, SPLITS[split][0] + "-*-of-*"))
random.shuffle(all_shards)
all_shards_dataset = tf.data.Dataset.from_tensor_slices(all_shards)
cycle_length = min(16, len(all_shards))
dataset = all_shards_dataset.apply(
tf.contrib.data.parallel_interleave(
tf.data.TFRecordDataset,
cycle_length=cycle_length,
block_length=1, sloppy=True,
buffer_output_elements=serialized_prefetch_size))
dataset = dataset.prefetch(serialized_prefetch_size)
if shuffle:
dataset = dataset.shuffle(serialized_prefetch_size)
if repeat:
dataset = dataset.repeat()
dataset = dataset.map(parse_fn)
dataset = dataset.prefetch(decoded_prefetch_size)
return dataset | [
"def",
"as_dataset",
"(",
"self",
",",
"split",
",",
"shuffle",
"=",
"False",
",",
"repeat",
"=",
"False",
",",
"serialized_prefetch_size",
"=",
"32",
",",
"decoded_prefetch_size",
"=",
"32",
")",
":",
"def",
"parse_fn",
"(",
"sequence_example",
")",
":",
"\"\"\"Parses a Charades example.\"\"\"",
"context_features",
"=",
"{",
"ms",
".",
"get_example_id_key",
"(",
")",
":",
"ms",
".",
"get_example_id_default_parser",
"(",
")",
",",
"ms",
".",
"get_segment_start_index_key",
"(",
")",
":",
"(",
"ms",
".",
"get_segment_start_index_default_parser",
"(",
")",
")",
",",
"ms",
".",
"get_segment_end_index_key",
"(",
")",
":",
"(",
"ms",
".",
"get_segment_end_index_default_parser",
"(",
")",
")",
",",
"ms",
".",
"get_segment_label_index_key",
"(",
")",
":",
"(",
"ms",
".",
"get_segment_label_index_default_parser",
"(",
")",
")",
",",
"ms",
".",
"get_segment_label_string_key",
"(",
")",
":",
"(",
"ms",
".",
"get_segment_label_string_default_parser",
"(",
")",
")",
",",
"ms",
".",
"get_segment_start_timestamp_key",
"(",
")",
":",
"(",
"ms",
".",
"get_segment_start_timestamp_default_parser",
"(",
")",
")",
",",
"ms",
".",
"get_segment_end_timestamp_key",
"(",
")",
":",
"(",
"ms",
".",
"get_segment_end_timestamp_default_parser",
"(",
")",
")",
",",
"ms",
".",
"get_image_frame_rate_key",
"(",
")",
":",
"(",
"ms",
".",
"get_image_frame_rate_default_parser",
"(",
")",
")",
",",
"}",
"sequence_features",
"=",
"{",
"ms",
".",
"get_image_encoded_key",
"(",
")",
":",
"ms",
".",
"get_image_encoded_default_parser",
"(",
")",
"}",
"parsed_context",
",",
"parsed_sequence",
"=",
"tf",
".",
"io",
".",
"parse_single_sequence_example",
"(",
"sequence_example",
",",
"context_features",
",",
"sequence_features",
")",
"sequence_length",
"=",
"tf",
".",
"shape",
"(",
"parsed_sequence",
"[",
"ms",
".",
"get_image_encoded_key",
"(",
")",
"]",
")",
"[",
"0",
"]",
"num_segments",
"=",
"tf",
".",
"shape",
"(",
"parsed_context",
"[",
"ms",
".",
"get_segment_label_index_key",
"(",
")",
"]",
")",
"[",
"0",
"]",
"# segments matrix and targets for training.",
"segments_matrix",
",",
"indicator",
"=",
"one_hot_segments",
"(",
"tf",
".",
"sparse_tensor_to_dense",
"(",
"parsed_context",
"[",
"ms",
".",
"get_segment_start_index_key",
"(",
")",
"]",
")",
",",
"tf",
".",
"sparse_tensor_to_dense",
"(",
"parsed_context",
"[",
"ms",
".",
"get_segment_end_index_key",
"(",
")",
"]",
")",
",",
"sequence_length",
")",
"classification_target",
"=",
"timepoint_classification_target",
"(",
"segments_matrix",
",",
"tf",
".",
"sparse_tensor_to_dense",
"(",
"parsed_context",
"[",
"ms",
".",
"get_segment_label_index_key",
"(",
")",
"]",
")",
"+",
"CLASS_LABEL_OFFSET",
",",
"NUM_CLASSES",
"+",
"CLASS_LABEL_OFFSET",
")",
"# [segments, 2] start and end time in seconds.",
"gt_segment_seconds",
"=",
"tf",
".",
"to_float",
"(",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"sparse_tensor_to_dense",
"(",
"parsed_context",
"[",
"ms",
".",
"get_segment_start_timestamp_key",
"(",
")",
"]",
")",
",",
"1",
")",
",",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"sparse_tensor_to_dense",
"(",
"parsed_context",
"[",
"ms",
".",
"get_segment_end_timestamp_key",
"(",
")",
"]",
")",
",",
"1",
")",
"]",
",",
"1",
")",
")",
"/",
"float",
"(",
"SECONDS_TO_MICROSECONDS",
")",
"gt_segment_classes",
"=",
"tf",
".",
"sparse_tensor_to_dense",
"(",
"parsed_context",
"[",
"ms",
".",
"get_segment_label_index_key",
"(",
")",
"]",
")",
"+",
"CLASS_LABEL_OFFSET",
"example_id",
"=",
"parsed_context",
"[",
"ms",
".",
"get_example_id_key",
"(",
")",
"]",
"sampling_rate",
"=",
"parsed_context",
"[",
"ms",
".",
"get_image_frame_rate_key",
"(",
")",
"]",
"images",
"=",
"tf",
".",
"map_fn",
"(",
"tf",
".",
"image",
".",
"decode_jpeg",
",",
"parsed_sequence",
"[",
"ms",
".",
"get_image_encoded_key",
"(",
")",
"]",
",",
"back_prop",
"=",
"False",
",",
"dtype",
"=",
"tf",
".",
"uint8",
")",
"output_dict",
"=",
"{",
"\"segment_matrix\"",
":",
"segments_matrix",
",",
"\"indicator_matrix\"",
":",
"indicator",
",",
"\"classification_target\"",
":",
"classification_target",
",",
"\"example_id\"",
":",
"example_id",
",",
"\"sampling_rate\"",
":",
"sampling_rate",
",",
"\"gt_segment_seconds\"",
":",
"gt_segment_seconds",
",",
"\"gt_segment_classes\"",
":",
"gt_segment_classes",
",",
"\"num_segments\"",
":",
"num_segments",
",",
"\"num_timesteps\"",
":",
"sequence_length",
",",
"\"images\"",
":",
"images",
",",
"}",
"return",
"output_dict",
"if",
"split",
"not",
"in",
"SPLITS",
":",
"raise",
"ValueError",
"(",
"\"Split %s not in %s\"",
"%",
"split",
",",
"str",
"(",
"list",
"(",
"SPLITS",
".",
"keys",
"(",
")",
")",
")",
")",
"all_shards",
"=",
"tf",
".",
"io",
".",
"gfile",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path_to_data",
",",
"SPLITS",
"[",
"split",
"]",
"[",
"0",
"]",
"+",
"\"-*-of-*\"",
")",
")",
"random",
".",
"shuffle",
"(",
"all_shards",
")",
"all_shards_dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_tensor_slices",
"(",
"all_shards",
")",
"cycle_length",
"=",
"min",
"(",
"16",
",",
"len",
"(",
"all_shards",
")",
")",
"dataset",
"=",
"all_shards_dataset",
".",
"apply",
"(",
"tf",
".",
"contrib",
".",
"data",
".",
"parallel_interleave",
"(",
"tf",
".",
"data",
".",
"TFRecordDataset",
",",
"cycle_length",
"=",
"cycle_length",
",",
"block_length",
"=",
"1",
",",
"sloppy",
"=",
"True",
",",
"buffer_output_elements",
"=",
"serialized_prefetch_size",
")",
")",
"dataset",
"=",
"dataset",
".",
"prefetch",
"(",
"serialized_prefetch_size",
")",
"if",
"shuffle",
":",
"dataset",
"=",
"dataset",
".",
"shuffle",
"(",
"serialized_prefetch_size",
")",
"if",
"repeat",
":",
"dataset",
"=",
"dataset",
".",
"repeat",
"(",
")",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"parse_fn",
")",
"dataset",
"=",
"dataset",
".",
"prefetch",
"(",
"decoded_prefetch_size",
")",
"return",
"dataset"
] | https://github.com/google/mediapipe/blob/e6c19885c6d3c6f410c730952aeed2852790d306/mediapipe/examples/desktop/media_sequence/charades_dataset.py#L113-L243 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | SizerItemList.__getitem__ | (*args, **kwargs) | return _core_.SizerItemList___getitem__(*args, **kwargs) | __getitem__(self, size_t index) -> SizerItem | __getitem__(self, size_t index) -> SizerItem | [
"__getitem__",
"(",
"self",
"size_t",
"index",
")",
"-",
">",
"SizerItem"
] | def __getitem__(*args, **kwargs):
"""__getitem__(self, size_t index) -> SizerItem"""
return _core_.SizerItemList___getitem__(*args, **kwargs) | [
"def",
"__getitem__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerItemList___getitem__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13991-L13993 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/indexes/multi.py | python | MultiIndex.equals | (self, other: object) | return True | Determines if two MultiIndex objects have the same labeling information
(the levels themselves do not necessarily have to be the same)
See Also
--------
equal_levels | Determines if two MultiIndex objects have the same labeling information
(the levels themselves do not necessarily have to be the same) | [
"Determines",
"if",
"two",
"MultiIndex",
"objects",
"have",
"the",
"same",
"labeling",
"information",
"(",
"the",
"levels",
"themselves",
"do",
"not",
"necessarily",
"have",
"to",
"be",
"the",
"same",
")"
] | def equals(self, other: object) -> bool:
"""
Determines if two MultiIndex objects have the same labeling information
(the levels themselves do not necessarily have to be the same)
See Also
--------
equal_levels
"""
if self.is_(other):
return True
if not isinstance(other, Index):
return False
if len(self) != len(other):
return False
if not isinstance(other, MultiIndex):
# d-level MultiIndex can equal d-tuple Index
if not self._should_compare(other):
# object Index or Categorical[object] may contain tuples
return False
return array_equivalent(self._values, other._values)
if self.nlevels != other.nlevels:
return False
for i in range(self.nlevels):
self_codes = self.codes[i]
other_codes = other.codes[i]
self_mask = self_codes == -1
other_mask = other_codes == -1
if not np.array_equal(self_mask, other_mask):
return False
self_codes = self_codes[~self_mask]
self_values = self.levels[i]._values.take(self_codes)
other_codes = other_codes[~other_mask]
other_values = other.levels[i]._values.take(other_codes)
# since we use NaT both datetime64 and timedelta64 we can have a
# situation where a level is typed say timedelta64 in self (IOW it
# has other values than NaT) but types datetime64 in other (where
# its all NaT) but these are equivalent
if len(self_values) == 0 and len(other_values) == 0:
continue
if not isinstance(self_values, np.ndarray):
# i.e. ExtensionArray
if not self_values.equals(other_values):
return False
else:
if not array_equivalent(self_values, other_values):
return False
return True | [
"def",
"equals",
"(",
"self",
",",
"other",
":",
"object",
")",
"->",
"bool",
":",
"if",
"self",
".",
"is_",
"(",
"other",
")",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Index",
")",
":",
"return",
"False",
"if",
"len",
"(",
"self",
")",
"!=",
"len",
"(",
"other",
")",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"other",
",",
"MultiIndex",
")",
":",
"# d-level MultiIndex can equal d-tuple Index",
"if",
"not",
"self",
".",
"_should_compare",
"(",
"other",
")",
":",
"# object Index or Categorical[object] may contain tuples",
"return",
"False",
"return",
"array_equivalent",
"(",
"self",
".",
"_values",
",",
"other",
".",
"_values",
")",
"if",
"self",
".",
"nlevels",
"!=",
"other",
".",
"nlevels",
":",
"return",
"False",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"nlevels",
")",
":",
"self_codes",
"=",
"self",
".",
"codes",
"[",
"i",
"]",
"other_codes",
"=",
"other",
".",
"codes",
"[",
"i",
"]",
"self_mask",
"=",
"self_codes",
"==",
"-",
"1",
"other_mask",
"=",
"other_codes",
"==",
"-",
"1",
"if",
"not",
"np",
".",
"array_equal",
"(",
"self_mask",
",",
"other_mask",
")",
":",
"return",
"False",
"self_codes",
"=",
"self_codes",
"[",
"~",
"self_mask",
"]",
"self_values",
"=",
"self",
".",
"levels",
"[",
"i",
"]",
".",
"_values",
".",
"take",
"(",
"self_codes",
")",
"other_codes",
"=",
"other_codes",
"[",
"~",
"other_mask",
"]",
"other_values",
"=",
"other",
".",
"levels",
"[",
"i",
"]",
".",
"_values",
".",
"take",
"(",
"other_codes",
")",
"# since we use NaT both datetime64 and timedelta64 we can have a",
"# situation where a level is typed say timedelta64 in self (IOW it",
"# has other values than NaT) but types datetime64 in other (where",
"# its all NaT) but these are equivalent",
"if",
"len",
"(",
"self_values",
")",
"==",
"0",
"and",
"len",
"(",
"other_values",
")",
"==",
"0",
":",
"continue",
"if",
"not",
"isinstance",
"(",
"self_values",
",",
"np",
".",
"ndarray",
")",
":",
"# i.e. ExtensionArray",
"if",
"not",
"self_values",
".",
"equals",
"(",
"other_values",
")",
":",
"return",
"False",
"else",
":",
"if",
"not",
"array_equivalent",
"(",
"self_values",
",",
"other_values",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/multi.py#L3472-L3528 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/array_grad.py | python | _CheckNumericsV2Grad | (op, grad) | return array_ops.check_numerics_v2(
grad,
"Not a number (NaN) or infinity (Inf) values detected in gradient. %s" %
op.get_attr("message")) | Gradient for check_numerics op. | Gradient for check_numerics op. | [
"Gradient",
"for",
"check_numerics",
"op",
"."
] | def _CheckNumericsV2Grad(op, grad):
"""Gradient for check_numerics op."""
return array_ops.check_numerics_v2(
grad,
"Not a number (NaN) or infinity (Inf) values detected in gradient. %s" %
op.get_attr("message")) | [
"def",
"_CheckNumericsV2Grad",
"(",
"op",
",",
"grad",
")",
":",
"return",
"array_ops",
".",
"check_numerics_v2",
"(",
"grad",
",",
"\"Not a number (NaN) or infinity (Inf) values detected in gradient. %s\"",
"%",
"op",
".",
"get_attr",
"(",
"\"message\"",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_grad.py#L755-L760 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/layers/nn.py | python | gaussian_random_batch_size_like | (input,
shape,
input_dim_idx=0,
output_dim_idx=0,
mean=0.0,
std=1.0,
seed=0,
dtype='float32') | return out | ${comment}
Args:
input (Variable): ${input_comment}
shape (tuple|list): ${shape_comment}
input_dim_idx (int): ${input_dim_idx_comment}
output_dim_idx (int): ${output_dim_idx_comment}
mean (float): ${mean_comment}
std (float): ${std_comment}
seed (int): ${seed_comment}
dtype(np.dtype|core.VarDesc.VarType|str): The type of output data, float32 or float_64.
Returns:
out (Variable): ${out_comment}
Examples:
.. code-block:: python
import paddle
import paddle.fluid as fluid
paddle.enable_static()
input = fluid.data(name="input", shape=[13, 11], dtype='float32')
out = fluid.layers.gaussian_random_batch_size_like(
input, shape=[-1, 11], mean=1.0, std=2.0) | ${comment} | [
"$",
"{",
"comment",
"}"
] | def gaussian_random_batch_size_like(input,
shape,
input_dim_idx=0,
output_dim_idx=0,
mean=0.0,
std=1.0,
seed=0,
dtype='float32'):
"""
${comment}
Args:
input (Variable): ${input_comment}
shape (tuple|list): ${shape_comment}
input_dim_idx (int): ${input_dim_idx_comment}
output_dim_idx (int): ${output_dim_idx_comment}
mean (float): ${mean_comment}
std (float): ${std_comment}
seed (int): ${seed_comment}
dtype(np.dtype|core.VarDesc.VarType|str): The type of output data, float32 or float_64.
Returns:
out (Variable): ${out_comment}
Examples:
.. code-block:: python
import paddle
import paddle.fluid as fluid
paddle.enable_static()
input = fluid.data(name="input", shape=[13, 11], dtype='float32')
out = fluid.layers.gaussian_random_batch_size_like(
input, shape=[-1, 11], mean=1.0, std=2.0)
"""
helper = LayerHelper('gaussian_random_batch_size_like', **locals())
check_type(input, 'input', (Variable),
'fluid.layers.gaussian_random_batch_size_like')
check_type(shape, 'shape', (list, tuple),
'fluid.layers.gaussian_random_batch_size_like')
check_dtype(dtype, 'dtype', ['float16', 'float32', 'int'],
'fluid.layers.gaussian_random_batch_size_like')
out = helper.create_variable_for_type_inference(dtype)
c_dtype = convert_np_dtype_to_dtype_(dtype)
helper.append_op(
type='gaussian_random_batch_size_like',
inputs={'Input': input},
outputs={'Out': out},
attrs={
'shape': shape,
'input_dim_idx': input_dim_idx,
'output_dim_idx': output_dim_idx,
'mean': mean,
'std': std,
'seed': seed,
'dtype': c_dtype
})
return out | [
"def",
"gaussian_random_batch_size_like",
"(",
"input",
",",
"shape",
",",
"input_dim_idx",
"=",
"0",
",",
"output_dim_idx",
"=",
"0",
",",
"mean",
"=",
"0.0",
",",
"std",
"=",
"1.0",
",",
"seed",
"=",
"0",
",",
"dtype",
"=",
"'float32'",
")",
":",
"helper",
"=",
"LayerHelper",
"(",
"'gaussian_random_batch_size_like'",
",",
"*",
"*",
"locals",
"(",
")",
")",
"check_type",
"(",
"input",
",",
"'input'",
",",
"(",
"Variable",
")",
",",
"'fluid.layers.gaussian_random_batch_size_like'",
")",
"check_type",
"(",
"shape",
",",
"'shape'",
",",
"(",
"list",
",",
"tuple",
")",
",",
"'fluid.layers.gaussian_random_batch_size_like'",
")",
"check_dtype",
"(",
"dtype",
",",
"'dtype'",
",",
"[",
"'float16'",
",",
"'float32'",
",",
"'int'",
"]",
",",
"'fluid.layers.gaussian_random_batch_size_like'",
")",
"out",
"=",
"helper",
".",
"create_variable_for_type_inference",
"(",
"dtype",
")",
"c_dtype",
"=",
"convert_np_dtype_to_dtype_",
"(",
"dtype",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"'gaussian_random_batch_size_like'",
",",
"inputs",
"=",
"{",
"'Input'",
":",
"input",
"}",
",",
"outputs",
"=",
"{",
"'Out'",
":",
"out",
"}",
",",
"attrs",
"=",
"{",
"'shape'",
":",
"shape",
",",
"'input_dim_idx'",
":",
"input_dim_idx",
",",
"'output_dim_idx'",
":",
"output_dim_idx",
",",
"'mean'",
":",
"mean",
",",
"'std'",
":",
"std",
",",
"'seed'",
":",
"seed",
",",
"'dtype'",
":",
"c_dtype",
"}",
")",
"return",
"out"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/nn.py#L10903-L10963 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/jinja2/parser.py | python | Parser.parse_set | (self) | return nodes.AssignBlock(target, filter_node, body, lineno=lineno) | Parse an assign statement. | Parse an assign statement. | [
"Parse",
"an",
"assign",
"statement",
"."
] | def parse_set(self):
"""Parse an assign statement."""
lineno = next(self.stream).lineno
target = self.parse_assign_target(with_namespace=True)
if self.stream.skip_if('assign'):
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno)
filter_node = self.parse_filter(None)
body = self.parse_statements(('name:endset',),
drop_needle=True)
return nodes.AssignBlock(target, filter_node, body, lineno=lineno) | [
"def",
"parse_set",
"(",
"self",
")",
":",
"lineno",
"=",
"next",
"(",
"self",
".",
"stream",
")",
".",
"lineno",
"target",
"=",
"self",
".",
"parse_assign_target",
"(",
"with_namespace",
"=",
"True",
")",
"if",
"self",
".",
"stream",
".",
"skip_if",
"(",
"'assign'",
")",
":",
"expr",
"=",
"self",
".",
"parse_tuple",
"(",
")",
"return",
"nodes",
".",
"Assign",
"(",
"target",
",",
"expr",
",",
"lineno",
"=",
"lineno",
")",
"filter_node",
"=",
"self",
".",
"parse_filter",
"(",
"None",
")",
"body",
"=",
"self",
".",
"parse_statements",
"(",
"(",
"'name:endset'",
",",
")",
",",
"drop_needle",
"=",
"True",
")",
"return",
"nodes",
".",
"AssignBlock",
"(",
"target",
",",
"filter_node",
",",
"body",
",",
"lineno",
"=",
"lineno",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/parser.py#L176-L186 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py | python | ProcessConfigOverrides | (filename) | return True | Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further. | Loads the configuration files and processes the config overrides. | [
"Loads",
"the",
"configuration",
"files",
"and",
"processes",
"the",
"config",
"overrides",
"."
] | def ProcessConfigOverrides(filename):
""" Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further.
"""
abs_filename = os.path.abspath(filename)
cfg_filters = []
keep_looking = True
while keep_looking:
abs_path, base_name = os.path.split(abs_filename)
if not base_name:
break # Reached the root directory.
cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
abs_filename = abs_path
if not os.path.isfile(cfg_file):
continue
try:
with open(cfg_file) as file_handle:
for line in file_handle:
line, _, _ = line.partition('#') # Remove comments.
if not line.strip():
continue
name, _, val = line.partition('=')
name = name.strip()
val = val.strip()
if name == 'set noparent':
keep_looking = False
elif name == 'filter':
cfg_filters.append(val)
elif name == 'exclude_files':
# When matching exclude_files pattern, use the base_name of
# the current file name or the directory name we are processing.
# For example, if we are checking for lint errors in /foo/bar/baz.cc
# and we found the .cfg file at /foo/CPPLINT.cfg, then the config
# file's "exclude_files" filter is meant to be checked against "bar"
# and not "baz" nor "bar/baz.cc".
if base_name:
pattern = re.compile(val)
if pattern.match(base_name):
if _cpplint_state.quiet:
# Suppress "Ignoring file" warning when using --quiet.
return False
_cpplint_state.PrintInfo('Ignoring "%s": file excluded by "%s". '
'File path component "%s" matches '
'pattern "%s"\n' %
(filename, cfg_file, base_name, val))
return False
elif name == 'linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
_cpplint_state.PrintError('Line length must be numeric.')
elif name == 'extensions':
global _valid_extensions
try:
extensions = [ext.strip() for ext in val.split(',')]
_valid_extensions = set(extensions)
except ValueError:
sys.stderr.write('Extensions should be a comma-separated list of values;'
'for example: extensions=hpp,cpp\n'
'This could not be parsed: "%s"' % (val,))
elif name == 'root':
global _root
# root directories are specified relative to CPPLINT.cfg dir.
_root = os.path.join(os.path.dirname(cfg_file), val)
elif name == 'headers':
ProcessHppHeadersOption(val)
else:
_cpplint_state.PrintError(
'Invalid configuration option (%s) in file %s\n' %
(name, cfg_file))
except IOError:
_cpplint_state.PrintError(
"Skipping config file '%s': Can't open for reading\n" % cfg_file)
keep_looking = False
# Apply all the accumulated filters in reverse order (top-level directory
# config options having the least priority).
for cfg_filter in reversed(cfg_filters):
_AddFilters(cfg_filter)
return True | [
"def",
"ProcessConfigOverrides",
"(",
"filename",
")",
":",
"abs_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"cfg_filters",
"=",
"[",
"]",
"keep_looking",
"=",
"True",
"while",
"keep_looking",
":",
"abs_path",
",",
"base_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"abs_filename",
")",
"if",
"not",
"base_name",
":",
"break",
"# Reached the root directory.",
"cfg_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"abs_path",
",",
"\"CPPLINT.cfg\"",
")",
"abs_filename",
"=",
"abs_path",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"cfg_file",
")",
":",
"continue",
"try",
":",
"with",
"open",
"(",
"cfg_file",
")",
"as",
"file_handle",
":",
"for",
"line",
"in",
"file_handle",
":",
"line",
",",
"_",
",",
"_",
"=",
"line",
".",
"partition",
"(",
"'#'",
")",
"# Remove comments.",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"continue",
"name",
",",
"_",
",",
"val",
"=",
"line",
".",
"partition",
"(",
"'='",
")",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"val",
"=",
"val",
".",
"strip",
"(",
")",
"if",
"name",
"==",
"'set noparent'",
":",
"keep_looking",
"=",
"False",
"elif",
"name",
"==",
"'filter'",
":",
"cfg_filters",
".",
"append",
"(",
"val",
")",
"elif",
"name",
"==",
"'exclude_files'",
":",
"# When matching exclude_files pattern, use the base_name of",
"# the current file name or the directory name we are processing.",
"# For example, if we are checking for lint errors in /foo/bar/baz.cc",
"# and we found the .cfg file at /foo/CPPLINT.cfg, then the config",
"# file's \"exclude_files\" filter is meant to be checked against \"bar\"",
"# and not \"baz\" nor \"bar/baz.cc\".",
"if",
"base_name",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"val",
")",
"if",
"pattern",
".",
"match",
"(",
"base_name",
")",
":",
"if",
"_cpplint_state",
".",
"quiet",
":",
"# Suppress \"Ignoring file\" warning when using --quiet.",
"return",
"False",
"_cpplint_state",
".",
"PrintInfo",
"(",
"'Ignoring \"%s\": file excluded by \"%s\". '",
"'File path component \"%s\" matches '",
"'pattern \"%s\"\\n'",
"%",
"(",
"filename",
",",
"cfg_file",
",",
"base_name",
",",
"val",
")",
")",
"return",
"False",
"elif",
"name",
"==",
"'linelength'",
":",
"global",
"_line_length",
"try",
":",
"_line_length",
"=",
"int",
"(",
"val",
")",
"except",
"ValueError",
":",
"_cpplint_state",
".",
"PrintError",
"(",
"'Line length must be numeric.'",
")",
"elif",
"name",
"==",
"'extensions'",
":",
"global",
"_valid_extensions",
"try",
":",
"extensions",
"=",
"[",
"ext",
".",
"strip",
"(",
")",
"for",
"ext",
"in",
"val",
".",
"split",
"(",
"','",
")",
"]",
"_valid_extensions",
"=",
"set",
"(",
"extensions",
")",
"except",
"ValueError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Extensions should be a comma-separated list of values;'",
"'for example: extensions=hpp,cpp\\n'",
"'This could not be parsed: \"%s\"'",
"%",
"(",
"val",
",",
")",
")",
"elif",
"name",
"==",
"'root'",
":",
"global",
"_root",
"# root directories are specified relative to CPPLINT.cfg dir.",
"_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"cfg_file",
")",
",",
"val",
")",
"elif",
"name",
"==",
"'headers'",
":",
"ProcessHppHeadersOption",
"(",
"val",
")",
"else",
":",
"_cpplint_state",
".",
"PrintError",
"(",
"'Invalid configuration option (%s) in file %s\\n'",
"%",
"(",
"name",
",",
"cfg_file",
")",
")",
"except",
"IOError",
":",
"_cpplint_state",
".",
"PrintError",
"(",
"\"Skipping config file '%s': Can't open for reading\\n\"",
"%",
"cfg_file",
")",
"keep_looking",
"=",
"False",
"# Apply all the accumulated filters in reverse order (top-level directory",
"# config options having the least priority).",
"for",
"cfg_filter",
"in",
"reversed",
"(",
"cfg_filters",
")",
":",
"_AddFilters",
"(",
"cfg_filter",
")",
"return",
"True"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py#L6200-L6291 | |
cvmfs/cvmfs | 4637bdb5153178eadf885c1acf37bdc5c685bf8a | cpplint.py | python | IsInitializerList | (clean_lines, linenum) | return False | Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise. | Check if current line is inside constructor initializer list. | [
"Check",
"if",
"current",
"line",
"is",
"inside",
"constructor",
"initializer",
"list",
"."
] | def IsInitializerList(clean_lines, linenum):
"""Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise.
"""
for i in xrange(linenum, 1, -1):
line = clean_lines.elided[i]
if i == linenum:
remove_function_body = Match(r'^(.*)\{\s*$', line)
if remove_function_body:
line = remove_function_body.group(1)
if Search(r'\s:\s*\w+[({]', line):
# A lone colon tend to indicate the start of a constructor
# initializer list. It could also be a ternary operator, which
# also tend to appear in constructor initializer lists as
# opposed to parameter lists.
return True
if Search(r'\}\s*,\s*$', line):
# A closing brace followed by a comma is probably the end of a
# brace-initialized member in constructor initializer list.
return True
if Search(r'[{};]\s*$', line):
# Found one of the following:
# - A closing brace or semicolon, probably the end of the previous
# function.
# - An opening brace, probably the start of current class or namespace.
#
# Current line is probably not inside an initializer list since
# we saw one of those things without seeing the starting colon.
return False
# Got to the beginning of the file without seeing the start of
# constructor initializer list.
return False | [
"def",
"IsInitializerList",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
",",
"1",
",",
"-",
"1",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
"if",
"i",
"==",
"linenum",
":",
"remove_function_body",
"=",
"Match",
"(",
"r'^(.*)\\{\\s*$'",
",",
"line",
")",
"if",
"remove_function_body",
":",
"line",
"=",
"remove_function_body",
".",
"group",
"(",
"1",
")",
"if",
"Search",
"(",
"r'\\s:\\s*\\w+[({]'",
",",
"line",
")",
":",
"# A lone colon tend to indicate the start of a constructor",
"# initializer list. It could also be a ternary operator, which",
"# also tend to appear in constructor initializer lists as",
"# opposed to parameter lists.",
"return",
"True",
"if",
"Search",
"(",
"r'\\}\\s*,\\s*$'",
",",
"line",
")",
":",
"# A closing brace followed by a comma is probably the end of a",
"# brace-initialized member in constructor initializer list.",
"return",
"True",
"if",
"Search",
"(",
"r'[{};]\\s*$'",
",",
"line",
")",
":",
"# Found one of the following:",
"# - A closing brace or semicolon, probably the end of the previous",
"# function.",
"# - An opening brace, probably the start of current class or namespace.",
"#",
"# Current line is probably not inside an initializer list since",
"# we saw one of those things without seeing the starting colon.",
"return",
"False",
"# Got to the beginning of the file without seeing the start of",
"# constructor initializer list.",
"return",
"False"
] | https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L5041-L5080 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py | python | pack_struct | (builder, values) | return st | Pack a sequence of values into a LLVM struct. | Pack a sequence of values into a LLVM struct. | [
"Pack",
"a",
"sequence",
"of",
"values",
"into",
"a",
"LLVM",
"struct",
"."
] | def pack_struct(builder, values):
"""
Pack a sequence of values into a LLVM struct.
"""
structty = ir.LiteralStructType([v.type for v in values])
st = structty(ir.Undefined)
for i, v in enumerate(values):
st = builder.insert_value(st, v, i)
return st | [
"def",
"pack_struct",
"(",
"builder",
",",
"values",
")",
":",
"structty",
"=",
"ir",
".",
"LiteralStructType",
"(",
"[",
"v",
".",
"type",
"for",
"v",
"in",
"values",
"]",
")",
"st",
"=",
"structty",
"(",
"ir",
".",
"Undefined",
")",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"values",
")",
":",
"st",
"=",
"builder",
".",
"insert_value",
"(",
"st",
",",
"v",
",",
"i",
")",
"return",
"st"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py#L637-L645 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/urllib.py | python | thishost | () | return _thishost | Return the IP address of the current host. | Return the IP address of the current host. | [
"Return",
"the",
"IP",
"address",
"of",
"the",
"current",
"host",
"."
] | def thishost():
"""Return the IP address of the current host."""
global _thishost
if _thishost is None:
try:
_thishost = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
_thishost = socket.gethostbyname('localhost')
return _thishost | [
"def",
"thishost",
"(",
")",
":",
"global",
"_thishost",
"if",
"_thishost",
"is",
"None",
":",
"try",
":",
"_thishost",
"=",
"socket",
".",
"gethostbyname",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"except",
"socket",
".",
"gaierror",
":",
"_thishost",
"=",
"socket",
".",
"gethostbyname",
"(",
"'localhost'",
")",
"return",
"_thishost"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/urllib.py#L826-L834 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bernoulli.py | python | Bernoulli.validate_args | (self) | return self._validate_args | Boolean describing behavior on invalid input. | Boolean describing behavior on invalid input. | [
"Boolean",
"describing",
"behavior",
"on",
"invalid",
"input",
"."
] | def validate_args(self):
"""Boolean describing behavior on invalid input."""
return self._validate_args | [
"def",
"validate_args",
"(",
"self",
")",
":",
"return",
"self",
".",
"_validate_args"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bernoulli.py#L88-L90 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/vision/models/shufflenetv2.py | python | shufflenet_v2_x0_25 | (pretrained=False, **kwargs) | return _shufflenet_v2(
"shufflenet_v2_x0_25", scale=0.25, pretrained=pretrained, **kwargs) | ShuffleNetV2 with 0.25x output channels, as described in
`"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_ 。
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet. Default: False.
Examples:
.. code-block:: python
import paddle
from paddle.vision.models import shufflenet_v2_x0_25
# build model
model = shufflenet_v2_x0_25()
# build model and load imagenet pretrained weight
# model = shufflenet_v2_x0_25(pretrained=True)
x = paddle.rand([1, 3, 224, 224])
out = model(x)
print(out.shape) | ShuffleNetV2 with 0.25x output channels, as described in
`"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_ 。 | [
"ShuffleNetV2",
"with",
"0",
".",
"25x",
"output",
"channels",
"as",
"described",
"in",
"ShuffleNet",
"V2",
":",
"Practical",
"Guidelines",
"for",
"Ecient",
"CNN",
"Architecture",
"Design",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1807",
".",
"11164",
".",
"pdf",
">",
"_",
"。"
] | def shufflenet_v2_x0_25(pretrained=False, **kwargs):
"""ShuffleNetV2 with 0.25x output channels, as described in
`"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_ 。
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet. Default: False.
Examples:
.. code-block:: python
import paddle
from paddle.vision.models import shufflenet_v2_x0_25
# build model
model = shufflenet_v2_x0_25()
# build model and load imagenet pretrained weight
# model = shufflenet_v2_x0_25(pretrained=True)
x = paddle.rand([1, 3, 224, 224])
out = model(x)
print(out.shape)
"""
return _shufflenet_v2(
"shufflenet_v2_x0_25", scale=0.25, pretrained=pretrained, **kwargs) | [
"def",
"shufflenet_v2_x0_25",
"(",
"pretrained",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_shufflenet_v2",
"(",
"\"shufflenet_v2_x0_25\"",
",",
"scale",
"=",
"0.25",
",",
"pretrained",
"=",
"pretrained",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/vision/models/shufflenetv2.py#L319-L345 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/tools/build/src/build/virtual_target.py | python | traverse | (target, include_roots = False, include_sources = False) | return result | Traverses the dependency graph of 'target' and return all targets that will
be created before this one is created. If root of some dependency graph is
found during traversal, it's either included or not, dependencing of the
value of 'include_roots'. In either case, sources of root are not traversed. | Traverses the dependency graph of 'target' and return all targets that will
be created before this one is created. If root of some dependency graph is
found during traversal, it's either included or not, dependencing of the
value of 'include_roots'. In either case, sources of root are not traversed. | [
"Traverses",
"the",
"dependency",
"graph",
"of",
"target",
"and",
"return",
"all",
"targets",
"that",
"will",
"be",
"created",
"before",
"this",
"one",
"is",
"created",
".",
"If",
"root",
"of",
"some",
"dependency",
"graph",
"is",
"found",
"during",
"traversal",
"it",
"s",
"either",
"included",
"or",
"not",
"dependencing",
"of",
"the",
"value",
"of",
"include_roots",
".",
"In",
"either",
"case",
"sources",
"of",
"root",
"are",
"not",
"traversed",
"."
] | def traverse (target, include_roots = False, include_sources = False):
""" Traverses the dependency graph of 'target' and return all targets that will
be created before this one is created. If root of some dependency graph is
found during traversal, it's either included or not, dependencing of the
value of 'include_roots'. In either case, sources of root are not traversed.
"""
assert isinstance(target, VirtualTarget)
assert isinstance(include_roots, (int, bool))
assert isinstance(include_sources, (int, bool))
result = []
if target.action ():
action = target.action ()
# This includes 'target' as well
result += action.targets ()
for t in action.sources ():
# FIXME:
# TODO: see comment in Manager.register_object ()
#if not isinstance (t, VirtualTarget):
# t = target.project_.manager_.get_object (t)
if not t.root ():
result += traverse (t, include_roots, include_sources)
elif include_roots:
result.append (t)
elif include_sources:
result.append (target)
return result | [
"def",
"traverse",
"(",
"target",
",",
"include_roots",
"=",
"False",
",",
"include_sources",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"target",
",",
"VirtualTarget",
")",
"assert",
"isinstance",
"(",
"include_roots",
",",
"(",
"int",
",",
"bool",
")",
")",
"assert",
"isinstance",
"(",
"include_sources",
",",
"(",
"int",
",",
"bool",
")",
")",
"result",
"=",
"[",
"]",
"if",
"target",
".",
"action",
"(",
")",
":",
"action",
"=",
"target",
".",
"action",
"(",
")",
"# This includes 'target' as well",
"result",
"+=",
"action",
".",
"targets",
"(",
")",
"for",
"t",
"in",
"action",
".",
"sources",
"(",
")",
":",
"# FIXME:",
"# TODO: see comment in Manager.register_object ()",
"#if not isinstance (t, VirtualTarget):",
"# t = target.project_.manager_.get_object (t)",
"if",
"not",
"t",
".",
"root",
"(",
")",
":",
"result",
"+=",
"traverse",
"(",
"t",
",",
"include_roots",
",",
"include_sources",
")",
"elif",
"include_roots",
":",
"result",
".",
"append",
"(",
"t",
")",
"elif",
"include_sources",
":",
"result",
".",
"append",
"(",
"target",
")",
"return",
"result"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/virtual_target.py#L963-L996 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/generator/eclipse.py | python | GetAllIncludeDirectories | (target_list, target_dicts,
shared_intermediate_dirs, config_name, params,
compiler_path) | return all_includes_list | Calculate the set of include directories to be used.
Returns:
A list including all the include_dir's specified for every target followed
by any include directories that were added as cflag compiler options. | Calculate the set of include directories to be used. | [
"Calculate",
"the",
"set",
"of",
"include",
"directories",
"to",
"be",
"used",
"."
] | def GetAllIncludeDirectories(target_list, target_dicts,
shared_intermediate_dirs, config_name, params,
compiler_path):
"""Calculate the set of include directories to be used.
Returns:
A list including all the include_dir's specified for every target followed
by any include directories that were added as cflag compiler options.
"""
gyp_includes_set = set()
compiler_includes_list = []
# Find compiler's default include dirs.
if compiler_path:
command = shlex.split(compiler_path)
command.extend(['-E', '-xc++', '-v', '-'])
proc = subprocess.Popen(args=command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = proc.communicate()[1]
# Extract the list of include dirs from the output, which has this format:
# ...
# #include "..." search starts here:
# #include <...> search starts here:
# /usr/include/c++/4.6
# /usr/local/include
# End of search list.
# ...
in_include_list = False
for line in output.splitlines():
if line.startswith('#include'):
in_include_list = True
continue
if line.startswith('End of search list.'):
break
if in_include_list:
include_dir = line.strip()
if include_dir not in compiler_includes_list:
compiler_includes_list.append(include_dir)
flavor = gyp.common.GetFlavor(params)
if flavor == 'win':
generator_flags = params.get('generator_flags', {})
for target_name in target_list:
target = target_dicts[target_name]
if config_name in target['configurations']:
config = target['configurations'][config_name]
# Look for any include dirs that were explicitly added via cflags. This
# may be done in gyp files to force certain includes to come at the end.
# TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and
# remove this.
if flavor == 'win':
msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags)
cflags = msvs_settings.GetCflags(config_name)
else:
cflags = config['cflags']
for cflag in cflags:
if cflag.startswith('-I'):
include_dir = cflag[2:]
if include_dir not in compiler_includes_list:
compiler_includes_list.append(include_dir)
# Find standard gyp include dirs.
if config.has_key('include_dirs'):
include_dirs = config['include_dirs']
for shared_intermediate_dir in shared_intermediate_dirs:
for include_dir in include_dirs:
include_dir = include_dir.replace('$SHARED_INTERMEDIATE_DIR',
shared_intermediate_dir)
if not os.path.isabs(include_dir):
base_dir = os.path.dirname(target_name)
include_dir = base_dir + '/' + include_dir
include_dir = os.path.abspath(include_dir)
gyp_includes_set.add(include_dir)
# Generate a list that has all the include dirs.
all_includes_list = list(gyp_includes_set)
all_includes_list.sort()
for compiler_include in compiler_includes_list:
if not compiler_include in gyp_includes_set:
all_includes_list.append(compiler_include)
# All done.
return all_includes_list | [
"def",
"GetAllIncludeDirectories",
"(",
"target_list",
",",
"target_dicts",
",",
"shared_intermediate_dirs",
",",
"config_name",
",",
"params",
",",
"compiler_path",
")",
":",
"gyp_includes_set",
"=",
"set",
"(",
")",
"compiler_includes_list",
"=",
"[",
"]",
"# Find compiler's default include dirs.",
"if",
"compiler_path",
":",
"command",
"=",
"shlex",
".",
"split",
"(",
"compiler_path",
")",
"command",
".",
"extend",
"(",
"[",
"'-E'",
",",
"'-xc++'",
",",
"'-v'",
",",
"'-'",
"]",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
"=",
"command",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"output",
"=",
"proc",
".",
"communicate",
"(",
")",
"[",
"1",
"]",
"# Extract the list of include dirs from the output, which has this format:",
"# ...",
"# #include \"...\" search starts here:",
"# #include <...> search starts here:",
"# /usr/include/c++/4.6",
"# /usr/local/include",
"# End of search list.",
"# ...",
"in_include_list",
"=",
"False",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'#include'",
")",
":",
"in_include_list",
"=",
"True",
"continue",
"if",
"line",
".",
"startswith",
"(",
"'End of search list.'",
")",
":",
"break",
"if",
"in_include_list",
":",
"include_dir",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"include_dir",
"not",
"in",
"compiler_includes_list",
":",
"compiler_includes_list",
".",
"append",
"(",
"include_dir",
")",
"flavor",
"=",
"gyp",
".",
"common",
".",
"GetFlavor",
"(",
"params",
")",
"if",
"flavor",
"==",
"'win'",
":",
"generator_flags",
"=",
"params",
".",
"get",
"(",
"'generator_flags'",
",",
"{",
"}",
")",
"for",
"target_name",
"in",
"target_list",
":",
"target",
"=",
"target_dicts",
"[",
"target_name",
"]",
"if",
"config_name",
"in",
"target",
"[",
"'configurations'",
"]",
":",
"config",
"=",
"target",
"[",
"'configurations'",
"]",
"[",
"config_name",
"]",
"# Look for any include dirs that were explicitly added via cflags. This",
"# may be done in gyp files to force certain includes to come at the end.",
"# TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and",
"# remove this.",
"if",
"flavor",
"==",
"'win'",
":",
"msvs_settings",
"=",
"gyp",
".",
"msvs_emulation",
".",
"MsvsSettings",
"(",
"target",
",",
"generator_flags",
")",
"cflags",
"=",
"msvs_settings",
".",
"GetCflags",
"(",
"config_name",
")",
"else",
":",
"cflags",
"=",
"config",
"[",
"'cflags'",
"]",
"for",
"cflag",
"in",
"cflags",
":",
"if",
"cflag",
".",
"startswith",
"(",
"'-I'",
")",
":",
"include_dir",
"=",
"cflag",
"[",
"2",
":",
"]",
"if",
"include_dir",
"not",
"in",
"compiler_includes_list",
":",
"compiler_includes_list",
".",
"append",
"(",
"include_dir",
")",
"# Find standard gyp include dirs.",
"if",
"config",
".",
"has_key",
"(",
"'include_dirs'",
")",
":",
"include_dirs",
"=",
"config",
"[",
"'include_dirs'",
"]",
"for",
"shared_intermediate_dir",
"in",
"shared_intermediate_dirs",
":",
"for",
"include_dir",
"in",
"include_dirs",
":",
"include_dir",
"=",
"include_dir",
".",
"replace",
"(",
"'$SHARED_INTERMEDIATE_DIR'",
",",
"shared_intermediate_dir",
")",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"include_dir",
")",
":",
"base_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"target_name",
")",
"include_dir",
"=",
"base_dir",
"+",
"'/'",
"+",
"include_dir",
"include_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"include_dir",
")",
"gyp_includes_set",
".",
"add",
"(",
"include_dir",
")",
"# Generate a list that has all the include dirs.",
"all_includes_list",
"=",
"list",
"(",
"gyp_includes_set",
")",
"all_includes_list",
".",
"sort",
"(",
")",
"for",
"compiler_include",
"in",
"compiler_includes_list",
":",
"if",
"not",
"compiler_include",
"in",
"gyp_includes_set",
":",
"all_includes_list",
".",
"append",
"(",
"compiler_include",
")",
"# All done.",
"return",
"all_includes_list"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/eclipse.py#L80-L166 | |
HKUST-Aerial-Robotics/Fast-Planner | 2ddd7793eecd573dbb5b47e2c985aa06606df3cf | uav_simulator/Utils/multi_map_server/src/multi_map_server/msg/_MultiSparseMap3D.py | python | MultiSparseMap3D.__init__ | (self, *args, **kwds) | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
maps,origins
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields. | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments. | [
"Constructor",
".",
"Any",
"message",
"fields",
"that",
"are",
"implicitly",
"/",
"explicitly",
"set",
"to",
"None",
"will",
"be",
"assigned",
"a",
"default",
"value",
".",
"The",
"recommend",
"use",
"is",
"keyword",
"arguments",
"as",
"this",
"is",
"more",
"robust",
"to",
"future",
"message",
"changes",
".",
"You",
"cannot",
"mix",
"in",
"-",
"order",
"arguments",
"and",
"keyword",
"arguments",
"."
] | def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
maps,origins
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(MultiSparseMap3D, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.maps is None:
self.maps = []
if self.origins is None:
self.origins = []
else:
self.maps = []
self.origins = [] | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"args",
"or",
"kwds",
":",
"super",
"(",
"MultiSparseMap3D",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"#message fields cannot be None, assign default values for those that are",
"if",
"self",
".",
"maps",
"is",
"None",
":",
"self",
".",
"maps",
"=",
"[",
"]",
"if",
"self",
".",
"origins",
"is",
"None",
":",
"self",
".",
"origins",
"=",
"[",
"]",
"else",
":",
"self",
".",
"maps",
"=",
"[",
"]",
"self",
".",
"origins",
"=",
"[",
"]"
] | https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/multi_map_server/src/multi_map_server/msg/_MultiSparseMap3D.py#L95-L118 | ||
google/shaka-packager | e1b0c7c45431327fd3ce193514a5407d07b39b22 | packager/third_party/protobuf/python/google/protobuf/internal/containers.py | python | RepeatedCompositeFieldContainer.__getslice__ | (self, start, stop) | return self._values[start:stop] | Retrieves the subset of items from between the specified indices. | Retrieves the subset of items from between the specified indices. | [
"Retrieves",
"the",
"subset",
"of",
"items",
"from",
"between",
"the",
"specified",
"indices",
"."
] | def __getslice__(self, start, stop):
"""Retrieves the subset of items from between the specified indices."""
return self._values[start:stop] | [
"def",
"__getslice__",
"(",
"self",
",",
"start",
",",
"stop",
")",
":",
"return",
"self",
".",
"_values",
"[",
"start",
":",
"stop",
"]"
] | https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/containers.py#L410-L412 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/mixture/gmm.py | python | _GMMBase._set_covars | (self, covars) | Provide values for covariance. | Provide values for covariance. | [
"Provide",
"values",
"for",
"covariance",
"."
] | def _set_covars(self, covars):
"""Provide values for covariance."""
covars = np.asarray(covars)
_validate_covars(covars, self.covariance_type, self.n_components)
self.covars_ = covars | [
"def",
"_set_covars",
"(",
"self",
",",
"covars",
")",
":",
"covars",
"=",
"np",
".",
"asarray",
"(",
"covars",
")",
"_validate_covars",
"(",
"covars",
",",
"self",
".",
"covariance_type",
",",
"self",
".",
"n_components",
")",
"self",
".",
"covars_",
"=",
"covars"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/gmm.py#L296-L300 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/database.py | python | DependencyGraph.add_edge | (self, x, y, label=None) | Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type label: ``str`` or ``None`` | Add an edge from distribution *x* to distribution *y* with the given | [
"Add",
"an",
"edge",
"from",
"distribution",
"*",
"x",
"*",
"to",
"distribution",
"*",
"y",
"*",
"with",
"the",
"given"
] | def add_edge(self, x, y, label=None):
"""Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type label: ``str`` or ``None``
"""
self.adjacency_list[x].append((y, label))
# multiple edges are allowed, so be careful
if x not in self.reverse_list[y]:
self.reverse_list[y].append(x) | [
"def",
"add_edge",
"(",
"self",
",",
"x",
",",
"y",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"adjacency_list",
"[",
"x",
"]",
".",
"append",
"(",
"(",
"y",
",",
"label",
")",
")",
"# multiple edges are allowed, so be careful",
"if",
"x",
"not",
"in",
"self",
".",
"reverse_list",
"[",
"y",
"]",
":",
"self",
".",
"reverse_list",
"[",
"y",
"]",
".",
"append",
"(",
"x",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/database.py#L2223-L2249 | ||
qboticslabs/mastering_ros | d83e78f30acc45b0f18522c1d5fae3a7f52974b9 | chapter_9_codes/chefbot/chefbot_bringup/scripts/bkup_working/launchpad_process_node.py | python | Process_Sensor._HandleVelocityCommand | (self,twistCommand) | Handle movement requests. | Handle movement requests. | [
"Handle",
"movement",
"requests",
"."
] | def _HandleVelocityCommand(self,twistCommand):
""" Handle movement requests. """
v = twistCommand.linear.x # m/s
omega = twistCommand.angular.z # rad/s
rospy.logwarn("Handling twist command: " + str(v) + "," + str(omega))
# omega= omega * 1000
# message = 's %.3f %.3f\r' % (v, omega)
message = 's %.3f %.3f\r' % (v, omega)
# rospy.logwarn(str(v)+str(omega))
# rospy.logwarn("Sending speed command message: " + message)
angularVelocityOffset = 0.5 * omega * self.trackwidth
speed_limit = 100
if (v > 0):
if ((speed_limit * self.distance_per_count) - math.fabs(angularVelocityOffset) < v):
v = (speed_limit * self.distance_per_count) - math.fabs(angularVelocityOffset)
elif(v < 0):
if (-((speed_limit * self.distance_per_count) - math.fabs(angularVelocityOffset)) > v):
v = -((speed_limit * self.distance_per_count) - math.fabs(angularVelocityOffset))
expectedLeftSpeed = v - angularVelocityOffset
expectedRightSpeed = v + angularVelocityOffset
expectedLeftSpeed = expectedLeftSpeed / self.distance_per_count
expectedRightSpeed = expectedRightSpeed / self.distance_per_count
NormalizedLeftCV = expectedLeftSpeed
NormalizedRightCV = expectedRightSpeed
rospy.logwarn("Actual speed")
# rospy.loginfo(NormalizedLeftCV)
# rospy.loginfo(NormalizedRightCV)
old_max = 1
old_min = -1
new_max = 1023
new_min = -1023
old_left_value = NormalizedLeftCV
old_right_value = NormalizedRightCV
actual_left_speed = ( (old_left_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min
actual_right_speed = ( (old_left_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min
rospy.logwarn("Actual speed")
rospy.logwarn(actual_left_speed)
rospy.logwarn(actual_right_speed)
#Path for turning
self.Publish_Speed(actual_left_speed ,actual_right_speed,v,omega) | [
"def",
"_HandleVelocityCommand",
"(",
"self",
",",
"twistCommand",
")",
":",
"v",
"=",
"twistCommand",
".",
"linear",
".",
"x",
"# m/s",
"omega",
"=",
"twistCommand",
".",
"angular",
".",
"z",
"# rad/s",
"rospy",
".",
"logwarn",
"(",
"\"Handling twist command: \"",
"+",
"str",
"(",
"v",
")",
"+",
"\",\"",
"+",
"str",
"(",
"omega",
")",
")",
"#\t\tomega= omega * 1000",
"#\t\tmessage = 's %.3f %.3f\\r' % (v, omega)",
"message",
"=",
"'s %.3f %.3f\\r'",
"%",
"(",
"v",
",",
"omega",
")",
"#\t\trospy.logwarn(str(v)+str(omega))",
"#\t\trospy.logwarn(\"Sending speed command message: \" + message)",
"angularVelocityOffset",
"=",
"0.5",
"*",
"omega",
"*",
"self",
".",
"trackwidth",
"speed_limit",
"=",
"100",
"if",
"(",
"v",
">",
"0",
")",
":",
"if",
"(",
"(",
"speed_limit",
"*",
"self",
".",
"distance_per_count",
")",
"-",
"math",
".",
"fabs",
"(",
"angularVelocityOffset",
")",
"<",
"v",
")",
":",
"v",
"=",
"(",
"speed_limit",
"*",
"self",
".",
"distance_per_count",
")",
"-",
"math",
".",
"fabs",
"(",
"angularVelocityOffset",
")",
"elif",
"(",
"v",
"<",
"0",
")",
":",
"if",
"(",
"-",
"(",
"(",
"speed_limit",
"*",
"self",
".",
"distance_per_count",
")",
"-",
"math",
".",
"fabs",
"(",
"angularVelocityOffset",
")",
")",
">",
"v",
")",
":",
"v",
"=",
"-",
"(",
"(",
"speed_limit",
"*",
"self",
".",
"distance_per_count",
")",
"-",
"math",
".",
"fabs",
"(",
"angularVelocityOffset",
")",
")",
"expectedLeftSpeed",
"=",
"v",
"-",
"angularVelocityOffset",
"expectedRightSpeed",
"=",
"v",
"+",
"angularVelocityOffset",
"expectedLeftSpeed",
"=",
"expectedLeftSpeed",
"/",
"self",
".",
"distance_per_count",
"expectedRightSpeed",
"=",
"expectedRightSpeed",
"/",
"self",
".",
"distance_per_count",
"NormalizedLeftCV",
"=",
"expectedLeftSpeed",
"NormalizedRightCV",
"=",
"expectedRightSpeed",
"rospy",
".",
"logwarn",
"(",
"\"Actual speed\"",
")",
"#\t\trospy.loginfo(NormalizedLeftCV)",
"#\t\trospy.loginfo(NormalizedRightCV)",
"old_max",
"=",
"1",
"old_min",
"=",
"-",
"1",
"new_max",
"=",
"1023",
"new_min",
"=",
"-",
"1023",
"old_left_value",
"=",
"NormalizedLeftCV",
"old_right_value",
"=",
"NormalizedRightCV",
"actual_left_speed",
"=",
"(",
"(",
"old_left_value",
"-",
"old_min",
")",
"/",
"(",
"old_max",
"-",
"old_min",
")",
")",
"*",
"(",
"new_max",
"-",
"new_min",
")",
"+",
"new_min",
"actual_right_speed",
"=",
"(",
"(",
"old_left_value",
"-",
"old_min",
")",
"/",
"(",
"old_max",
"-",
"old_min",
")",
")",
"*",
"(",
"new_max",
"-",
"new_min",
")",
"+",
"new_min",
"rospy",
".",
"logwarn",
"(",
"\"Actual speed\"",
")",
"rospy",
".",
"logwarn",
"(",
"actual_left_speed",
")",
"rospy",
".",
"logwarn",
"(",
"actual_right_speed",
")",
"#Path for turning",
"self",
".",
"Publish_Speed",
"(",
"actual_left_speed",
",",
"actual_right_speed",
",",
"v",
",",
"omega",
")"
] | https://github.com/qboticslabs/mastering_ros/blob/d83e78f30acc45b0f18522c1d5fae3a7f52974b9/chapter_9_codes/chefbot/chefbot_bringup/scripts/bkup_working/launchpad_process_node.py#L314-L381 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGrid.GetUnspecifiedValueText | (*args, **kwargs) | return _propgrid.PropertyGrid_GetUnspecifiedValueText(*args, **kwargs) | GetUnspecifiedValueText(self, int argFlags=0) -> String | GetUnspecifiedValueText(self, int argFlags=0) -> String | [
"GetUnspecifiedValueText",
"(",
"self",
"int",
"argFlags",
"=",
"0",
")",
"-",
">",
"String"
] | def GetUnspecifiedValueText(*args, **kwargs):
"""GetUnspecifiedValueText(self, int argFlags=0) -> String"""
return _propgrid.PropertyGrid_GetUnspecifiedValueText(*args, **kwargs) | [
"def",
"GetUnspecifiedValueText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_GetUnspecifiedValueText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2295-L2297 | |
unsynchronized/gr-amps | 709d48272e7b605f34cfe89a517cc423923245e3 | docs/doxygen/doxyxml/base.py | python | Base._get_dict_members | (self, cat=None) | return self._dict_members[cat] | For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None. | For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None. | [
"For",
"given",
"category",
"a",
"dictionary",
"is",
"returned",
"mapping",
"member",
"names",
"to",
"members",
"of",
"that",
"category",
".",
"For",
"names",
"that",
"are",
"duplicated",
"the",
"name",
"is",
"mapped",
"to",
"None",
"."
] | def _get_dict_members(self, cat=None):
"""
For given category a dictionary is returned mapping member names to
members of that category. For names that are duplicated the name is
mapped to None.
"""
self.confirm_no_error()
if cat not in self._dict_members:
new_dict = {}
for mem in self.in_category(cat):
if mem.name() not in new_dict:
new_dict[mem.name()] = mem
else:
new_dict[mem.name()] = self.Duplicate
self._dict_members[cat] = new_dict
return self._dict_members[cat] | [
"def",
"_get_dict_members",
"(",
"self",
",",
"cat",
"=",
"None",
")",
":",
"self",
".",
"confirm_no_error",
"(",
")",
"if",
"cat",
"not",
"in",
"self",
".",
"_dict_members",
":",
"new_dict",
"=",
"{",
"}",
"for",
"mem",
"in",
"self",
".",
"in_category",
"(",
"cat",
")",
":",
"if",
"mem",
".",
"name",
"(",
")",
"not",
"in",
"new_dict",
":",
"new_dict",
"[",
"mem",
".",
"name",
"(",
")",
"]",
"=",
"mem",
"else",
":",
"new_dict",
"[",
"mem",
".",
"name",
"(",
")",
"]",
"=",
"self",
".",
"Duplicate",
"self",
".",
"_dict_members",
"[",
"cat",
"]",
"=",
"new_dict",
"return",
"self",
".",
"_dict_members",
"[",
"cat",
"]"
] | https://github.com/unsynchronized/gr-amps/blob/709d48272e7b605f34cfe89a517cc423923245e3/docs/doxygen/doxyxml/base.py#L122-L137 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/tools/transformers/gpt2_helper.py | python | Gpt2Helper.test_performance | (ort_session,
model,
device,
is_float16=False,
total_runs=100,
use_io_binding=True,
model_class="GPT2LMHeadModel",
has_position_ids=True,
has_attention_mask=True,
batch_size=8,
sequence_length=1,
past_sequence_length=32) | return latency | Generate random inputs and measure average latency of Onnx Runtime. | Generate random inputs and measure average latency of Onnx Runtime. | [
"Generate",
"random",
"inputs",
"and",
"measure",
"average",
"latency",
"of",
"Onnx",
"Runtime",
"."
] | def test_performance(ort_session,
model,
device,
is_float16=False,
total_runs=100,
use_io_binding=True,
model_class="GPT2LMHeadModel",
has_position_ids=True,
has_attention_mask=True,
batch_size=8,
sequence_length=1,
past_sequence_length=32):
""" Generate random inputs and measure average latency of Onnx Runtime.
"""
config: GPT2Config = model.config
output_buffers = None
if use_io_binding:
output_shapes = Gpt2Helper.get_output_shapes(batch_size, past_sequence_length, sequence_length, config,
model_class)
output_buffers = Gpt2Helper.get_output_buffers(output_shapes, device, is_float16)
dummy_inputs = Gpt2Helper.get_dummy_inputs(batch_size, past_sequence_length, sequence_length,
config.num_attention_heads, config.hidden_size, config.n_layer,
config.vocab_size, device, is_float16, has_position_ids,
has_attention_mask)
if use_io_binding:
_, latency = Gpt2Helper.onnxruntime_inference(ort_session, dummy_inputs, total_runs)
else:
_, latency = Gpt2Helper.onnxruntime_inference_with_binded_io(ort_session, dummy_inputs, output_buffers,
output_shapes, total_runs)
return latency | [
"def",
"test_performance",
"(",
"ort_session",
",",
"model",
",",
"device",
",",
"is_float16",
"=",
"False",
",",
"total_runs",
"=",
"100",
",",
"use_io_binding",
"=",
"True",
",",
"model_class",
"=",
"\"GPT2LMHeadModel\"",
",",
"has_position_ids",
"=",
"True",
",",
"has_attention_mask",
"=",
"True",
",",
"batch_size",
"=",
"8",
",",
"sequence_length",
"=",
"1",
",",
"past_sequence_length",
"=",
"32",
")",
":",
"config",
":",
"GPT2Config",
"=",
"model",
".",
"config",
"output_buffers",
"=",
"None",
"if",
"use_io_binding",
":",
"output_shapes",
"=",
"Gpt2Helper",
".",
"get_output_shapes",
"(",
"batch_size",
",",
"past_sequence_length",
",",
"sequence_length",
",",
"config",
",",
"model_class",
")",
"output_buffers",
"=",
"Gpt2Helper",
".",
"get_output_buffers",
"(",
"output_shapes",
",",
"device",
",",
"is_float16",
")",
"dummy_inputs",
"=",
"Gpt2Helper",
".",
"get_dummy_inputs",
"(",
"batch_size",
",",
"past_sequence_length",
",",
"sequence_length",
",",
"config",
".",
"num_attention_heads",
",",
"config",
".",
"hidden_size",
",",
"config",
".",
"n_layer",
",",
"config",
".",
"vocab_size",
",",
"device",
",",
"is_float16",
",",
"has_position_ids",
",",
"has_attention_mask",
")",
"if",
"use_io_binding",
":",
"_",
",",
"latency",
"=",
"Gpt2Helper",
".",
"onnxruntime_inference",
"(",
"ort_session",
",",
"dummy_inputs",
",",
"total_runs",
")",
"else",
":",
"_",
",",
"latency",
"=",
"Gpt2Helper",
".",
"onnxruntime_inference_with_binded_io",
"(",
"ort_session",
",",
"dummy_inputs",
",",
"output_buffers",
",",
"output_shapes",
",",
"total_runs",
")",
"return",
"latency"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/transformers/gpt2_helper.py#L713-L747 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Sizer._ReplaceWin | (*args, **kwargs) | return _core_.Sizer__ReplaceWin(*args, **kwargs) | _ReplaceWin(self, Window oldwin, Window newwin, bool recursive=False) -> bool | _ReplaceWin(self, Window oldwin, Window newwin, bool recursive=False) -> bool | [
"_ReplaceWin",
"(",
"self",
"Window",
"oldwin",
"Window",
"newwin",
"bool",
"recursive",
"=",
"False",
")",
"-",
">",
"bool"
] | def _ReplaceWin(*args, **kwargs):
"""_ReplaceWin(self, Window oldwin, Window newwin, bool recursive=False) -> bool"""
return _core_.Sizer__ReplaceWin(*args, **kwargs) | [
"def",
"_ReplaceWin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Sizer__ReplaceWin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14566-L14568 | |
deepmind/streetlearn | ccf1d60b9c45154894d45a897748aee85d7eb69b | streetlearn/python/agents/plain_agent.py | python | PlainAgent._torso | (self, input_) | return core_input | Processing of all the visual and language inputs to the LSTM core. | Processing of all the visual and language inputs to the LSTM core. | [
"Processing",
"of",
"all",
"the",
"visual",
"and",
"language",
"inputs",
"to",
"the",
"LSTM",
"core",
"."
] | def _torso(self, input_):
"""Processing of all the visual and language inputs to the LSTM core."""
# Extract the inputs
last_action, env_output = input_
last_reward, _, _, observation = env_output
if type(observation) == list:
frame = observation[self._idx_frame]
else:
frame = observation
# Convert to image to floats and normalise.
frame = tf.to_float(frame)
frame /= 255
# Feed image through convnet.
with tf.variable_scope('convnet'):
conv_out = frame
for i, (num_ch, num_blocks) in enumerate([(16, 2), (32, 2), (32, 2)]):
# Downscale.
conv_out = snt.Conv2D(num_ch, 3, stride=1, padding='SAME')(conv_out)
conv_out = tf.nn.pool(
conv_out,
window_shape=[3, 3],
pooling_type='MAX',
padding='SAME',
strides=[2, 2])
# Residual block(s).
for j in range(num_blocks):
with tf.variable_scope('residual_%d_%d' % (i, j)):
block_input = conv_out
conv_out = tf.nn.relu(conv_out)
conv_out = snt.Conv2D(num_ch, 3, stride=1, padding='SAME')(conv_out)
conv_out = tf.nn.relu(conv_out)
conv_out = snt.Conv2D(num_ch, 3, stride=1, padding='SAME')(conv_out)
conv_out += block_input
# Fully connected layer.
conv_out = tf.nn.relu(conv_out)
conv_out = snt.BatchFlatten()(conv_out)
conv_out = snt.Linear(256)(conv_out)
conv_out = tf.nn.relu(conv_out)
# Concatenate outputs of the visual and instruction pathways.
if self._feed_action_and_reward:
# Append clipped last reward and one hot last action.
tf.logging.info('Append last reward clipped to: %f', self._max_reward)
clipped_last_reward = tf.expand_dims(
tf.clip_by_value(last_reward, -self._max_reward, self._max_reward),
-1)
tf.logging.info('Append last action (one-hot of %d)', self._num_actions)
one_hot_last_action = tf.one_hot(last_action, self._num_actions)
core_input = tf.concat(
[conv_out, clipped_last_reward, one_hot_last_action],
axis=1)
else:
core_input = conv_out
return core_input | [
"def",
"_torso",
"(",
"self",
",",
"input_",
")",
":",
"# Extract the inputs",
"last_action",
",",
"env_output",
"=",
"input_",
"last_reward",
",",
"_",
",",
"_",
",",
"observation",
"=",
"env_output",
"if",
"type",
"(",
"observation",
")",
"==",
"list",
":",
"frame",
"=",
"observation",
"[",
"self",
".",
"_idx_frame",
"]",
"else",
":",
"frame",
"=",
"observation",
"# Convert to image to floats and normalise.",
"frame",
"=",
"tf",
".",
"to_float",
"(",
"frame",
")",
"frame",
"/=",
"255",
"# Feed image through convnet.",
"with",
"tf",
".",
"variable_scope",
"(",
"'convnet'",
")",
":",
"conv_out",
"=",
"frame",
"for",
"i",
",",
"(",
"num_ch",
",",
"num_blocks",
")",
"in",
"enumerate",
"(",
"[",
"(",
"16",
",",
"2",
")",
",",
"(",
"32",
",",
"2",
")",
",",
"(",
"32",
",",
"2",
")",
"]",
")",
":",
"# Downscale.",
"conv_out",
"=",
"snt",
".",
"Conv2D",
"(",
"num_ch",
",",
"3",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
")",
"(",
"conv_out",
")",
"conv_out",
"=",
"tf",
".",
"nn",
".",
"pool",
"(",
"conv_out",
",",
"window_shape",
"=",
"[",
"3",
",",
"3",
"]",
",",
"pooling_type",
"=",
"'MAX'",
",",
"padding",
"=",
"'SAME'",
",",
"strides",
"=",
"[",
"2",
",",
"2",
"]",
")",
"# Residual block(s).",
"for",
"j",
"in",
"range",
"(",
"num_blocks",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'residual_%d_%d'",
"%",
"(",
"i",
",",
"j",
")",
")",
":",
"block_input",
"=",
"conv_out",
"conv_out",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"conv_out",
")",
"conv_out",
"=",
"snt",
".",
"Conv2D",
"(",
"num_ch",
",",
"3",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
")",
"(",
"conv_out",
")",
"conv_out",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"conv_out",
")",
"conv_out",
"=",
"snt",
".",
"Conv2D",
"(",
"num_ch",
",",
"3",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
")",
"(",
"conv_out",
")",
"conv_out",
"+=",
"block_input",
"# Fully connected layer.",
"conv_out",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"conv_out",
")",
"conv_out",
"=",
"snt",
".",
"BatchFlatten",
"(",
")",
"(",
"conv_out",
")",
"conv_out",
"=",
"snt",
".",
"Linear",
"(",
"256",
")",
"(",
"conv_out",
")",
"conv_out",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"conv_out",
")",
"# Concatenate outputs of the visual and instruction pathways.",
"if",
"self",
".",
"_feed_action_and_reward",
":",
"# Append clipped last reward and one hot last action.",
"tf",
".",
"logging",
".",
"info",
"(",
"'Append last reward clipped to: %f'",
",",
"self",
".",
"_max_reward",
")",
"clipped_last_reward",
"=",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"clip_by_value",
"(",
"last_reward",
",",
"-",
"self",
".",
"_max_reward",
",",
"self",
".",
"_max_reward",
")",
",",
"-",
"1",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"'Append last action (one-hot of %d)'",
",",
"self",
".",
"_num_actions",
")",
"one_hot_last_action",
"=",
"tf",
".",
"one_hot",
"(",
"last_action",
",",
"self",
".",
"_num_actions",
")",
"core_input",
"=",
"tf",
".",
"concat",
"(",
"[",
"conv_out",
",",
"clipped_last_reward",
",",
"one_hot_last_action",
"]",
",",
"axis",
"=",
"1",
")",
"else",
":",
"core_input",
"=",
"conv_out",
"return",
"core_input"
] | https://github.com/deepmind/streetlearn/blob/ccf1d60b9c45154894d45a897748aee85d7eb69b/streetlearn/python/agents/plain_agent.py#L93-L149 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py | python | Type.is_const_qualified | (self) | return conf.lib.clang_isConstQualifiedType(self) | Determine whether a Type has the "const" qualifier set.
This does not look through typedefs that may have added "const"
at a different level. | Determine whether a Type has the "const" qualifier set. | [
"Determine",
"whether",
"a",
"Type",
"has",
"the",
"const",
"qualifier",
"set",
"."
] | def is_const_qualified(self):
"""Determine whether a Type has the "const" qualifier set.
This does not look through typedefs that may have added "const"
at a different level.
"""
return conf.lib.clang_isConstQualifiedType(self) | [
"def",
"is_const_qualified",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isConstQualifiedType",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L2038-L2044 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/pylib/utils/xvfb.py | python | Xvfb.Start | (self) | Start Xvfb and set an appropriate DISPLAY environment. Linux only.
Copied from tools/code_coverage/coverage_posix.py | Start Xvfb and set an appropriate DISPLAY environment. Linux only. | [
"Start",
"Xvfb",
"and",
"set",
"an",
"appropriate",
"DISPLAY",
"environment",
".",
"Linux",
"only",
"."
] | def Start(self):
"""Start Xvfb and set an appropriate DISPLAY environment. Linux only.
Copied from tools/code_coverage/coverage_posix.py
"""
if not _IsLinux():
return
proc = subprocess.Popen(['Xvfb', ':9', '-screen', '0', '1024x768x24',
'-ac'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
self._pid = proc.pid
if not self._pid:
raise Exception('Could not start Xvfb')
os.environ['DISPLAY'] = ':9'
# Now confirm, giving a chance for it to start if needed.
for _ in range(10):
proc = subprocess.Popen('xdpyinfo >/dev/null', shell=True)
_, retcode = os.waitpid(proc.pid, 0)
if retcode == 0:
break
time.sleep(0.25)
if retcode != 0:
raise Exception('Could not confirm Xvfb happiness') | [
"def",
"Start",
"(",
"self",
")",
":",
"if",
"not",
"_IsLinux",
"(",
")",
":",
"return",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'Xvfb'",
",",
"':9'",
",",
"'-screen'",
",",
"'0'",
",",
"'1024x768x24'",
",",
"'-ac'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"self",
".",
"_pid",
"=",
"proc",
".",
"pid",
"if",
"not",
"self",
".",
"_pid",
":",
"raise",
"Exception",
"(",
"'Could not start Xvfb'",
")",
"os",
".",
"environ",
"[",
"'DISPLAY'",
"]",
"=",
"':9'",
"# Now confirm, giving a chance for it to start if needed.",
"for",
"_",
"in",
"range",
"(",
"10",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"'xdpyinfo >/dev/null'",
",",
"shell",
"=",
"True",
")",
"_",
",",
"retcode",
"=",
"os",
".",
"waitpid",
"(",
"proc",
".",
"pid",
",",
"0",
")",
"if",
"retcode",
"==",
"0",
":",
"break",
"time",
".",
"sleep",
"(",
"0.25",
")",
"if",
"retcode",
"!=",
"0",
":",
"raise",
"Exception",
"(",
"'Could not confirm Xvfb happiness'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/utils/xvfb.py#L25-L48 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/trace.py | python | find_executable_linenos | (filename) | return find_lines(code, strs) | Return dict where keys are line numbers in the line number table. | Return dict where keys are line numbers in the line number table. | [
"Return",
"dict",
"where",
"keys",
"are",
"line",
"numbers",
"in",
"the",
"line",
"number",
"table",
"."
] | def find_executable_linenos(filename):
"""Return dict where keys are line numbers in the line number table."""
try:
prog = open(filename, "rU").read()
except IOError, err:
print >> sys.stderr, ("Not printing coverage data for %r: %s"
% (filename, err))
return {}
code = compile(prog, filename, "exec")
strs = find_strings(filename)
return find_lines(code, strs) | [
"def",
"find_executable_linenos",
"(",
"filename",
")",
":",
"try",
":",
"prog",
"=",
"open",
"(",
"filename",
",",
"\"rU\"",
")",
".",
"read",
"(",
")",
"except",
"IOError",
",",
"err",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"(",
"\"Not printing coverage data for %r: %s\"",
"%",
"(",
"filename",
",",
"err",
")",
")",
"return",
"{",
"}",
"code",
"=",
"compile",
"(",
"prog",
",",
"filename",
",",
"\"exec\"",
")",
"strs",
"=",
"find_strings",
"(",
"filename",
")",
"return",
"find_lines",
"(",
"code",
",",
"strs",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/trace.py#L438-L448 | |
ycm-core/ycmd | fc0fb7e5e15176cc5a2a30c80956335988c6b59a | ycmd/completers/cs/solutiondetection.py | python | FindSolutionPath | ( filepath ) | return path_to_solutionfile | Try to find suitable solution file given a source file path using all
available information sources | Try to find suitable solution file given a source file path using all
available information sources | [
"Try",
"to",
"find",
"suitable",
"solution",
"file",
"given",
"a",
"source",
"file",
"path",
"using",
"all",
"available",
"information",
"sources"
] | def FindSolutionPath( filepath ):
"""Try to find suitable solution file given a source file path using all
available information sources"""
# try to load ycm_extra_conf
# if it needs to be verified, abort here and try again later
module = extra_conf_store.ModuleForSourceFile( filepath )
path_to_solutionfile = PollModule( module, filepath )
if not path_to_solutionfile:
# ycm_extra_conf not available or did not provide a solution file
path_to_solutionfile = GuessFile( filepath )
return path_to_solutionfile | [
"def",
"FindSolutionPath",
"(",
"filepath",
")",
":",
"# try to load ycm_extra_conf",
"# if it needs to be verified, abort here and try again later",
"module",
"=",
"extra_conf_store",
".",
"ModuleForSourceFile",
"(",
"filepath",
")",
"path_to_solutionfile",
"=",
"PollModule",
"(",
"module",
",",
"filepath",
")",
"if",
"not",
"path_to_solutionfile",
":",
"# ycm_extra_conf not available or did not provide a solution file",
"path_to_solutionfile",
"=",
"GuessFile",
"(",
"filepath",
")",
"return",
"path_to_solutionfile"
] | https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/completers/cs/solutiondetection.py#L25-L37 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | InfoBar.RemoveButton | (*args, **kwargs) | return _controls_.InfoBar_RemoveButton(*args, **kwargs) | RemoveButton(self, int btnid) | RemoveButton(self, int btnid) | [
"RemoveButton",
"(",
"self",
"int",
"btnid",
")"
] | def RemoveButton(*args, **kwargs):
"""RemoveButton(self, int btnid)"""
return _controls_.InfoBar_RemoveButton(*args, **kwargs) | [
"def",
"RemoveButton",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"InfoBar_RemoveButton",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L7820-L7822 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntIntVV.AddBackSorted | (self, *args) | return _snap.TIntIntVV_AddBackSorted(self, *args) | AddBackSorted(TIntIntVV self, TIntV Val, bool const & Asc) -> int
Parameters:
Val: TVec< TInt,int > const &
Asc: bool const & | AddBackSorted(TIntIntVV self, TIntV Val, bool const & Asc) -> int | [
"AddBackSorted",
"(",
"TIntIntVV",
"self",
"TIntV",
"Val",
"bool",
"const",
"&",
"Asc",
")",
"-",
">",
"int"
] | def AddBackSorted(self, *args):
"""
AddBackSorted(TIntIntVV self, TIntV Val, bool const & Asc) -> int
Parameters:
Val: TVec< TInt,int > const &
Asc: bool const &
"""
return _snap.TIntIntVV_AddBackSorted(self, *args) | [
"def",
"AddBackSorted",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TIntIntVV_AddBackSorted",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L16887-L16896 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/changelog.py | python | mixed_text_from_docutils | (node) | return content | Takes most Text-ish docutils objects and converts them to MixedText
:param node: ``docutils.nodes.{paragraph, list_item, ...}`` text-ish
:returns: ``MixedText`` representing the given docutils object | Takes most Text-ish docutils objects and converts them to MixedText | [
"Takes",
"most",
"Text",
"-",
"ish",
"docutils",
"objects",
"and",
"converts",
"them",
"to",
"MixedText"
] | def mixed_text_from_docutils(node):
'''
Takes most Text-ish docutils objects and converts them to MixedText
:param node: ``docutils.nodes.{paragraph, list_item, ...}`` text-ish
:returns: ``MixedText`` representing the given docutils object
'''
content = MixedText()
for child in node.children:
if isinstance(child, docutils.nodes.paragraph):
content.texts.extend(mixed_text_from_docutils(child).texts)
elif isinstance(child, docutils.nodes.Text):
content.texts.append(child.astext())
elif isinstance(child, docutils.nodes.reference):
content.texts.append(reference_from_docutils(child))
elif isinstance(child, docutils.nodes.emphasis):
content.texts.append('*{0}*'.format(child.astext()))
elif isinstance(child, docutils.nodes.strong):
content.texts.append('**{0}**'.format(child.astext()))
elif isinstance(child, docutils.nodes.literal):
content.texts.append('``{0}``'.format(child.astext()))
elif isinstance(child, docutils.nodes.literal_block):
content.texts.append('\n\n ' + child.astext() + '\n')
elif isinstance(child, docutils.nodes.target):
pass
elif isinstance(child, docutils.nodes.system_message):
log.debug("Skipping system_message: {0}".format(child))
elif isinstance(child, docutils.nodes.bullet_list):
content.texts.append(bullet_list_class_from_docutils(child))
else:
try:
# Try to add it as plain text
log.debug("Trying to add {0}'s child of type {1}: '{2}'"
.format(type(node), type(child), child))
content.texts.append(child.astext())
except AttributeError:
log.debug("Ignored {0} child of type {1}: '{2}'"
.format(type(node), type(child), child))
return content | [
"def",
"mixed_text_from_docutils",
"(",
"node",
")",
":",
"content",
"=",
"MixedText",
"(",
")",
"for",
"child",
"in",
"node",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"paragraph",
")",
":",
"content",
".",
"texts",
".",
"extend",
"(",
"mixed_text_from_docutils",
"(",
"child",
")",
".",
"texts",
")",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"Text",
")",
":",
"content",
".",
"texts",
".",
"append",
"(",
"child",
".",
"astext",
"(",
")",
")",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"reference",
")",
":",
"content",
".",
"texts",
".",
"append",
"(",
"reference_from_docutils",
"(",
"child",
")",
")",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"emphasis",
")",
":",
"content",
".",
"texts",
".",
"append",
"(",
"'*{0}*'",
".",
"format",
"(",
"child",
".",
"astext",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"strong",
")",
":",
"content",
".",
"texts",
".",
"append",
"(",
"'**{0}**'",
".",
"format",
"(",
"child",
".",
"astext",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"literal",
")",
":",
"content",
".",
"texts",
".",
"append",
"(",
"'``{0}``'",
".",
"format",
"(",
"child",
".",
"astext",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"literal_block",
")",
":",
"content",
".",
"texts",
".",
"append",
"(",
"'\\n\\n '",
"+",
"child",
".",
"astext",
"(",
")",
"+",
"'\\n'",
")",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"target",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"system_message",
")",
":",
"log",
".",
"debug",
"(",
"\"Skipping system_message: {0}\"",
".",
"format",
"(",
"child",
")",
")",
"elif",
"isinstance",
"(",
"child",
",",
"docutils",
".",
"nodes",
".",
"bullet_list",
")",
":",
"content",
".",
"texts",
".",
"append",
"(",
"bullet_list_class_from_docutils",
"(",
"child",
")",
")",
"else",
":",
"try",
":",
"# Try to add it as plain text",
"log",
".",
"debug",
"(",
"\"Trying to add {0}'s child of type {1}: '{2}'\"",
".",
"format",
"(",
"type",
"(",
"node",
")",
",",
"type",
"(",
"child",
")",
",",
"child",
")",
")",
"content",
".",
"texts",
".",
"append",
"(",
"child",
".",
"astext",
"(",
")",
")",
"except",
"AttributeError",
":",
"log",
".",
"debug",
"(",
"\"Ignored {0} child of type {1}: '{2}'\"",
".",
"format",
"(",
"type",
"(",
"node",
")",
",",
"type",
"(",
"child",
")",
",",
"child",
")",
")",
"return",
"content"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/changelog.py#L143-L181 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/symsrc/pefile.py | python | Dump.add_header | (self, txt) | Adds a header element. | Adds a header element. | [
"Adds",
"a",
"header",
"element",
"."
] | def add_header(self, txt):
"""Adds a header element."""
self.add_line('-'*10+txt+'-'*10+'\n') | [
"def",
"add_header",
"(",
"self",
",",
"txt",
")",
":",
"self",
".",
"add_line",
"(",
"'-'",
"*",
"10",
"+",
"txt",
"+",
"'-'",
"*",
"10",
"+",
"'\\n'",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/symsrc/pefile.py#L644-L647 | ||
h2oai/datatable | 753197c3f76041dd6468e0f6a9708af92d80f6aa | ci/xbuild/wheel.py | python | Wheel._get_abi_tag | (self) | return abi | Return the ABI tag if available, otherwise just emulate it.
Adopted from pypa/wheel, see https://github.com/pypa/wheel/blob/a51977075740fda01b2c0e983a79bfe753567219/src/wheel/bdist_wheel.py#L67 | Return the ABI tag if available, otherwise just emulate it.
Adopted from pypa/wheel, see https://github.com/pypa/wheel/blob/a51977075740fda01b2c0e983a79bfe753567219/src/wheel/bdist_wheel.py#L67 | [
"Return",
"the",
"ABI",
"tag",
"if",
"available",
"otherwise",
"just",
"emulate",
"it",
".",
"Adopted",
"from",
"pypa",
"/",
"wheel",
"see",
"https",
":",
"//",
"github",
".",
"com",
"/",
"pypa",
"/",
"wheel",
"/",
"blob",
"/",
"a51977075740fda01b2c0e983a79bfe753567219",
"/",
"src",
"/",
"wheel",
"/",
"bdist_wheel",
".",
"py#L67"
] | def _get_abi_tag(self):
"""
Return the ABI tag if available, otherwise just emulate it.
Adopted from pypa/wheel, see https://github.com/pypa/wheel/blob/a51977075740fda01b2c0e983a79bfe753567219/src/wheel/bdist_wheel.py#L67
"""
def get_flag(var, fallback):
val = sysconfig.get_config_var(var)
if val is None:
self.log.report_abi_variable_missing(var)
return fallback
return val
soabi = sysconfig.get_config_var('SOABI')
if soabi:
parts = soabi.split("-")
assert parts[0] == "cpython"
abi = 'cp' + parts[1]
else:
abi = self._get_python_tag()
if get_flag('Py_DEBUG', hasattr(sys, 'gettotalrefcount')):
abi += 'd'
if sys.version_info < (3, 8) and get_flag('WITH_PYMALLOC', True):
abi += 'm'
return abi | [
"def",
"_get_abi_tag",
"(",
"self",
")",
":",
"def",
"get_flag",
"(",
"var",
",",
"fallback",
")",
":",
"val",
"=",
"sysconfig",
".",
"get_config_var",
"(",
"var",
")",
"if",
"val",
"is",
"None",
":",
"self",
".",
"log",
".",
"report_abi_variable_missing",
"(",
"var",
")",
"return",
"fallback",
"return",
"val",
"soabi",
"=",
"sysconfig",
".",
"get_config_var",
"(",
"'SOABI'",
")",
"if",
"soabi",
":",
"parts",
"=",
"soabi",
".",
"split",
"(",
"\"-\"",
")",
"assert",
"parts",
"[",
"0",
"]",
"==",
"\"cpython\"",
"abi",
"=",
"'cp'",
"+",
"parts",
"[",
"1",
"]",
"else",
":",
"abi",
"=",
"self",
".",
"_get_python_tag",
"(",
")",
"if",
"get_flag",
"(",
"'Py_DEBUG'",
",",
"hasattr",
"(",
"sys",
",",
"'gettotalrefcount'",
")",
")",
":",
"abi",
"+=",
"'d'",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"8",
")",
"and",
"get_flag",
"(",
"'WITH_PYMALLOC'",
",",
"True",
")",
":",
"abi",
"+=",
"'m'",
"return",
"abi"
] | https://github.com/h2oai/datatable/blob/753197c3f76041dd6468e0f6a9708af92d80f6aa/ci/xbuild/wheel.py#L420-L445 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/framework/ops.py | python | default_session | (session) | return _default_session_stack.get_controller(session) | Python "with" handler for defining a default session.
This function provides a means of registering a session for handling
Tensor.eval() and Operation.run() calls. It is primarily intended for use
by session.Session, but can be used with any object that implements
the Session.run() interface.
Use with the "with" keyword to specify that Tensor.eval() and Operation.run()
invocations within the scope of a block should be executed by a particular
session.
The default session applies to the current thread only, so it is always
possible to inspect the call stack and determine the scope of a default
session. If you create a new thread, and wish to use the default session
in that thread, you must explicitly add a "with ops.default_session(sess):"
block in that thread's function.
Example:
The following code examples are equivalent:
# 1. Using the Session object directly:
sess = ...
c = tf.constant(5.0)
sess.run(c)
# 2. Using default_session():
sess = ...
with ops.default_session(sess):
c = tf.constant(5.0)
result = c.eval()
# 3. Overriding default_session():
sess = ...
with ops.default_session(sess):
c = tf.constant(5.0)
with ops.default_session(...):
c.eval(session=sess)
Args:
session: The session to be installed as the default session.
Returns:
A context manager for the default session. | Python "with" handler for defining a default session. | [
"Python",
"with",
"handler",
"for",
"defining",
"a",
"default",
"session",
"."
] | def default_session(session):
"""Python "with" handler for defining a default session.
This function provides a means of registering a session for handling
Tensor.eval() and Operation.run() calls. It is primarily intended for use
by session.Session, but can be used with any object that implements
the Session.run() interface.
Use with the "with" keyword to specify that Tensor.eval() and Operation.run()
invocations within the scope of a block should be executed by a particular
session.
The default session applies to the current thread only, so it is always
possible to inspect the call stack and determine the scope of a default
session. If you create a new thread, and wish to use the default session
in that thread, you must explicitly add a "with ops.default_session(sess):"
block in that thread's function.
Example:
The following code examples are equivalent:
# 1. Using the Session object directly:
sess = ...
c = tf.constant(5.0)
sess.run(c)
# 2. Using default_session():
sess = ...
with ops.default_session(sess):
c = tf.constant(5.0)
result = c.eval()
# 3. Overriding default_session():
sess = ...
with ops.default_session(sess):
c = tf.constant(5.0)
with ops.default_session(...):
c.eval(session=sess)
Args:
session: The session to be installed as the default session.
Returns:
A context manager for the default session.
"""
return _default_session_stack.get_controller(session) | [
"def",
"default_session",
"(",
"session",
")",
":",
"return",
"_default_session_stack",
".",
"get_controller",
"(",
"session",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L3667-L3712 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/abinsalgorithm.py | python | AbinsAlgorithm._compare_one_line | (one_line, pattern) | return one_line and pattern in one_line.replace(" ", "") | compares line in the the form of string with a pattern.
:param one_line: line in the for mof string to be compared
:param pattern: string which should be present in the line after removing white spaces and setting all
letters to lower case
:returns: True is pattern present in the line, otherwise False | compares line in the the form of string with a pattern.
:param one_line: line in the for mof string to be compared
:param pattern: string which should be present in the line after removing white spaces and setting all
letters to lower case
:returns: True is pattern present in the line, otherwise False | [
"compares",
"line",
"in",
"the",
"the",
"form",
"of",
"string",
"with",
"a",
"pattern",
".",
":",
"param",
"one_line",
":",
"line",
"in",
"the",
"for",
"mof",
"string",
"to",
"be",
"compared",
":",
"param",
"pattern",
":",
"string",
"which",
"should",
"be",
"present",
"in",
"the",
"line",
"after",
"removing",
"white",
"spaces",
"and",
"setting",
"all",
"letters",
"to",
"lower",
"case",
":",
"returns",
":",
"True",
"is",
"pattern",
"present",
"in",
"the",
"line",
"otherwise",
"False"
] | def _compare_one_line(one_line, pattern):
"""
compares line in the the form of string with a pattern.
:param one_line: line in the for mof string to be compared
:param pattern: string which should be present in the line after removing white spaces and setting all
letters to lower case
:returns: True is pattern present in the line, otherwise False
"""
return one_line and pattern in one_line.replace(" ", "") | [
"def",
"_compare_one_line",
"(",
"one_line",
",",
"pattern",
")",
":",
"return",
"one_line",
"and",
"pattern",
"in",
"one_line",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/abinsalgorithm.py#L778-L786 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/coremodules/landuse/wxgui.py | python | AddZoneTool.get_optionspanel | (self, parent, size=(200, -1)) | return self._optionspanel | Return tool option widgets on given parent | Return tool option widgets on given parent | [
"Return",
"tool",
"option",
"widgets",
"on",
"given",
"parent"
] | def get_optionspanel(self, parent, size=(200, -1)):
"""
Return tool option widgets on given parent
"""
self._optionspanel = ObjPanel(parent, obj=self,
id=None,
attrconfigs=None,
#tables = None,
# table = None, id=None, ids=None,
groupnames=['options'],
func_change_obj=None,
show_groupnames=False, show_title=True, is_modal=False,
mainframe=self.parent.get_mainframe(),
pos=wx.DefaultPosition, size=size, style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER,
func_apply=self.on_apply_option,
immediate_apply=False, panelstyle='default', # 'instrumental'
standartbuttons=['apply', 'restore'])
return self._optionspanel | [
"def",
"get_optionspanel",
"(",
"self",
",",
"parent",
",",
"size",
"=",
"(",
"200",
",",
"-",
"1",
")",
")",
":",
"self",
".",
"_optionspanel",
"=",
"ObjPanel",
"(",
"parent",
",",
"obj",
"=",
"self",
",",
"id",
"=",
"None",
",",
"attrconfigs",
"=",
"None",
",",
"#tables = None,",
"# table = None, id=None, ids=None,",
"groupnames",
"=",
"[",
"'options'",
"]",
",",
"func_change_obj",
"=",
"None",
",",
"show_groupnames",
"=",
"False",
",",
"show_title",
"=",
"True",
",",
"is_modal",
"=",
"False",
",",
"mainframe",
"=",
"self",
".",
"parent",
".",
"get_mainframe",
"(",
")",
",",
"pos",
"=",
"wx",
".",
"DefaultPosition",
",",
"size",
"=",
"size",
",",
"style",
"=",
"wx",
".",
"MAXIMIZE_BOX",
"|",
"wx",
".",
"RESIZE_BORDER",
",",
"func_apply",
"=",
"self",
".",
"on_apply_option",
",",
"immediate_apply",
"=",
"False",
",",
"panelstyle",
"=",
"'default'",
",",
"# 'instrumental'",
"standartbuttons",
"=",
"[",
"'apply'",
",",
"'restore'",
"]",
")",
"return",
"self",
".",
"_optionspanel"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/landuse/wxgui.py#L311-L329 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_ev_parser.py | python | p_optdir | (p) | optdir : | optdir : | [
"optdir",
":"
] | def p_optdir(p):
'optdir : '
p[0] = Event | [
"def",
"p_optdir",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Event"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_ev_parser.py#L303-L305 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/fft/_pocketfft.py | python | irfft | (a, n=None, axis=-1, norm=None) | return output | Compute the inverse of the n-point DFT for real input.
This function computes the inverse of the one-dimensional *n*-point
discrete Fourier Transform of real input computed by `rfft`.
In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical
accuracy. (See Notes below for why ``len(a)`` is necessary here.)
The input is expected to be in the form returned by `rfft`, i.e. the
real zero-frequency term followed by the complex positive frequency terms
in order of increasing frequency. Since the discrete Fourier Transform of
real input is Hermitian-symmetric, the negative frequency terms are taken
to be the complex conjugates of the corresponding positive frequency terms.
Parameters
----------
a : array_like
The input array.
n : int, optional
Length of the transformed axis of the output.
For `n` output points, ``n//2+1`` input points are necessary. If the
input is longer than this, it is cropped. If it is shorter than this,
it is padded with zeros. If `n` is not given, it is taken to be
``2*(m-1)`` where ``m`` is the length of the input along the axis
specified by `axis`.
axis : int, optional
Axis over which to compute the inverse FFT. If not given, the last
axis is used.
norm : {None, "ortho"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is None.
Returns
-------
out : ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
The length of the transformed axis is `n`, or, if `n` is not given,
``2*(m-1)`` where ``m`` is the length of the transformed axis of the
input. To get an odd number of output points, `n` must be specified.
Raises
------
IndexError
If `axis` is larger than the last axis of `a`.
See Also
--------
numpy.fft : For definition of the DFT and conventions used.
rfft : The one-dimensional FFT of real input, of which `irfft` is inverse.
fft : The one-dimensional FFT.
irfft2 : The inverse of the two-dimensional FFT of real input.
irfftn : The inverse of the *n*-dimensional FFT of real input.
Notes
-----
Returns the real valued `n`-point inverse discrete Fourier transform
of `a`, where `a` contains the non-negative frequency terms of a
Hermitian-symmetric sequence. `n` is the length of the result, not the
input.
If you specify an `n` such that `a` must be zero-padded or truncated, the
extra/removed values will be added/removed at high frequencies. One can
thus resample a series to `m` points via Fourier interpolation by:
``a_resamp = irfft(rfft(a), m)``.
The correct interpretation of the hermitian input depends on the length of
the original data, as given by `n`. This is because each input shape could
correspond to either an odd or even length signal. By default, `irfft`
assumes an even output length which puts the last entry at the Nyquist
frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,
the value is thus treated as purely real. To avoid losing information, the
correct length of the real input **must** be given.
Examples
--------
>>> np.fft.ifft([1, -1j, -1, 1j])
array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary
>>> np.fft.irfft([1, -1j, -1])
array([0., 1., 0., 0.])
Notice how the last term in the input to the ordinary `ifft` is the
complex conjugate of the second term, and the output has zero imaginary
part everywhere. When calling `irfft`, the negative frequencies are not
specified, and the output array is purely real. | Compute the inverse of the n-point DFT for real input. | [
"Compute",
"the",
"inverse",
"of",
"the",
"n",
"-",
"point",
"DFT",
"for",
"real",
"input",
"."
] | def irfft(a, n=None, axis=-1, norm=None):
"""
Compute the inverse of the n-point DFT for real input.
This function computes the inverse of the one-dimensional *n*-point
discrete Fourier Transform of real input computed by `rfft`.
In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical
accuracy. (See Notes below for why ``len(a)`` is necessary here.)
The input is expected to be in the form returned by `rfft`, i.e. the
real zero-frequency term followed by the complex positive frequency terms
in order of increasing frequency. Since the discrete Fourier Transform of
real input is Hermitian-symmetric, the negative frequency terms are taken
to be the complex conjugates of the corresponding positive frequency terms.
Parameters
----------
a : array_like
The input array.
n : int, optional
Length of the transformed axis of the output.
For `n` output points, ``n//2+1`` input points are necessary. If the
input is longer than this, it is cropped. If it is shorter than this,
it is padded with zeros. If `n` is not given, it is taken to be
``2*(m-1)`` where ``m`` is the length of the input along the axis
specified by `axis`.
axis : int, optional
Axis over which to compute the inverse FFT. If not given, the last
axis is used.
norm : {None, "ortho"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is None.
Returns
-------
out : ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
The length of the transformed axis is `n`, or, if `n` is not given,
``2*(m-1)`` where ``m`` is the length of the transformed axis of the
input. To get an odd number of output points, `n` must be specified.
Raises
------
IndexError
If `axis` is larger than the last axis of `a`.
See Also
--------
numpy.fft : For definition of the DFT and conventions used.
rfft : The one-dimensional FFT of real input, of which `irfft` is inverse.
fft : The one-dimensional FFT.
irfft2 : The inverse of the two-dimensional FFT of real input.
irfftn : The inverse of the *n*-dimensional FFT of real input.
Notes
-----
Returns the real valued `n`-point inverse discrete Fourier transform
of `a`, where `a` contains the non-negative frequency terms of a
Hermitian-symmetric sequence. `n` is the length of the result, not the
input.
If you specify an `n` such that `a` must be zero-padded or truncated, the
extra/removed values will be added/removed at high frequencies. One can
thus resample a series to `m` points via Fourier interpolation by:
``a_resamp = irfft(rfft(a), m)``.
The correct interpretation of the hermitian input depends on the length of
the original data, as given by `n`. This is because each input shape could
correspond to either an odd or even length signal. By default, `irfft`
assumes an even output length which puts the last entry at the Nyquist
frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,
the value is thus treated as purely real. To avoid losing information, the
correct length of the real input **must** be given.
Examples
--------
>>> np.fft.ifft([1, -1j, -1, 1j])
array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary
>>> np.fft.irfft([1, -1j, -1])
array([0., 1., 0., 0.])
Notice how the last term in the input to the ordinary `ifft` is the
complex conjugate of the second term, and the output has zero imaginary
part everywhere. When calling `irfft`, the negative frequencies are not
specified, and the output array is purely real.
"""
a = asarray(a)
if n is None:
n = (a.shape[axis] - 1) * 2
inv_norm = n
if norm is not None and _unitary(norm):
inv_norm = sqrt(n)
output = _raw_fft(a, n, axis, True, False, inv_norm)
return output | [
"def",
"irfft",
"(",
"a",
",",
"n",
"=",
"None",
",",
"axis",
"=",
"-",
"1",
",",
"norm",
"=",
"None",
")",
":",
"a",
"=",
"asarray",
"(",
"a",
")",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"(",
"a",
".",
"shape",
"[",
"axis",
"]",
"-",
"1",
")",
"*",
"2",
"inv_norm",
"=",
"n",
"if",
"norm",
"is",
"not",
"None",
"and",
"_unitary",
"(",
"norm",
")",
":",
"inv_norm",
"=",
"sqrt",
"(",
"n",
")",
"output",
"=",
"_raw_fft",
"(",
"a",
",",
"n",
",",
"axis",
",",
"True",
",",
"False",
",",
"inv_norm",
")",
"return",
"output"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/fft/_pocketfft.py#L379-L475 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CalculateMonteCarloAbsorption.py | python | CalculateMonteCarloAbsorption._convert_from_wavelength | (self, workspace) | Converts the specified workspace into units of wavelength.
:param workspace: The workspace whose units to convert.
:return: A workspace with units of wavelength, created from
converting the specified workspace. | Converts the specified workspace into units of wavelength. | [
"Converts",
"the",
"specified",
"workspace",
"into",
"units",
"of",
"wavelength",
"."
] | def _convert_from_wavelength(self, workspace):
"""
Converts the specified workspace into units of wavelength.
:param workspace: The workspace whose units to convert.
:return: A workspace with units of wavelength, created from
converting the specified workspace.
"""
if self._transposed:
workspace = self._tranpose_ws(workspace)
if self._sample_unit == 'Label' and not self._isis_instrument:
# This happens for E/I Fixed Window Scans for IN16B at ILL
# In this case we want to keep the correction workspace in wavelength and the vertical axis as in the input
return workspace
elif self._indirect_elastic:
return self._convert_units(workspace, "MomentumTransfer", self._emode, self._efixed)
elif self._emode == "Indirect":
return self._convert_units(workspace, self._sample_unit, self._emode, self._efixed)
elif self._sample_unit != 'Wavelength':
return self._convert_units(workspace, self._sample_unit, self._emode)
else:
return workspace | [
"def",
"_convert_from_wavelength",
"(",
"self",
",",
"workspace",
")",
":",
"if",
"self",
".",
"_transposed",
":",
"workspace",
"=",
"self",
".",
"_tranpose_ws",
"(",
"workspace",
")",
"if",
"self",
".",
"_sample_unit",
"==",
"'Label'",
"and",
"not",
"self",
".",
"_isis_instrument",
":",
"# This happens for E/I Fixed Window Scans for IN16B at ILL",
"# In this case we want to keep the correction workspace in wavelength and the vertical axis as in the input",
"return",
"workspace",
"elif",
"self",
".",
"_indirect_elastic",
":",
"return",
"self",
".",
"_convert_units",
"(",
"workspace",
",",
"\"MomentumTransfer\"",
",",
"self",
".",
"_emode",
",",
"self",
".",
"_efixed",
")",
"elif",
"self",
".",
"_emode",
"==",
"\"Indirect\"",
":",
"return",
"self",
".",
"_convert_units",
"(",
"workspace",
",",
"self",
".",
"_sample_unit",
",",
"self",
".",
"_emode",
",",
"self",
".",
"_efixed",
")",
"elif",
"self",
".",
"_sample_unit",
"!=",
"'Wavelength'",
":",
"return",
"self",
".",
"_convert_units",
"(",
"workspace",
",",
"self",
".",
"_sample_unit",
",",
"self",
".",
"_emode",
")",
"else",
":",
"return",
"workspace"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CalculateMonteCarloAbsorption.py#L608-L631 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/utils.py | python | contextfunction | (f) | return f | This decorator can be used to mark a function or method context callable.
A context callable is passed the active :class:`Context` as first argument when
called from the template. This is useful if a function wants to get access
to the context or functions provided on the context object. For example
a function that returns a sorted list of template variables the current
template exports could look like this::
@contextfunction
def get_exported_names(context):
return sorted(context.exported_vars) | This decorator can be used to mark a function or method context callable.
A context callable is passed the active :class:`Context` as first argument when
called from the template. This is useful if a function wants to get access
to the context or functions provided on the context object. For example
a function that returns a sorted list of template variables the current
template exports could look like this:: | [
"This",
"decorator",
"can",
"be",
"used",
"to",
"mark",
"a",
"function",
"or",
"method",
"context",
"callable",
".",
"A",
"context",
"callable",
"is",
"passed",
"the",
"active",
":",
"class",
":",
"Context",
"as",
"first",
"argument",
"when",
"called",
"from",
"the",
"template",
".",
"This",
"is",
"useful",
"if",
"a",
"function",
"wants",
"to",
"get",
"access",
"to",
"the",
"context",
"or",
"functions",
"provided",
"on",
"the",
"context",
"object",
".",
"For",
"example",
"a",
"function",
"that",
"returns",
"a",
"sorted",
"list",
"of",
"template",
"variables",
"the",
"current",
"template",
"exports",
"could",
"look",
"like",
"this",
"::"
] | def contextfunction(f):
"""This decorator can be used to mark a function or method context callable.
A context callable is passed the active :class:`Context` as first argument when
called from the template. This is useful if a function wants to get access
to the context or functions provided on the context object. For example
a function that returns a sorted list of template variables the current
template exports could look like this::
@contextfunction
def get_exported_names(context):
return sorted(context.exported_vars)
"""
f.contextfunction = True
return f | [
"def",
"contextfunction",
"(",
"f",
")",
":",
"f",
".",
"contextfunction",
"=",
"True",
"return",
"f"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/utils.py#L40-L53 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | contrib/src/sceneeditor/seManipulation.py | python | DirectManipulationControl.plantSelectedNodePath | (self) | Move selected object to intersection point of cursor on scene | Move selected object to intersection point of cursor on scene | [
"Move",
"selected",
"object",
"to",
"intersection",
"point",
"of",
"cursor",
"on",
"scene"
] | def plantSelectedNodePath(self):
""" Move selected object to intersection point of cursor on scene """
# Check for intersection
entry = SEditor.iRay.pickGeom(
skipFlags = SKIP_HIDDEN | SKIP_BACKFACE | SKIP_CAMERA)
# MRM: Need to handle moving COA
if (entry != None) and (SEditor.selected.last != None):
# Record undo point
SEditor.pushUndo(SEditor.selected)
# Record wrt matrix
SEditor.selected.getWrtAll()
# Move selected
SEditor.widget.setPos(
SEditor.camera,entry.getSurfacePoint(entry.getFromNodePath()))
# Move all the selected objects with widget
# Move the objects with the widget
SEditor.selected.moveWrtWidgetAll()
# Let everyone know that something was moved
messenger.send('DIRECT_manipulateObjectCleanup') | [
"def",
"plantSelectedNodePath",
"(",
"self",
")",
":",
"# Check for intersection",
"entry",
"=",
"SEditor",
".",
"iRay",
".",
"pickGeom",
"(",
"skipFlags",
"=",
"SKIP_HIDDEN",
"|",
"SKIP_BACKFACE",
"|",
"SKIP_CAMERA",
")",
"# MRM: Need to handle moving COA",
"if",
"(",
"entry",
"!=",
"None",
")",
"and",
"(",
"SEditor",
".",
"selected",
".",
"last",
"!=",
"None",
")",
":",
"# Record undo point",
"SEditor",
".",
"pushUndo",
"(",
"SEditor",
".",
"selected",
")",
"# Record wrt matrix",
"SEditor",
".",
"selected",
".",
"getWrtAll",
"(",
")",
"# Move selected",
"SEditor",
".",
"widget",
".",
"setPos",
"(",
"SEditor",
".",
"camera",
",",
"entry",
".",
"getSurfacePoint",
"(",
"entry",
".",
"getFromNodePath",
"(",
")",
")",
")",
"# Move all the selected objects with widget",
"# Move the objects with the widget",
"SEditor",
".",
"selected",
".",
"moveWrtWidgetAll",
"(",
")",
"# Let everyone know that something was moved",
"messenger",
".",
"send",
"(",
"'DIRECT_manipulateObjectCleanup'",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/contrib/src/sceneeditor/seManipulation.py#L490-L508 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/examples/speech_commands/freeze.py | python | create_inference_graph | (wanted_words, sample_rate, clip_duration_ms,
clip_stride_ms, window_size_ms, window_stride_ms,
feature_bin_count, model_architecture, preprocess) | return reshaped_input, softmax | Creates an audio model with the nodes needed for inference.
Uses the supplied arguments to create a model, and inserts the input and
output nodes that are needed to use the graph for inference.
Args:
wanted_words: Comma-separated list of the words we're trying to recognize.
sample_rate: How many samples per second are in the input audio files.
clip_duration_ms: How many samples to analyze for the audio pattern.
clip_stride_ms: How often to run recognition. Useful for models with cache.
window_size_ms: Time slice duration to estimate frequencies from.
window_stride_ms: How far apart time slices should be.
feature_bin_count: Number of frequency bands to analyze.
model_architecture: Name of the kind of model to generate.
preprocess: How the spectrogram is processed to produce features, for
example 'mfcc', 'average', or 'micro'.
Returns:
Input and output tensor objects.
Raises:
Exception: If the preprocessing mode isn't recognized. | Creates an audio model with the nodes needed for inference. | [
"Creates",
"an",
"audio",
"model",
"with",
"the",
"nodes",
"needed",
"for",
"inference",
"."
] | def create_inference_graph(wanted_words, sample_rate, clip_duration_ms,
clip_stride_ms, window_size_ms, window_stride_ms,
feature_bin_count, model_architecture, preprocess):
"""Creates an audio model with the nodes needed for inference.
Uses the supplied arguments to create a model, and inserts the input and
output nodes that are needed to use the graph for inference.
Args:
wanted_words: Comma-separated list of the words we're trying to recognize.
sample_rate: How many samples per second are in the input audio files.
clip_duration_ms: How many samples to analyze for the audio pattern.
clip_stride_ms: How often to run recognition. Useful for models with cache.
window_size_ms: Time slice duration to estimate frequencies from.
window_stride_ms: How far apart time slices should be.
feature_bin_count: Number of frequency bands to analyze.
model_architecture: Name of the kind of model to generate.
preprocess: How the spectrogram is processed to produce features, for
example 'mfcc', 'average', or 'micro'.
Returns:
Input and output tensor objects.
Raises:
Exception: If the preprocessing mode isn't recognized.
"""
words_list = input_data.prepare_words_list(wanted_words.split(','))
model_settings = models.prepare_model_settings(
len(words_list), sample_rate, clip_duration_ms, window_size_ms,
window_stride_ms, feature_bin_count, preprocess)
runtime_settings = {'clip_stride_ms': clip_stride_ms}
wav_data_placeholder = tf.compat.v1.placeholder(tf.string, [],
name='wav_data')
decoded_sample_data = tf.audio.decode_wav(
wav_data_placeholder,
desired_channels=1,
desired_samples=model_settings['desired_samples'],
name='decoded_sample_data')
spectrogram = audio_ops.audio_spectrogram(
decoded_sample_data.audio,
window_size=model_settings['window_size_samples'],
stride=model_settings['window_stride_samples'],
magnitude_squared=True)
if preprocess == 'average':
fingerprint_input = tf.nn.pool(
input=tf.expand_dims(spectrogram, -1),
window_shape=[1, model_settings['average_window_width']],
strides=[1, model_settings['average_window_width']],
pooling_type='AVG',
padding='SAME')
elif preprocess == 'mfcc':
fingerprint_input = audio_ops.mfcc(
spectrogram,
sample_rate,
dct_coefficient_count=model_settings['fingerprint_width'])
elif preprocess == 'micro':
if not frontend_op:
raise Exception(
'Micro frontend op is currently not available when running TensorFlow'
' directly from Python, you need to build and run through Bazel, for'
' example'
' `bazel run tensorflow/examples/speech_commands:freeze_graph`')
sample_rate = model_settings['sample_rate']
window_size_ms = (model_settings['window_size_samples'] *
1000) / sample_rate
window_step_ms = (model_settings['window_stride_samples'] *
1000) / sample_rate
int16_input = tf.cast(
tf.multiply(decoded_sample_data.audio, 32767), tf.int16)
micro_frontend = frontend_op.audio_microfrontend(
int16_input,
sample_rate=sample_rate,
window_size=window_size_ms,
window_step=window_step_ms,
num_channels=model_settings['fingerprint_width'],
out_scale=1,
out_type=tf.float32)
fingerprint_input = tf.multiply(micro_frontend, (10.0 / 256.0))
else:
raise Exception('Unknown preprocess mode "%s" (should be "mfcc",'
' "average", or "micro")' % (preprocess))
fingerprint_size = model_settings['fingerprint_size']
reshaped_input = tf.reshape(fingerprint_input, [-1, fingerprint_size])
logits = models.create_model(
reshaped_input, model_settings, model_architecture, is_training=False,
runtime_settings=runtime_settings)
# Create an output to use for inference.
softmax = tf.nn.softmax(logits, name='labels_softmax')
return reshaped_input, softmax | [
"def",
"create_inference_graph",
"(",
"wanted_words",
",",
"sample_rate",
",",
"clip_duration_ms",
",",
"clip_stride_ms",
",",
"window_size_ms",
",",
"window_stride_ms",
",",
"feature_bin_count",
",",
"model_architecture",
",",
"preprocess",
")",
":",
"words_list",
"=",
"input_data",
".",
"prepare_words_list",
"(",
"wanted_words",
".",
"split",
"(",
"','",
")",
")",
"model_settings",
"=",
"models",
".",
"prepare_model_settings",
"(",
"len",
"(",
"words_list",
")",
",",
"sample_rate",
",",
"clip_duration_ms",
",",
"window_size_ms",
",",
"window_stride_ms",
",",
"feature_bin_count",
",",
"preprocess",
")",
"runtime_settings",
"=",
"{",
"'clip_stride_ms'",
":",
"clip_stride_ms",
"}",
"wav_data_placeholder",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"placeholder",
"(",
"tf",
".",
"string",
",",
"[",
"]",
",",
"name",
"=",
"'wav_data'",
")",
"decoded_sample_data",
"=",
"tf",
".",
"audio",
".",
"decode_wav",
"(",
"wav_data_placeholder",
",",
"desired_channels",
"=",
"1",
",",
"desired_samples",
"=",
"model_settings",
"[",
"'desired_samples'",
"]",
",",
"name",
"=",
"'decoded_sample_data'",
")",
"spectrogram",
"=",
"audio_ops",
".",
"audio_spectrogram",
"(",
"decoded_sample_data",
".",
"audio",
",",
"window_size",
"=",
"model_settings",
"[",
"'window_size_samples'",
"]",
",",
"stride",
"=",
"model_settings",
"[",
"'window_stride_samples'",
"]",
",",
"magnitude_squared",
"=",
"True",
")",
"if",
"preprocess",
"==",
"'average'",
":",
"fingerprint_input",
"=",
"tf",
".",
"nn",
".",
"pool",
"(",
"input",
"=",
"tf",
".",
"expand_dims",
"(",
"spectrogram",
",",
"-",
"1",
")",
",",
"window_shape",
"=",
"[",
"1",
",",
"model_settings",
"[",
"'average_window_width'",
"]",
"]",
",",
"strides",
"=",
"[",
"1",
",",
"model_settings",
"[",
"'average_window_width'",
"]",
"]",
",",
"pooling_type",
"=",
"'AVG'",
",",
"padding",
"=",
"'SAME'",
")",
"elif",
"preprocess",
"==",
"'mfcc'",
":",
"fingerprint_input",
"=",
"audio_ops",
".",
"mfcc",
"(",
"spectrogram",
",",
"sample_rate",
",",
"dct_coefficient_count",
"=",
"model_settings",
"[",
"'fingerprint_width'",
"]",
")",
"elif",
"preprocess",
"==",
"'micro'",
":",
"if",
"not",
"frontend_op",
":",
"raise",
"Exception",
"(",
"'Micro frontend op is currently not available when running TensorFlow'",
"' directly from Python, you need to build and run through Bazel, for'",
"' example'",
"' `bazel run tensorflow/examples/speech_commands:freeze_graph`'",
")",
"sample_rate",
"=",
"model_settings",
"[",
"'sample_rate'",
"]",
"window_size_ms",
"=",
"(",
"model_settings",
"[",
"'window_size_samples'",
"]",
"*",
"1000",
")",
"/",
"sample_rate",
"window_step_ms",
"=",
"(",
"model_settings",
"[",
"'window_stride_samples'",
"]",
"*",
"1000",
")",
"/",
"sample_rate",
"int16_input",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"multiply",
"(",
"decoded_sample_data",
".",
"audio",
",",
"32767",
")",
",",
"tf",
".",
"int16",
")",
"micro_frontend",
"=",
"frontend_op",
".",
"audio_microfrontend",
"(",
"int16_input",
",",
"sample_rate",
"=",
"sample_rate",
",",
"window_size",
"=",
"window_size_ms",
",",
"window_step",
"=",
"window_step_ms",
",",
"num_channels",
"=",
"model_settings",
"[",
"'fingerprint_width'",
"]",
",",
"out_scale",
"=",
"1",
",",
"out_type",
"=",
"tf",
".",
"float32",
")",
"fingerprint_input",
"=",
"tf",
".",
"multiply",
"(",
"micro_frontend",
",",
"(",
"10.0",
"/",
"256.0",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Unknown preprocess mode \"%s\" (should be \"mfcc\",'",
"' \"average\", or \"micro\")'",
"%",
"(",
"preprocess",
")",
")",
"fingerprint_size",
"=",
"model_settings",
"[",
"'fingerprint_size'",
"]",
"reshaped_input",
"=",
"tf",
".",
"reshape",
"(",
"fingerprint_input",
",",
"[",
"-",
"1",
",",
"fingerprint_size",
"]",
")",
"logits",
"=",
"models",
".",
"create_model",
"(",
"reshaped_input",
",",
"model_settings",
",",
"model_architecture",
",",
"is_training",
"=",
"False",
",",
"runtime_settings",
"=",
"runtime_settings",
")",
"# Create an output to use for inference.",
"softmax",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"logits",
",",
"name",
"=",
"'labels_softmax'",
")",
"return",
"reshaped_input",
",",
"softmax"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/examples/speech_commands/freeze.py#L59-L154 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | ThirdParty/cinema/paraview/tpl/cinema_python/database/raster_wrangler.py | python | RasterWrangler.valuewriter | (self, imageSlice, fname, vrange) | Takes in either a (1C) float or a RGB (3C) buffer and writes it as
an image file. | Takes in either a (1C) float or a RGB (3C) buffer and writes it as
an image file. | [
"Takes",
"in",
"either",
"a",
"(",
"1C",
")",
"float",
"or",
"a",
"RGB",
"(",
"3C",
")",
"buffer",
"and",
"writes",
"it",
"as",
"an",
"image",
"file",
"."
] | def valuewriter(self, imageSlice, fname, vrange):
""" Takes in either a (1C) float or a RGB (3C) buffer and writes it as
an image file."""
# Adjust the filename, replace png with .im
baseName, ext = os.path.splitext(fname)
adjustedName = baseName + self.floatExtension()
dimensions = imageSlice.shape
if len(dimensions) == 2 and imageSlice.dtype == numpy.float32:
# Given as single channel floating point buffer.
return self.zwriter(imageSlice, adjustedName)
elif (len(dimensions) > 2) and (dimensions[2] == 3):
# if self.dontConvertValsToFloat
# self.rgbwriter(imageSlice, fname)
# return
# Given an RGB buffer
# Convert it to a floating point buffer for consistency
# TODO: just one copy of this code in cinema
w0 = numpy.left_shift(imageSlice[:, :, 0].astype(numpy.uint32), 16)
w1 = numpy.left_shift(imageSlice[:, :, 1].astype(numpy.uint32), 8)
w2 = imageSlice[:, :, 2].astype(numpy.uint32)
value = numpy.bitwise_or(w0, w1)
value = numpy.bitwise_or(value, w2)
value = numpy.subtract(value, 1)
value = value.astype(numpy.float32)
adjusted_val = numpy.divide(value, float(0xFFFFFE))
return self.zwriter(adjusted_val, adjustedName)
else:
raise ValueError("Invalid dimensions for a value raster.") | [
"def",
"valuewriter",
"(",
"self",
",",
"imageSlice",
",",
"fname",
",",
"vrange",
")",
":",
"# Adjust the filename, replace png with .im",
"baseName",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"adjustedName",
"=",
"baseName",
"+",
"self",
".",
"floatExtension",
"(",
")",
"dimensions",
"=",
"imageSlice",
".",
"shape",
"if",
"len",
"(",
"dimensions",
")",
"==",
"2",
"and",
"imageSlice",
".",
"dtype",
"==",
"numpy",
".",
"float32",
":",
"# Given as single channel floating point buffer.",
"return",
"self",
".",
"zwriter",
"(",
"imageSlice",
",",
"adjustedName",
")",
"elif",
"(",
"len",
"(",
"dimensions",
")",
">",
"2",
")",
"and",
"(",
"dimensions",
"[",
"2",
"]",
"==",
"3",
")",
":",
"# if self.dontConvertValsToFloat",
"# self.rgbwriter(imageSlice, fname)",
"# return",
"# Given an RGB buffer",
"# Convert it to a floating point buffer for consistency",
"# TODO: just one copy of this code in cinema",
"w0",
"=",
"numpy",
".",
"left_shift",
"(",
"imageSlice",
"[",
":",
",",
":",
",",
"0",
"]",
".",
"astype",
"(",
"numpy",
".",
"uint32",
")",
",",
"16",
")",
"w1",
"=",
"numpy",
".",
"left_shift",
"(",
"imageSlice",
"[",
":",
",",
":",
",",
"1",
"]",
".",
"astype",
"(",
"numpy",
".",
"uint32",
")",
",",
"8",
")",
"w2",
"=",
"imageSlice",
"[",
":",
",",
":",
",",
"2",
"]",
".",
"astype",
"(",
"numpy",
".",
"uint32",
")",
"value",
"=",
"numpy",
".",
"bitwise_or",
"(",
"w0",
",",
"w1",
")",
"value",
"=",
"numpy",
".",
"bitwise_or",
"(",
"value",
",",
"w2",
")",
"value",
"=",
"numpy",
".",
"subtract",
"(",
"value",
",",
"1",
")",
"value",
"=",
"value",
".",
"astype",
"(",
"numpy",
".",
"float32",
")",
"adjusted_val",
"=",
"numpy",
".",
"divide",
"(",
"value",
",",
"float",
"(",
"0xFFFFFE",
")",
")",
"return",
"self",
".",
"zwriter",
"(",
"adjusted_val",
",",
"adjustedName",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid dimensions for a value raster.\"",
")"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/raster_wrangler.py#L239-L272 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Alignment/MillePedeAlignmentAlgorithm/scripts/mps_alisetup.py | python | SetupAlignment._fetch_defaults | (self) | Fetch default general options from config file. | Fetch default general options from config file. | [
"Fetch",
"default",
"general",
"options",
"from",
"config",
"file",
"."
] | def _fetch_defaults(self):
"""Fetch default general options from config file."""
for var in ("globaltag", "configTemplate", "json", "massStorageDir",
"testMode"):
try:
self._general_options[var] = self._config.get("general", var)
except ConfigParser.NoOptionError:
if var == "testMode": continue
print("No '" + var + "' given in [general] section.")
for dataset in self._external_datasets.values():
dataset["general"] = {}
for var in ("globaltag", "configTemplate", "json"):
try:
dataset["general"][var] = dataset["config"].get("general", var)
except (ConfigParser.NoSectionError,ConfigParser.NoOptionError):
pass | [
"def",
"_fetch_defaults",
"(",
"self",
")",
":",
"for",
"var",
"in",
"(",
"\"globaltag\"",
",",
"\"configTemplate\"",
",",
"\"json\"",
",",
"\"massStorageDir\"",
",",
"\"testMode\"",
")",
":",
"try",
":",
"self",
".",
"_general_options",
"[",
"var",
"]",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"\"general\"",
",",
"var",
")",
"except",
"ConfigParser",
".",
"NoOptionError",
":",
"if",
"var",
"==",
"\"testMode\"",
":",
"continue",
"print",
"(",
"\"No '\"",
"+",
"var",
"+",
"\"' given in [general] section.\"",
")",
"for",
"dataset",
"in",
"self",
".",
"_external_datasets",
".",
"values",
"(",
")",
":",
"dataset",
"[",
"\"general\"",
"]",
"=",
"{",
"}",
"for",
"var",
"in",
"(",
"\"globaltag\"",
",",
"\"configTemplate\"",
",",
"\"json\"",
")",
":",
"try",
":",
"dataset",
"[",
"\"general\"",
"]",
"[",
"var",
"]",
"=",
"dataset",
"[",
"\"config\"",
"]",
".",
"get",
"(",
"\"general\"",
",",
"var",
")",
"except",
"(",
"ConfigParser",
".",
"NoSectionError",
",",
"ConfigParser",
".",
"NoOptionError",
")",
":",
"pass"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_alisetup.py#L671-L688 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/feature_selection/_base.py | python | SelectorMixin.transform | (self, X) | return X[:, safe_mask(X, mask)] | Reduce X to the selected features.
Parameters
----------
X : array of shape [n_samples, n_features]
The input samples.
Returns
-------
X_r : array of shape [n_samples, n_selected_features]
The input samples with only the selected features. | Reduce X to the selected features. | [
"Reduce",
"X",
"to",
"the",
"selected",
"features",
"."
] | def transform(self, X):
"""Reduce X to the selected features.
Parameters
----------
X : array of shape [n_samples, n_features]
The input samples.
Returns
-------
X_r : array of shape [n_samples, n_selected_features]
The input samples with only the selected features.
"""
tags = self._get_tags()
X = check_array(X, dtype=None, accept_sparse='csr',
force_all_finite=not tags.get('allow_nan', True))
mask = self.get_support()
if not mask.any():
warn("No features were selected: either the data is"
" too noisy or the selection test too strict.",
UserWarning)
return np.empty(0).reshape((X.shape[0], 0))
if len(mask) != X.shape[1]:
raise ValueError("X has a different shape than during fitting.")
return X[:, safe_mask(X, mask)] | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"tags",
"=",
"self",
".",
"_get_tags",
"(",
")",
"X",
"=",
"check_array",
"(",
"X",
",",
"dtype",
"=",
"None",
",",
"accept_sparse",
"=",
"'csr'",
",",
"force_all_finite",
"=",
"not",
"tags",
".",
"get",
"(",
"'allow_nan'",
",",
"True",
")",
")",
"mask",
"=",
"self",
".",
"get_support",
"(",
")",
"if",
"not",
"mask",
".",
"any",
"(",
")",
":",
"warn",
"(",
"\"No features were selected: either the data is\"",
"\" too noisy or the selection test too strict.\"",
",",
"UserWarning",
")",
"return",
"np",
".",
"empty",
"(",
"0",
")",
".",
"reshape",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"0",
")",
")",
"if",
"len",
"(",
"mask",
")",
"!=",
"X",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"X has a different shape than during fitting.\"",
")",
"return",
"X",
"[",
":",
",",
"safe_mask",
"(",
"X",
",",
"mask",
")",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_selection/_base.py#L61-L85 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/multiarray.py | python | positive | (x, out=None, **kwargs) | return _mx_nd_np.positive(x, out=out) | r"""
Computes the numerical positive of each element `x_i` (i.e.,`y_i = +x_i`)
of the input array x .
Parameters
----------
x : ndarray or scalar
Input array.
Returns
-------
y : ndarray or scalar
Returned array or scalar: y = +x. This is a scalar if x is a scalar.
Notes
-----
Equivalent to `x.copy()`, but only defined for types that support arithmetic.
Examples
--------
>>> x1 = np.array(([1., -1.]))
>>> np.positive(x1)
array([ 1., -1.])
>>> +x1
array([ 1., -1.]) | r"""
Computes the numerical positive of each element `x_i` (i.e.,`y_i = +x_i`)
of the input array x . | [
"r",
"Computes",
"the",
"numerical",
"positive",
"of",
"each",
"element",
"x_i",
"(",
"i",
".",
"e",
".",
"y_i",
"=",
"+",
"x_i",
")",
"of",
"the",
"input",
"array",
"x",
"."
] | def positive(x, out=None, **kwargs):
r"""
Computes the numerical positive of each element `x_i` (i.e.,`y_i = +x_i`)
of the input array x .
Parameters
----------
x : ndarray or scalar
Input array.
Returns
-------
y : ndarray or scalar
Returned array or scalar: y = +x. This is a scalar if x is a scalar.
Notes
-----
Equivalent to `x.copy()`, but only defined for types that support arithmetic.
Examples
--------
>>> x1 = np.array(([1., -1.]))
>>> np.positive(x1)
array([ 1., -1.])
>>> +x1
array([ 1., -1.])
"""
return _mx_nd_np.positive(x, out=out) | [
"def",
"positive",
"(",
"x",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_mx_nd_np",
".",
"positive",
"(",
"x",
",",
"out",
"=",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L5284-L5311 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Environment.py | python | _delete_duplicates | (l, keep_last) | return result | Delete duplicates from a sequence, keeping the first or last. | Delete duplicates from a sequence, keeping the first or last. | [
"Delete",
"duplicates",
"from",
"a",
"sequence",
"keeping",
"the",
"first",
"or",
"last",
"."
] | def _delete_duplicates(l, keep_last):
"""Delete duplicates from a sequence, keeping the first or last."""
seen=set()
result=[]
if keep_last: # reverse in & out, then keep first
l.reverse()
for i in l:
try:
if i not in seen:
result.append(i)
seen.add(i)
except TypeError:
# probably unhashable. Just keep it.
result.append(i)
if keep_last:
result.reverse()
return result | [
"def",
"_delete_duplicates",
"(",
"l",
",",
"keep_last",
")",
":",
"seen",
"=",
"set",
"(",
")",
"result",
"=",
"[",
"]",
"if",
"keep_last",
":",
"# reverse in & out, then keep first",
"l",
".",
"reverse",
"(",
")",
"for",
"i",
"in",
"l",
":",
"try",
":",
"if",
"i",
"not",
"in",
"seen",
":",
"result",
".",
"append",
"(",
"i",
")",
"seen",
".",
"add",
"(",
"i",
")",
"except",
"TypeError",
":",
"# probably unhashable. Just keep it.",
"result",
".",
"append",
"(",
"i",
")",
"if",
"keep_last",
":",
"result",
".",
"reverse",
"(",
")",
"return",
"result"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Environment.py#L177-L193 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/bindings/python/clang/cindex.py | python | CompileCommand.filename | (self) | return conf.lib.clang_CompileCommand_getFilename(self.cmd) | Get the working filename for this CompileCommand | Get the working filename for this CompileCommand | [
"Get",
"the",
"working",
"filename",
"for",
"this",
"CompileCommand"
] | def filename(self):
"""Get the working filename for this CompileCommand"""
return conf.lib.clang_CompileCommand_getFilename(self.cmd) | [
"def",
"filename",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CompileCommand_getFilename",
"(",
"self",
".",
"cmd",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/bindings/python/clang/cindex.py#L3178-L3180 | |
apple/swift-clang | d7403439fc6641751840b723e7165fb02f52db95 | tools/scan-build-py/libscanbuild/arguments.py | python | create_analyze_parser | (from_build_command) | return parser | Creates a parser for command-line arguments to 'analyze'. | Creates a parser for command-line arguments to 'analyze'. | [
"Creates",
"a",
"parser",
"for",
"command",
"-",
"line",
"arguments",
"to",
"analyze",
"."
] | def create_analyze_parser(from_build_command):
""" Creates a parser for command-line arguments to 'analyze'. """
parser = create_default_parser()
if from_build_command:
parser_add_prefer_wrapper(parser)
parser_add_compilers(parser)
parser.add_argument(
'--intercept-first',
action='store_true',
help="""Run the build commands first, intercept compiler
calls and then run the static analyzer afterwards.
Generally speaking it has better coverage on build commands.
With '--override-compiler' it use compiler wrapper, but does
not run the analyzer till the build is finished.""")
else:
parser_add_cdb(parser)
parser.add_argument(
'--status-bugs',
action='store_true',
help="""The exit status of '%(prog)s' is the same as the executed
build command. This option ignores the build exit status and sets to
be non zero if it found potential bugs or zero otherwise.""")
parser.add_argument(
'--exclude',
metavar='<directory>',
dest='excludes',
action='append',
default=[],
help="""Do not run static analyzer against files found in this
directory. (You can specify this option multiple times.)
Could be useful when project contains 3rd party libraries.""")
output = parser.add_argument_group('output control options')
output.add_argument(
'--output',
'-o',
metavar='<path>',
default=tempfile.gettempdir(),
help="""Specifies the output directory for analyzer reports.
Subdirectory will be created if default directory is targeted.""")
output.add_argument(
'--keep-empty',
action='store_true',
help="""Don't remove the build results directory even if no issues
were reported.""")
output.add_argument(
'--html-title',
metavar='<title>',
help="""Specify the title used on generated HTML pages.
If not specified, a default title will be used.""")
format_group = output.add_mutually_exclusive_group()
format_group.add_argument(
'--plist',
'-plist',
dest='output_format',
const='plist',
default='html',
action='store_const',
help="""Cause the results as a set of .plist files.""")
format_group.add_argument(
'--plist-html',
'-plist-html',
dest='output_format',
const='plist-html',
default='html',
action='store_const',
help="""Cause the results as a set of .html and .plist files.""")
format_group.add_argument(
'--plist-multi-file',
'-plist-multi-file',
dest='output_format',
const='plist-multi-file',
default='html',
action='store_const',
help="""Cause the results as a set of .plist files with extra
information on related files.""")
advanced = parser.add_argument_group('advanced options')
advanced.add_argument(
'--use-analyzer',
metavar='<path>',
dest='clang',
default='clang',
help="""'%(prog)s' uses the 'clang' executable relative to itself for
static analysis. One can override this behavior with this option by
using the 'clang' packaged with Xcode (on OS X) or from the PATH.""")
advanced.add_argument(
'--no-failure-reports',
'-no-failure-reports',
dest='output_failures',
action='store_false',
help="""Do not create a 'failures' subdirectory that includes analyzer
crash reports and preprocessed source files.""")
parser.add_argument(
'--analyze-headers',
action='store_true',
help="""Also analyze functions in #included files. By default, such
functions are skipped unless they are called by functions within the
main source file.""")
advanced.add_argument(
'--stats',
'-stats',
action='store_true',
help="""Generates visitation statistics for the project.""")
advanced.add_argument(
'--internal-stats',
action='store_true',
help="""Generate internal analyzer statistics.""")
advanced.add_argument(
'--maxloop',
'-maxloop',
metavar='<loop count>',
type=int,
help="""Specify the number of times a block can be visited before
giving up. Increase for more comprehensive coverage at a cost of
speed.""")
advanced.add_argument(
'--store',
'-store',
metavar='<model>',
dest='store_model',
choices=['region', 'basic'],
help="""Specify the store model used by the analyzer. 'region'
specifies a field- sensitive store model. 'basic' which is far less
precise but can more quickly analyze code. 'basic' was the default
store model for checker-0.221 and earlier.""")
advanced.add_argument(
'--constraints',
'-constraints',
metavar='<model>',
dest='constraints_model',
choices=['range', 'basic'],
help="""Specify the constraint engine used by the analyzer. Specifying
'basic' uses a simpler, less powerful constraint model used by
checker-0.160 and earlier.""")
advanced.add_argument(
'--analyzer-config',
'-analyzer-config',
metavar='<options>',
help="""Provide options to pass through to the analyzer's
-analyzer-config flag. Several options are separated with comma:
'key1=val1,key2=val2'
Available options:
stable-report-filename=true or false (default)
Switch the page naming to:
report-<filename>-<function/method name>-<id>.html
instead of report-XXXXXX.html""")
advanced.add_argument(
'--force-analyze-debug-code',
dest='force_debug',
action='store_true',
help="""Tells analyzer to enable assertions in code even if they were
disabled during compilation, enabling more precise results.""")
plugins = parser.add_argument_group('checker options')
plugins.add_argument(
'--load-plugin',
'-load-plugin',
metavar='<plugin library>',
dest='plugins',
action='append',
help="""Loading external checkers using the clang plugin interface.""")
plugins.add_argument(
'--enable-checker',
'-enable-checker',
metavar='<checker name>',
action=AppendCommaSeparated,
help="""Enable specific checker.""")
plugins.add_argument(
'--disable-checker',
'-disable-checker',
metavar='<checker name>',
action=AppendCommaSeparated,
help="""Disable specific checker.""")
plugins.add_argument(
'--help-checkers',
action='store_true',
help="""A default group of checkers is run unless explicitly disabled.
Exactly which checkers constitute the default group is a function of
the operating system in use. These can be printed with this flag.""")
plugins.add_argument(
'--help-checkers-verbose',
action='store_true',
help="""Print all available checkers and mark the enabled ones.""")
if from_build_command:
parser.add_argument(
dest='build', nargs=argparse.REMAINDER, help="""Command to run.""")
else:
ctu = parser.add_argument_group('cross translation unit analysis')
ctu_mutex_group = ctu.add_mutually_exclusive_group()
ctu_mutex_group.add_argument(
'--ctu',
action='store_const',
const=CtuConfig(collect=True, analyze=True,
dir='', extdef_map_cmd=''),
dest='ctu_phases',
help="""Perform cross translation unit (ctu) analysis (both collect
and analyze phases) using default <ctu-dir> for temporary output.
At the end of the analysis, the temporary directory is removed.""")
ctu.add_argument(
'--ctu-dir',
metavar='<ctu-dir>',
dest='ctu_dir',
default='ctu-dir',
help="""Defines the temporary directory used between ctu
phases.""")
ctu_mutex_group.add_argument(
'--ctu-collect-only',
action='store_const',
const=CtuConfig(collect=True, analyze=False,
dir='', extdef_map_cmd=''),
dest='ctu_phases',
help="""Perform only the collect phase of ctu.
Keep <ctu-dir> for further use.""")
ctu_mutex_group.add_argument(
'--ctu-analyze-only',
action='store_const',
const=CtuConfig(collect=False, analyze=True,
dir='', extdef_map_cmd=''),
dest='ctu_phases',
help="""Perform only the analyze phase of ctu. <ctu-dir> should be
present and will not be removed after analysis.""")
ctu.add_argument(
'--use-extdef-map-cmd',
metavar='<path>',
dest='extdef_map_cmd',
default='clang-extdef-mapping',
help="""'%(prog)s' uses the 'clang-extdef-mapping' executable
relative to itself for generating external definition maps for
static analysis. One can override this behavior with this option
by using the 'clang-extdef-mapping' packaged with Xcode (on OS X)
or from the PATH.""")
return parser | [
"def",
"create_analyze_parser",
"(",
"from_build_command",
")",
":",
"parser",
"=",
"create_default_parser",
"(",
")",
"if",
"from_build_command",
":",
"parser_add_prefer_wrapper",
"(",
"parser",
")",
"parser_add_compilers",
"(",
"parser",
")",
"parser",
".",
"add_argument",
"(",
"'--intercept-first'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"Run the build commands first, intercept compiler\n calls and then run the static analyzer afterwards.\n Generally speaking it has better coverage on build commands.\n With '--override-compiler' it use compiler wrapper, but does\n not run the analyzer till the build is finished.\"\"\"",
")",
"else",
":",
"parser_add_cdb",
"(",
"parser",
")",
"parser",
".",
"add_argument",
"(",
"'--status-bugs'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"The exit status of '%(prog)s' is the same as the executed\n build command. This option ignores the build exit status and sets to\n be non zero if it found potential bugs or zero otherwise.\"\"\"",
")",
"parser",
".",
"add_argument",
"(",
"'--exclude'",
",",
"metavar",
"=",
"'<directory>'",
",",
"dest",
"=",
"'excludes'",
",",
"action",
"=",
"'append'",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"\"\"\"Do not run static analyzer against files found in this\n directory. (You can specify this option multiple times.)\n Could be useful when project contains 3rd party libraries.\"\"\"",
")",
"output",
"=",
"parser",
".",
"add_argument_group",
"(",
"'output control options'",
")",
"output",
".",
"add_argument",
"(",
"'--output'",
",",
"'-o'",
",",
"metavar",
"=",
"'<path>'",
",",
"default",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"help",
"=",
"\"\"\"Specifies the output directory for analyzer reports.\n Subdirectory will be created if default directory is targeted.\"\"\"",
")",
"output",
".",
"add_argument",
"(",
"'--keep-empty'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"Don't remove the build results directory even if no issues\n were reported.\"\"\"",
")",
"output",
".",
"add_argument",
"(",
"'--html-title'",
",",
"metavar",
"=",
"'<title>'",
",",
"help",
"=",
"\"\"\"Specify the title used on generated HTML pages.\n If not specified, a default title will be used.\"\"\"",
")",
"format_group",
"=",
"output",
".",
"add_mutually_exclusive_group",
"(",
")",
"format_group",
".",
"add_argument",
"(",
"'--plist'",
",",
"'-plist'",
",",
"dest",
"=",
"'output_format'",
",",
"const",
"=",
"'plist'",
",",
"default",
"=",
"'html'",
",",
"action",
"=",
"'store_const'",
",",
"help",
"=",
"\"\"\"Cause the results as a set of .plist files.\"\"\"",
")",
"format_group",
".",
"add_argument",
"(",
"'--plist-html'",
",",
"'-plist-html'",
",",
"dest",
"=",
"'output_format'",
",",
"const",
"=",
"'plist-html'",
",",
"default",
"=",
"'html'",
",",
"action",
"=",
"'store_const'",
",",
"help",
"=",
"\"\"\"Cause the results as a set of .html and .plist files.\"\"\"",
")",
"format_group",
".",
"add_argument",
"(",
"'--plist-multi-file'",
",",
"'-plist-multi-file'",
",",
"dest",
"=",
"'output_format'",
",",
"const",
"=",
"'plist-multi-file'",
",",
"default",
"=",
"'html'",
",",
"action",
"=",
"'store_const'",
",",
"help",
"=",
"\"\"\"Cause the results as a set of .plist files with extra\n information on related files.\"\"\"",
")",
"advanced",
"=",
"parser",
".",
"add_argument_group",
"(",
"'advanced options'",
")",
"advanced",
".",
"add_argument",
"(",
"'--use-analyzer'",
",",
"metavar",
"=",
"'<path>'",
",",
"dest",
"=",
"'clang'",
",",
"default",
"=",
"'clang'",
",",
"help",
"=",
"\"\"\"'%(prog)s' uses the 'clang' executable relative to itself for\n static analysis. One can override this behavior with this option by\n using the 'clang' packaged with Xcode (on OS X) or from the PATH.\"\"\"",
")",
"advanced",
".",
"add_argument",
"(",
"'--no-failure-reports'",
",",
"'-no-failure-reports'",
",",
"dest",
"=",
"'output_failures'",
",",
"action",
"=",
"'store_false'",
",",
"help",
"=",
"\"\"\"Do not create a 'failures' subdirectory that includes analyzer\n crash reports and preprocessed source files.\"\"\"",
")",
"parser",
".",
"add_argument",
"(",
"'--analyze-headers'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"Also analyze functions in #included files. By default, such\n functions are skipped unless they are called by functions within the\n main source file.\"\"\"",
")",
"advanced",
".",
"add_argument",
"(",
"'--stats'",
",",
"'-stats'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"Generates visitation statistics for the project.\"\"\"",
")",
"advanced",
".",
"add_argument",
"(",
"'--internal-stats'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"Generate internal analyzer statistics.\"\"\"",
")",
"advanced",
".",
"add_argument",
"(",
"'--maxloop'",
",",
"'-maxloop'",
",",
"metavar",
"=",
"'<loop count>'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"\"\"\"Specify the number of times a block can be visited before\n giving up. Increase for more comprehensive coverage at a cost of\n speed.\"\"\"",
")",
"advanced",
".",
"add_argument",
"(",
"'--store'",
",",
"'-store'",
",",
"metavar",
"=",
"'<model>'",
",",
"dest",
"=",
"'store_model'",
",",
"choices",
"=",
"[",
"'region'",
",",
"'basic'",
"]",
",",
"help",
"=",
"\"\"\"Specify the store model used by the analyzer. 'region'\n specifies a field- sensitive store model. 'basic' which is far less\n precise but can more quickly analyze code. 'basic' was the default\n store model for checker-0.221 and earlier.\"\"\"",
")",
"advanced",
".",
"add_argument",
"(",
"'--constraints'",
",",
"'-constraints'",
",",
"metavar",
"=",
"'<model>'",
",",
"dest",
"=",
"'constraints_model'",
",",
"choices",
"=",
"[",
"'range'",
",",
"'basic'",
"]",
",",
"help",
"=",
"\"\"\"Specify the constraint engine used by the analyzer. Specifying\n 'basic' uses a simpler, less powerful constraint model used by\n checker-0.160 and earlier.\"\"\"",
")",
"advanced",
".",
"add_argument",
"(",
"'--analyzer-config'",
",",
"'-analyzer-config'",
",",
"metavar",
"=",
"'<options>'",
",",
"help",
"=",
"\"\"\"Provide options to pass through to the analyzer's\n -analyzer-config flag. Several options are separated with comma:\n 'key1=val1,key2=val2'\n\n Available options:\n stable-report-filename=true or false (default)\n\n Switch the page naming to:\n report-<filename>-<function/method name>-<id>.html\n instead of report-XXXXXX.html\"\"\"",
")",
"advanced",
".",
"add_argument",
"(",
"'--force-analyze-debug-code'",
",",
"dest",
"=",
"'force_debug'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"Tells analyzer to enable assertions in code even if they were\n disabled during compilation, enabling more precise results.\"\"\"",
")",
"plugins",
"=",
"parser",
".",
"add_argument_group",
"(",
"'checker options'",
")",
"plugins",
".",
"add_argument",
"(",
"'--load-plugin'",
",",
"'-load-plugin'",
",",
"metavar",
"=",
"'<plugin library>'",
",",
"dest",
"=",
"'plugins'",
",",
"action",
"=",
"'append'",
",",
"help",
"=",
"\"\"\"Loading external checkers using the clang plugin interface.\"\"\"",
")",
"plugins",
".",
"add_argument",
"(",
"'--enable-checker'",
",",
"'-enable-checker'",
",",
"metavar",
"=",
"'<checker name>'",
",",
"action",
"=",
"AppendCommaSeparated",
",",
"help",
"=",
"\"\"\"Enable specific checker.\"\"\"",
")",
"plugins",
".",
"add_argument",
"(",
"'--disable-checker'",
",",
"'-disable-checker'",
",",
"metavar",
"=",
"'<checker name>'",
",",
"action",
"=",
"AppendCommaSeparated",
",",
"help",
"=",
"\"\"\"Disable specific checker.\"\"\"",
")",
"plugins",
".",
"add_argument",
"(",
"'--help-checkers'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"A default group of checkers is run unless explicitly disabled.\n Exactly which checkers constitute the default group is a function of\n the operating system in use. These can be printed with this flag.\"\"\"",
")",
"plugins",
".",
"add_argument",
"(",
"'--help-checkers-verbose'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"Print all available checkers and mark the enabled ones.\"\"\"",
")",
"if",
"from_build_command",
":",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'build'",
",",
"nargs",
"=",
"argparse",
".",
"REMAINDER",
",",
"help",
"=",
"\"\"\"Command to run.\"\"\"",
")",
"else",
":",
"ctu",
"=",
"parser",
".",
"add_argument_group",
"(",
"'cross translation unit analysis'",
")",
"ctu_mutex_group",
"=",
"ctu",
".",
"add_mutually_exclusive_group",
"(",
")",
"ctu_mutex_group",
".",
"add_argument",
"(",
"'--ctu'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"CtuConfig",
"(",
"collect",
"=",
"True",
",",
"analyze",
"=",
"True",
",",
"dir",
"=",
"''",
",",
"extdef_map_cmd",
"=",
"''",
")",
",",
"dest",
"=",
"'ctu_phases'",
",",
"help",
"=",
"\"\"\"Perform cross translation unit (ctu) analysis (both collect\n and analyze phases) using default <ctu-dir> for temporary output.\n At the end of the analysis, the temporary directory is removed.\"\"\"",
")",
"ctu",
".",
"add_argument",
"(",
"'--ctu-dir'",
",",
"metavar",
"=",
"'<ctu-dir>'",
",",
"dest",
"=",
"'ctu_dir'",
",",
"default",
"=",
"'ctu-dir'",
",",
"help",
"=",
"\"\"\"Defines the temporary directory used between ctu\n phases.\"\"\"",
")",
"ctu_mutex_group",
".",
"add_argument",
"(",
"'--ctu-collect-only'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"CtuConfig",
"(",
"collect",
"=",
"True",
",",
"analyze",
"=",
"False",
",",
"dir",
"=",
"''",
",",
"extdef_map_cmd",
"=",
"''",
")",
",",
"dest",
"=",
"'ctu_phases'",
",",
"help",
"=",
"\"\"\"Perform only the collect phase of ctu.\n Keep <ctu-dir> for further use.\"\"\"",
")",
"ctu_mutex_group",
".",
"add_argument",
"(",
"'--ctu-analyze-only'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"CtuConfig",
"(",
"collect",
"=",
"False",
",",
"analyze",
"=",
"True",
",",
"dir",
"=",
"''",
",",
"extdef_map_cmd",
"=",
"''",
")",
",",
"dest",
"=",
"'ctu_phases'",
",",
"help",
"=",
"\"\"\"Perform only the analyze phase of ctu. <ctu-dir> should be\n present and will not be removed after analysis.\"\"\"",
")",
"ctu",
".",
"add_argument",
"(",
"'--use-extdef-map-cmd'",
",",
"metavar",
"=",
"'<path>'",
",",
"dest",
"=",
"'extdef_map_cmd'",
",",
"default",
"=",
"'clang-extdef-mapping'",
",",
"help",
"=",
"\"\"\"'%(prog)s' uses the 'clang-extdef-mapping' executable\n relative to itself for generating external definition maps for\n static analysis. One can override this behavior with this option\n by using the 'clang-extdef-mapping' packaged with Xcode (on OS X)\n or from the PATH.\"\"\"",
")",
"return",
"parser"
] | https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/tools/scan-build-py/libscanbuild/arguments.py#L167-L406 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Listbox.__init__ | (self, master=None, cnf={}, **kw) | Construct a listbox widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, cursor,
exportselection, fg, font, foreground, height, highlightbackground,
highlightcolor, highlightthickness, relief, selectbackground,
selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
width, xscrollcommand, yscrollcommand, listvariable. | Construct a listbox widget with the parent MASTER. | [
"Construct",
"a",
"listbox",
"widget",
"with",
"the",
"parent",
"MASTER",
"."
] | def __init__(self, master=None, cnf={}, **kw):
"""Construct a listbox widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, cursor,
exportselection, fg, font, foreground, height, highlightbackground,
highlightcolor, highlightthickness, relief, selectbackground,
selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
width, xscrollcommand, yscrollcommand, listvariable."""
Widget.__init__(self, master, 'listbox', cnf, kw) | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"cnf",
"=",
"{",
"}",
",",
"*",
"*",
"kw",
")",
":",
"Widget",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"'listbox'",
",",
"cnf",
",",
"kw",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2541-L2549 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/importOBJ.py | python | insert | (filename,docname) | return doc | called when freecad wants to import a file | called when freecad wants to import a file | [
"called",
"when",
"freecad",
"wants",
"to",
"import",
"a",
"file"
] | def insert(filename,docname):
meshName = ntpath.basename(filename)
for i in meshName.split():
if "." in i:
i = i.split(".")[0]
meshName = i
"called when freecad wants to import a file"
try:
doc = FreeCAD.getDocument(docname)
except NameError:
doc = FreeCAD.newDocument(docname)
FreeCAD.ActiveDocument = doc
with pythonopen(filename,"r") as infile:
verts = []
facets = []
activeobject = None
material = None
colortable = {}
content_array = []
for line in infile:
content_array.append(line)
activeobjectExists = False
for line in content_array:
line = line.strip()
if line[:2] == "o ":
activeobjectExists = True
if not activeobjectExists:
activeobject = meshName
for line in content_array:
line = line.strip()
if line[:7] == "mtllib ":
matlib = os.path.join(os.path.dirname(filename),line[7:])
if os.path.exists(matlib):
with pythonopen(matlib,"r") as matfile:
mname = None
color = None
trans = None
for mline in matfile:
mline = mline.strip()
if mline[:7] == "newmtl ":
if mname and color:
colortable[mname] = [color,trans]
color = None
trans = None
mname = mline[7:]
elif mline[:3] == "Kd ":
color = tuple([float(i) for i in mline[3:].split()])
elif mline[:2] == "d ":
trans = int(float(mline[2:])*100)
if mname and color:
colortable[mname] = [color,trans]
elif line[:2] == "o ":
if activeobject:
makeMesh(doc,activeobject,verts,facets,material,colortable)
material = None
facets = []
activeobject = line[2:]
elif line[:2] == "v ":
verts.append([float(i) for i in line[2:].split()])
elif line[:2] == "f ":
fa = []
for i in line[2:].split():
if "/" in i:
i = i.split("/")[0]
fa.append(int(i))
facets.append(fa)
elif line[:7] == "usemtl ":
material = line[7:]
if activeobject:
makeMesh(doc,activeobject,verts,facets,material,colortable)
FreeCAD.Console.PrintMessage(translate("Arch","Successfully imported") + ' ' + decode(filename) + "\n")
return doc | [
"def",
"insert",
"(",
"filename",
",",
"docname",
")",
":",
"meshName",
"=",
"ntpath",
".",
"basename",
"(",
"filename",
")",
"for",
"i",
"in",
"meshName",
".",
"split",
"(",
")",
":",
"if",
"\".\"",
"in",
"i",
":",
"i",
"=",
"i",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"meshName",
"=",
"i",
"try",
":",
"doc",
"=",
"FreeCAD",
".",
"getDocument",
"(",
"docname",
")",
"except",
"NameError",
":",
"doc",
"=",
"FreeCAD",
".",
"newDocument",
"(",
"docname",
")",
"FreeCAD",
".",
"ActiveDocument",
"=",
"doc",
"with",
"pythonopen",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"infile",
":",
"verts",
"=",
"[",
"]",
"facets",
"=",
"[",
"]",
"activeobject",
"=",
"None",
"material",
"=",
"None",
"colortable",
"=",
"{",
"}",
"content_array",
"=",
"[",
"]",
"for",
"line",
"in",
"infile",
":",
"content_array",
".",
"append",
"(",
"line",
")",
"activeobjectExists",
"=",
"False",
"for",
"line",
"in",
"content_array",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"[",
":",
"2",
"]",
"==",
"\"o \"",
":",
"activeobjectExists",
"=",
"True",
"if",
"not",
"activeobjectExists",
":",
"activeobject",
"=",
"meshName",
"for",
"line",
"in",
"content_array",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"[",
":",
"7",
"]",
"==",
"\"mtllib \"",
":",
"matlib",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"line",
"[",
"7",
":",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"matlib",
")",
":",
"with",
"pythonopen",
"(",
"matlib",
",",
"\"r\"",
")",
"as",
"matfile",
":",
"mname",
"=",
"None",
"color",
"=",
"None",
"trans",
"=",
"None",
"for",
"mline",
"in",
"matfile",
":",
"mline",
"=",
"mline",
".",
"strip",
"(",
")",
"if",
"mline",
"[",
":",
"7",
"]",
"==",
"\"newmtl \"",
":",
"if",
"mname",
"and",
"color",
":",
"colortable",
"[",
"mname",
"]",
"=",
"[",
"color",
",",
"trans",
"]",
"color",
"=",
"None",
"trans",
"=",
"None",
"mname",
"=",
"mline",
"[",
"7",
":",
"]",
"elif",
"mline",
"[",
":",
"3",
"]",
"==",
"\"Kd \"",
":",
"color",
"=",
"tuple",
"(",
"[",
"float",
"(",
"i",
")",
"for",
"i",
"in",
"mline",
"[",
"3",
":",
"]",
".",
"split",
"(",
")",
"]",
")",
"elif",
"mline",
"[",
":",
"2",
"]",
"==",
"\"d \"",
":",
"trans",
"=",
"int",
"(",
"float",
"(",
"mline",
"[",
"2",
":",
"]",
")",
"*",
"100",
")",
"if",
"mname",
"and",
"color",
":",
"colortable",
"[",
"mname",
"]",
"=",
"[",
"color",
",",
"trans",
"]",
"elif",
"line",
"[",
":",
"2",
"]",
"==",
"\"o \"",
":",
"if",
"activeobject",
":",
"makeMesh",
"(",
"doc",
",",
"activeobject",
",",
"verts",
",",
"facets",
",",
"material",
",",
"colortable",
")",
"material",
"=",
"None",
"facets",
"=",
"[",
"]",
"activeobject",
"=",
"line",
"[",
"2",
":",
"]",
"elif",
"line",
"[",
":",
"2",
"]",
"==",
"\"v \"",
":",
"verts",
".",
"append",
"(",
"[",
"float",
"(",
"i",
")",
"for",
"i",
"in",
"line",
"[",
"2",
":",
"]",
".",
"split",
"(",
")",
"]",
")",
"elif",
"line",
"[",
":",
"2",
"]",
"==",
"\"f \"",
":",
"fa",
"=",
"[",
"]",
"for",
"i",
"in",
"line",
"[",
"2",
":",
"]",
".",
"split",
"(",
")",
":",
"if",
"\"/\"",
"in",
"i",
":",
"i",
"=",
"i",
".",
"split",
"(",
"\"/\"",
")",
"[",
"0",
"]",
"fa",
".",
"append",
"(",
"int",
"(",
"i",
")",
")",
"facets",
".",
"append",
"(",
"fa",
")",
"elif",
"line",
"[",
":",
"7",
"]",
"==",
"\"usemtl \"",
":",
"material",
"=",
"line",
"[",
"7",
":",
"]",
"if",
"activeobject",
":",
"makeMesh",
"(",
"doc",
",",
"activeobject",
",",
"verts",
",",
"facets",
",",
"material",
",",
"colortable",
")",
"FreeCAD",
".",
"Console",
".",
"PrintMessage",
"(",
"translate",
"(",
"\"Arch\"",
",",
"\"Successfully imported\"",
")",
"+",
"' '",
"+",
"decode",
"(",
"filename",
")",
"+",
"\"\\n\"",
")",
"return",
"doc"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/importOBJ.py#L294-L367 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | relaxNgValidCtxt.relaxNGValidateFullElement | (self, doc, elem) | return ret | Validate a full subtree when
xmlRelaxNGValidatePushElement() returned 0 and the content
of the node has been expanded. | Validate a full subtree when
xmlRelaxNGValidatePushElement() returned 0 and the content
of the node has been expanded. | [
"Validate",
"a",
"full",
"subtree",
"when",
"xmlRelaxNGValidatePushElement",
"()",
"returned",
"0",
"and",
"the",
"content",
"of",
"the",
"node",
"has",
"been",
"expanded",
"."
] | def relaxNGValidateFullElement(self, doc, elem):
"""Validate a full subtree when
xmlRelaxNGValidatePushElement() returned 0 and the content
of the node has been expanded. """
if doc is None: doc__o = None
else: doc__o = doc._o
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlRelaxNGValidateFullElement(self._o, doc__o, elem__o)
return ret | [
"def",
"relaxNGValidateFullElement",
"(",
"self",
",",
"doc",
",",
"elem",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"else",
":",
"elem__o",
"=",
"elem",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlRelaxNGValidateFullElement",
"(",
"self",
".",
"_o",
",",
"doc__o",
",",
"elem__o",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L5522-L5531 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftviewproviders/view_text.py | python | ViewProviderText.getIcon | (self) | return ":/icons/Draft_Text.svg" | Return the path to the icon used by the view provider. | Return the path to the icon used by the view provider. | [
"Return",
"the",
"path",
"to",
"the",
"icon",
"used",
"by",
"the",
"view",
"provider",
"."
] | def getIcon(self):
"""Return the path to the icon used by the view provider."""
return ":/icons/Draft_Text.svg" | [
"def",
"getIcon",
"(",
"self",
")",
":",
"return",
"\":/icons/Draft_Text.svg\""
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftviewproviders/view_text.py#L100-L102 | |
lballabio/quantlib-old | 136336947ed4fea9ecc1da6edad188700e821739 | gensrc/gensrc/addins/valueobjects.py | python | ValueObjects.generateHeaders | (self, cat) | Generate class source for constructor function prototypes. | Generate class source for constructor function prototypes. | [
"Generate",
"class",
"source",
"for",
"constructor",
"function",
"prototypes",
"."
] | def generateHeaders(self, cat):
"""Generate class source for constructor function prototypes."""
bufHeader = ''
for func in cat.functions('*'):
if func.generateVOs():
bufHeader += self.generateHeader(func)
self.bufferIncludesDecl_.set({
'categoryName' : cat.name(),
'headers' : bufHeader,
'libRoot' : environment.config().libRootDirectory(),
'namespaceObjects' : environment.config().namespaceObjects() })
fileName = self.rootPath_ + 'vo_' + cat.name() + '.hpp'
outputfile.OutputFile(self, fileName, self.copyright_, self.bufferIncludesDecl_) | [
"def",
"generateHeaders",
"(",
"self",
",",
"cat",
")",
":",
"bufHeader",
"=",
"''",
"for",
"func",
"in",
"cat",
".",
"functions",
"(",
"'*'",
")",
":",
"if",
"func",
".",
"generateVOs",
"(",
")",
":",
"bufHeader",
"+=",
"self",
".",
"generateHeader",
"(",
"func",
")",
"self",
".",
"bufferIncludesDecl_",
".",
"set",
"(",
"{",
"'categoryName'",
":",
"cat",
".",
"name",
"(",
")",
",",
"'headers'",
":",
"bufHeader",
",",
"'libRoot'",
":",
"environment",
".",
"config",
"(",
")",
".",
"libRootDirectory",
"(",
")",
",",
"'namespaceObjects'",
":",
"environment",
".",
"config",
"(",
")",
".",
"namespaceObjects",
"(",
")",
"}",
")",
"fileName",
"=",
"self",
".",
"rootPath_",
"+",
"'vo_'",
"+",
"cat",
".",
"name",
"(",
")",
"+",
"'.hpp'",
"outputfile",
".",
"OutputFile",
"(",
"self",
",",
"fileName",
",",
"self",
".",
"copyright_",
",",
"self",
".",
"bufferIncludesDecl_",
")"
] | https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/addins/valueobjects.py#L133-L146 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py | python | Treeview.selection_remove | (self, items) | Remove items from the selection. | Remove items from the selection. | [
"Remove",
"items",
"from",
"the",
"selection",
"."
] | def selection_remove(self, items):
"""Remove items from the selection."""
self.selection("remove", items) | [
"def",
"selection_remove",
"(",
"self",
",",
"items",
")",
":",
"self",
".",
"selection",
"(",
"\"remove\"",
",",
"items",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py#L1406-L1408 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/handlers.py | python | MapperWorkerCallbackHandler._state_to_task | (cls,
tstate,
shard_state,
eta=None,
countdown=None) | return worker_task | Generate task for slice according to current states.
Args:
tstate: An instance of TransientShardState.
shard_state: An instance of ShardState.
eta: Absolute time when the MR should execute. May not be specified
if 'countdown' is also supplied. This may be timezone-aware or
timezone-naive.
countdown: Time in seconds into the future that this MR should execute.
Defaults to zero.
Returns:
A model.HugeTask instance for the slice specified by current states. | Generate task for slice according to current states. | [
"Generate",
"task",
"for",
"slice",
"according",
"to",
"current",
"states",
"."
] | def _state_to_task(cls,
tstate,
shard_state,
eta=None,
countdown=None):
"""Generate task for slice according to current states.
Args:
tstate: An instance of TransientShardState.
shard_state: An instance of ShardState.
eta: Absolute time when the MR should execute. May not be specified
if 'countdown' is also supplied. This may be timezone-aware or
timezone-naive.
countdown: Time in seconds into the future that this MR should execute.
Defaults to zero.
Returns:
A model.HugeTask instance for the slice specified by current states.
"""
base_path = tstate.base_path
task_name = MapperWorkerCallbackHandler.get_task_name(
tstate.shard_id,
tstate.slice_id,
tstate.retries)
headers = util._get_task_headers(tstate.mapreduce_spec.mapreduce_id)
headers[util._MR_SHARD_ID_TASK_HEADER] = tstate.shard_id
worker_task = model.HugeTask(
url=base_path + "/worker_callback/" + tstate.shard_id,
params=tstate.to_dict(),
name=task_name,
eta=eta,
countdown=countdown,
parent=shard_state,
headers=headers)
return worker_task | [
"def",
"_state_to_task",
"(",
"cls",
",",
"tstate",
",",
"shard_state",
",",
"eta",
"=",
"None",
",",
"countdown",
"=",
"None",
")",
":",
"base_path",
"=",
"tstate",
".",
"base_path",
"task_name",
"=",
"MapperWorkerCallbackHandler",
".",
"get_task_name",
"(",
"tstate",
".",
"shard_id",
",",
"tstate",
".",
"slice_id",
",",
"tstate",
".",
"retries",
")",
"headers",
"=",
"util",
".",
"_get_task_headers",
"(",
"tstate",
".",
"mapreduce_spec",
".",
"mapreduce_id",
")",
"headers",
"[",
"util",
".",
"_MR_SHARD_ID_TASK_HEADER",
"]",
"=",
"tstate",
".",
"shard_id",
"worker_task",
"=",
"model",
".",
"HugeTask",
"(",
"url",
"=",
"base_path",
"+",
"\"/worker_callback/\"",
"+",
"tstate",
".",
"shard_id",
",",
"params",
"=",
"tstate",
".",
"to_dict",
"(",
")",
",",
"name",
"=",
"task_name",
",",
"eta",
"=",
"eta",
",",
"countdown",
"=",
"countdown",
",",
"parent",
"=",
"shard_state",
",",
"headers",
"=",
"headers",
")",
"return",
"worker_task"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/handlers.py#L940-L977 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/protocols.py | python | Protocol.eof_received | (self) | Called when the other end calls write_eof() or equivalent.
If this returns a false value (including None), the transport
will close itself. If it returns a true value, closing the
transport is up to the protocol. | Called when the other end calls write_eof() or equivalent. | [
"Called",
"when",
"the",
"other",
"end",
"calls",
"write_eof",
"()",
"or",
"equivalent",
"."
] | def eof_received(self):
"""Called when the other end calls write_eof() or equivalent.
If this returns a false value (including None), the transport
will close itself. If it returns a true value, closing the
transport is up to the protocol.
""" | [
"def",
"eof_received",
"(",
"self",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/protocols.py#L96-L102 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/setup.py | python | is_npy_no_signal | () | return sys.platform == 'win32' | Return True if the NPY_NO_SIGNAL symbol must be defined in configuration
header. | Return True if the NPY_NO_SIGNAL symbol must be defined in configuration
header. | [
"Return",
"True",
"if",
"the",
"NPY_NO_SIGNAL",
"symbol",
"must",
"be",
"defined",
"in",
"configuration",
"header",
"."
] | def is_npy_no_signal():
"""Return True if the NPY_NO_SIGNAL symbol must be defined in configuration
header."""
return sys.platform == 'win32' | [
"def",
"is_npy_no_signal",
"(",
")",
":",
"return",
"sys",
".",
"platform",
"==",
"'win32'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/setup.py#L78-L81 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/extensions/ifelse.py | python | IfCommandBase.evaluateFunction | (self, settings) | return not value if match.group('not') == '!' else value | Helper for evaluating the 'function' setting. | Helper for evaluating the 'function' setting. | [
"Helper",
"for",
"evaluating",
"the",
"function",
"setting",
"."
] | def evaluateFunction(self, settings):
"""Helper for evaluating the 'function' setting."""
# Separate function name from arguments
function = settings['function']
match = IfCommand.FUNCTION_RE.search(function)
if match is None:
msg = "Invalid expression for 'function' setting: {}"
raise exceptions.MooseDocsException(msg, function)
# Locate and evaluate the function
func = self.extension.getFunction(match.group('function'))
args = eval(match.group('args')[:-1] + ',)') # add trailing ',' to always create tuple
value = func(self.extension, *args)
# Require that an actual 'bool' is returned to avoid un-intended operation, for example
# if a function is returned it would evaluate to True.
if not isinstance(value, bool):
msg = "The return value from the function '{}' must be a 'bool' type, but '{}' returned."
raise exceptions.MooseDocsException(msg, match.group('function'), type(value))
return not value if match.group('not') == '!' else value | [
"def",
"evaluateFunction",
"(",
"self",
",",
"settings",
")",
":",
"# Separate function name from arguments",
"function",
"=",
"settings",
"[",
"'function'",
"]",
"match",
"=",
"IfCommand",
".",
"FUNCTION_RE",
".",
"search",
"(",
"function",
")",
"if",
"match",
"is",
"None",
":",
"msg",
"=",
"\"Invalid expression for 'function' setting: {}\"",
"raise",
"exceptions",
".",
"MooseDocsException",
"(",
"msg",
",",
"function",
")",
"# Locate and evaluate the function",
"func",
"=",
"self",
".",
"extension",
".",
"getFunction",
"(",
"match",
".",
"group",
"(",
"'function'",
")",
")",
"args",
"=",
"eval",
"(",
"match",
".",
"group",
"(",
"'args'",
")",
"[",
":",
"-",
"1",
"]",
"+",
"',)'",
")",
"# add trailing ',' to always create tuple",
"value",
"=",
"func",
"(",
"self",
".",
"extension",
",",
"*",
"args",
")",
"# Require that an actual 'bool' is returned to avoid un-intended operation, for example",
"# if a function is returned it would evaluate to True.",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"msg",
"=",
"\"The return value from the function '{}' must be a 'bool' type, but '{}' returned.\"",
"raise",
"exceptions",
".",
"MooseDocsException",
"(",
"msg",
",",
"match",
".",
"group",
"(",
"'function'",
")",
",",
"type",
"(",
"value",
")",
")",
"return",
"not",
"value",
"if",
"match",
".",
"group",
"(",
"'not'",
")",
"==",
"'!'",
"else",
"value"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/extensions/ifelse.py#L153-L174 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/calendar.py | python | TextCalendar.formatweekheader | (self, width) | return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays()) | Return a header for a week. | Return a header for a week. | [
"Return",
"a",
"header",
"for",
"a",
"week",
"."
] | def formatweekheader(self, width):
"""
Return a header for a week.
"""
return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays()) | [
"def",
"formatweekheader",
"(",
"self",
",",
"width",
")",
":",
"return",
"' '",
".",
"join",
"(",
"self",
".",
"formatweekday",
"(",
"i",
",",
"width",
")",
"for",
"i",
"in",
"self",
".",
"iterweekdays",
"(",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/calendar.py#L297-L301 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | ppapi/generators/idl_node.py | python | IDLNode.Warning | (self, msg) | Log a warning for this object. | Log a warning for this object. | [
"Log",
"a",
"warning",
"for",
"this",
"object",
"."
] | def Warning(self, msg):
"""Log a warning for this object."""
WarnOut.LogLine(self._filename, self.lineno, 0, ' %s %s' %
(str(self), msg)) | [
"def",
"Warning",
"(",
"self",
",",
"msg",
")",
":",
"WarnOut",
".",
"LogLine",
"(",
"self",
".",
"_filename",
",",
"self",
".",
"lineno",
",",
"0",
",",
"' %s %s'",
"%",
"(",
"str",
"(",
"self",
")",
",",
"msg",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/ppapi/generators/idl_node.py#L110-L113 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/ntpath.py | python | relpath | (path, start=curdir) | return join(*rel_list) | Return a relative version of a path | Return a relative version of a path | [
"Return",
"a",
"relative",
"version",
"of",
"a",
"path"
] | def relpath(path, start=curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
if start_list[0].lower() != path_list[0].lower():
unc_path, rest = splitunc(path)
unc_start, rest = splitunc(start)
if bool(unc_path) ^ bool(unc_start):
raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
% (path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_list[0], start_list[0]))
# Work out how much of the filepath is shared by start and path.
for i in range(min(len(start_list), len(path_list))):
if start_list[i].lower() != path_list[i].lower():
break
else:
i += 1
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list) | [
"def",
"relpath",
"(",
"path",
",",
"start",
"=",
"curdir",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"no path specified\"",
")",
"start_list",
"=",
"abspath",
"(",
"start",
")",
".",
"split",
"(",
"sep",
")",
"path_list",
"=",
"abspath",
"(",
"path",
")",
".",
"split",
"(",
"sep",
")",
"if",
"start_list",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"path_list",
"[",
"0",
"]",
".",
"lower",
"(",
")",
":",
"unc_path",
",",
"rest",
"=",
"splitunc",
"(",
"path",
")",
"unc_start",
",",
"rest",
"=",
"splitunc",
"(",
"start",
")",
"if",
"bool",
"(",
"unc_path",
")",
"^",
"bool",
"(",
"unc_start",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot mix UNC and non-UNC paths (%s and %s)\"",
"%",
"(",
"path",
",",
"start",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"path is on drive %s, start on drive %s\"",
"%",
"(",
"path_list",
"[",
"0",
"]",
",",
"start_list",
"[",
"0",
"]",
")",
")",
"# Work out how much of the filepath is shared by start and path.",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"len",
"(",
"start_list",
")",
",",
"len",
"(",
"path_list",
")",
")",
")",
":",
"if",
"start_list",
"[",
"i",
"]",
".",
"lower",
"(",
")",
"!=",
"path_list",
"[",
"i",
"]",
".",
"lower",
"(",
")",
":",
"break",
"else",
":",
"i",
"+=",
"1",
"rel_list",
"=",
"[",
"pardir",
"]",
"*",
"(",
"len",
"(",
"start_list",
")",
"-",
"i",
")",
"+",
"path_list",
"[",
"i",
":",
"]",
"if",
"not",
"rel_list",
":",
"return",
"curdir",
"return",
"join",
"(",
"*",
"rel_list",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ntpath.py#L480-L506 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/utils/checkpoints.py | python | init_from_checkpoint | (checkpoint_dir, assignment_map) | See `tf.contrib.framework.init_from_checkpoint`. | See `tf.contrib.framework.init_from_checkpoint`. | [
"See",
"tf",
".",
"contrib",
".",
"framework",
".",
"init_from_checkpoint",
"."
] | def init_from_checkpoint(checkpoint_dir, assignment_map):
"""See `tf.contrib.framework.init_from_checkpoint`."""
checkpoint_utils.init_from_checkpoint(checkpoint_dir, assignment_map) | [
"def",
"init_from_checkpoint",
"(",
"checkpoint_dir",
",",
"assignment_map",
")",
":",
"checkpoint_utils",
".",
"init_from_checkpoint",
"(",
"checkpoint_dir",
",",
"assignment_map",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/utils/checkpoints.py#L49-L51 | ||
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Base/Python/slicer/release/wiki.py | python | main | () | This command-line tool allows to `version` Slicer mediawiki documentation.
It has three main modes of operation: ``query``, `copy` and ``update``. | This command-line tool allows to `version` Slicer mediawiki documentation. | [
"This",
"command",
"-",
"line",
"tool",
"allows",
"to",
"version",
"Slicer",
"mediawiki",
"documentation",
"."
] | def main():
"""This command-line tool allows to `version` Slicer mediawiki documentation.
It has three main modes of operation: ``query``, `copy` and ``update``.
"""
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'--log-level', dest='log_level',
default='INFO',
help='Level of debug verbosity. DEBUG, INFO, WARNING, ERROR, CRITICAL.',
)
parser.add_argument(
"--password", type=str, default=os.environ.get('SLICER_WIKI_UPDATEBOT_PWD'),
help="password for 'UpdateBot' user. By default, try to get password from "
"'SLICER_WIKI_UPDATEBOT_PWD' environment variable."
)
subparsers = parser.add_subparsers(
help='available sub-commands', dest='command')
# sub-command parser
parser_query = subparsers.add_parser(
'query', help='obtain version information')
parser_query.add_argument(
"--version-info", action="store_true",
help="display the version associated with pages %s" % ", ".join(
['%s' % page_name for page_name in Wiki.VERSION_INFO_PAGES.values()])
)
parser_query.add_argument(
"--next-version-info", action="store_true",
help="display what would be the *next* version associated "
"with pages %s" % ", ".join(
['%s' % page_name for page_name in Wiki.VERSION_INFO_PAGES.values()])
)
parser_query.add_argument(
"--version-list", action="store_true",
help="display the versions associated with page "
"'Template::Documentation/versionlist'"
)
parser_query.add_argument(
"--acknowledgments-main-version", action="store_true",
help="display the version associated with page "
"'Template:Documentation/acknowledgments-versionlist'"
)
parser_query.add_argument(
"--redirect-pages-version", action="store_true",
help="display the version associated with pages with redirect"
)
# sub-command parser
parser_copy = subparsers.add_parser(
'copy', help='copy Nightly pages into RELEASE_VERSION namespace')
parser_copy.add_argument(
"release_version", type=str, metavar="RELEASE_VERSION",
help="the release version where Nightly pages will be copied into"
)
# sub-command parser
parser_update = subparsers.add_parser(
'update', help='create and/or update wiki pages with RELEASE_VERSION')
parser_update.add_argument(
"release_version", type=str, metavar="RELEASE_VERSION",
help="the release version used to update permanent pages"
)
parser_update.add_argument(
"--version-info-pages", action="store_true",
help="update the version associated with pages %s" % ", ".join(
['%s' % page_name for page_name in Wiki.VERSION_INFO_PAGES.values()])
)
parser_update.add_argument(
"--redirect-pages", action="store_true",
help="update the version associated with redirect pages"
)
parser_update.add_argument(
"--version-list", action="store_true",
help="add RELEASE_VERSION to page "
"'Template::Documentation/versionlist'"
)
parser_update.add_argument(
"--acknowledgments-main-version", action="store_true",
help="add RELEASE_VERSION to page "
"'Template:Documentation/acknowledgments-versionlist'"
)
parser_update.add_argument(
"--top-level-documentation-page", action="store_true",
help="add RELEASE_VERSION to page 'Documentation'"
)
args = parser.parse_args()
log.setLevel(args.log_level.upper())
log.addHandler(logging.StreamHandler())
wiki = Wiki(password=args.password)
if args.command == "query":
handle_query(wiki, args)
elif args.command == "copy":
handle_copy(wiki, args)
elif args.command == "update":
handle_update(wiki, args) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'--log-level'",
",",
"dest",
"=",
"'log_level'",
",",
"default",
"=",
"'INFO'",
",",
"help",
"=",
"'Level of debug verbosity. DEBUG, INFO, WARNING, ERROR, CRITICAL.'",
",",
")",
"parser",
".",
"add_argument",
"(",
"\"--password\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SLICER_WIKI_UPDATEBOT_PWD'",
")",
",",
"help",
"=",
"\"password for 'UpdateBot' user. By default, try to get password from \"",
"\"'SLICER_WIKI_UPDATEBOT_PWD' environment variable.\"",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"help",
"=",
"'available sub-commands'",
",",
"dest",
"=",
"'command'",
")",
"# sub-command parser",
"parser_query",
"=",
"subparsers",
".",
"add_parser",
"(",
"'query'",
",",
"help",
"=",
"'obtain version information'",
")",
"parser_query",
".",
"add_argument",
"(",
"\"--version-info\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"display the version associated with pages %s\"",
"%",
"\", \"",
".",
"join",
"(",
"[",
"'%s'",
"%",
"page_name",
"for",
"page_name",
"in",
"Wiki",
".",
"VERSION_INFO_PAGES",
".",
"values",
"(",
")",
"]",
")",
")",
"parser_query",
".",
"add_argument",
"(",
"\"--next-version-info\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"display what would be the *next* version associated \"",
"\"with pages %s\"",
"%",
"\", \"",
".",
"join",
"(",
"[",
"'%s'",
"%",
"page_name",
"for",
"page_name",
"in",
"Wiki",
".",
"VERSION_INFO_PAGES",
".",
"values",
"(",
")",
"]",
")",
")",
"parser_query",
".",
"add_argument",
"(",
"\"--version-list\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"display the versions associated with page \"",
"\"'Template::Documentation/versionlist'\"",
")",
"parser_query",
".",
"add_argument",
"(",
"\"--acknowledgments-main-version\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"display the version associated with page \"",
"\"'Template:Documentation/acknowledgments-versionlist'\"",
")",
"parser_query",
".",
"add_argument",
"(",
"\"--redirect-pages-version\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"display the version associated with pages with redirect\"",
")",
"# sub-command parser",
"parser_copy",
"=",
"subparsers",
".",
"add_parser",
"(",
"'copy'",
",",
"help",
"=",
"'copy Nightly pages into RELEASE_VERSION namespace'",
")",
"parser_copy",
".",
"add_argument",
"(",
"\"release_version\"",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"\"RELEASE_VERSION\"",
",",
"help",
"=",
"\"the release version where Nightly pages will be copied into\"",
")",
"# sub-command parser",
"parser_update",
"=",
"subparsers",
".",
"add_parser",
"(",
"'update'",
",",
"help",
"=",
"'create and/or update wiki pages with RELEASE_VERSION'",
")",
"parser_update",
".",
"add_argument",
"(",
"\"release_version\"",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"\"RELEASE_VERSION\"",
",",
"help",
"=",
"\"the release version used to update permanent pages\"",
")",
"parser_update",
".",
"add_argument",
"(",
"\"--version-info-pages\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"update the version associated with pages %s\"",
"%",
"\", \"",
".",
"join",
"(",
"[",
"'%s'",
"%",
"page_name",
"for",
"page_name",
"in",
"Wiki",
".",
"VERSION_INFO_PAGES",
".",
"values",
"(",
")",
"]",
")",
")",
"parser_update",
".",
"add_argument",
"(",
"\"--redirect-pages\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"update the version associated with redirect pages\"",
")",
"parser_update",
".",
"add_argument",
"(",
"\"--version-list\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"add RELEASE_VERSION to page \"",
"\"'Template::Documentation/versionlist'\"",
")",
"parser_update",
".",
"add_argument",
"(",
"\"--acknowledgments-main-version\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"add RELEASE_VERSION to page \"",
"\"'Template:Documentation/acknowledgments-versionlist'\"",
")",
"parser_update",
".",
"add_argument",
"(",
"\"--top-level-documentation-page\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"add RELEASE_VERSION to page 'Documentation'\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"log",
".",
"setLevel",
"(",
"args",
".",
"log_level",
".",
"upper",
"(",
")",
")",
"log",
".",
"addHandler",
"(",
"logging",
".",
"StreamHandler",
"(",
")",
")",
"wiki",
"=",
"Wiki",
"(",
"password",
"=",
"args",
".",
"password",
")",
"if",
"args",
".",
"command",
"==",
"\"query\"",
":",
"handle_query",
"(",
"wiki",
",",
"args",
")",
"elif",
"args",
".",
"command",
"==",
"\"copy\"",
":",
"handle_copy",
"(",
"wiki",
",",
"args",
")",
"elif",
"args",
".",
"command",
"==",
"\"update\"",
":",
"handle_update",
"(",
"wiki",
",",
"args",
")"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/release/wiki.py#L410-L512 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozpack/files.py | python | MinifiedProperties.open | (self) | return BytesIO(''.join(l for l in self._file.open().readlines()
if not l.startswith('#'))) | Return a file-like object allowing to read() the minified content of
the properties file. | Return a file-like object allowing to read() the minified content of
the properties file. | [
"Return",
"a",
"file",
"-",
"like",
"object",
"allowing",
"to",
"read",
"()",
"the",
"minified",
"content",
"of",
"the",
"properties",
"file",
"."
] | def open(self):
'''
Return a file-like object allowing to read() the minified content of
the properties file.
'''
return BytesIO(''.join(l for l in self._file.open().readlines()
if not l.startswith('#'))) | [
"def",
"open",
"(",
"self",
")",
":",
"return",
"BytesIO",
"(",
"''",
".",
"join",
"(",
"l",
"for",
"l",
"in",
"self",
".",
"_file",
".",
"open",
"(",
")",
".",
"readlines",
"(",
")",
"if",
"not",
"l",
".",
"startswith",
"(",
"'#'",
")",
")",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/files.py#L592-L598 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_HMAC_Start_REQUEST.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(TPM2_HMAC_Start_REQUEST) | Returns new TPM2_HMAC_Start_REQUEST object constructed from its
marshaled representation in the given byte buffer | Returns new TPM2_HMAC_Start_REQUEST object constructed from its
marshaled representation in the given byte buffer | [
"Returns",
"new",
"TPM2_HMAC_Start_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new TPM2_HMAC_Start_REQUEST object constructed from its
marshaled representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(TPM2_HMAC_Start_REQUEST) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"TPM2_HMAC_Start_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L11946-L11950 | |
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/tools/scan-build-py/libscanbuild/__init__.py | python | reconfigure_logging | (verbose_level) | Reconfigure logging level and format based on the verbose flag.
:param verbose_level: number of `-v` flags received by the command
:return: no return value | Reconfigure logging level and format based on the verbose flag. | [
"Reconfigure",
"logging",
"level",
"and",
"format",
"based",
"on",
"the",
"verbose",
"flag",
"."
] | def reconfigure_logging(verbose_level):
""" Reconfigure logging level and format based on the verbose flag.
:param verbose_level: number of `-v` flags received by the command
:return: no return value
"""
# Exit when nothing to do.
if verbose_level == 0:
return
root = logging.getLogger()
# Tune logging level.
level = logging.WARNING - min(logging.WARNING, (10 * verbose_level))
root.setLevel(level)
# Be verbose with messages.
if verbose_level <= 3:
fmt_string = '%(name)s: %(levelname)s: %(message)s'
else:
fmt_string = '%(name)s: %(levelname)s: %(funcName)s: %(message)s'
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(fmt=fmt_string))
root.handlers = [handler] | [
"def",
"reconfigure_logging",
"(",
"verbose_level",
")",
":",
"# Exit when nothing to do.",
"if",
"verbose_level",
"==",
"0",
":",
"return",
"root",
"=",
"logging",
".",
"getLogger",
"(",
")",
"# Tune logging level.",
"level",
"=",
"logging",
".",
"WARNING",
"-",
"min",
"(",
"logging",
".",
"WARNING",
",",
"(",
"10",
"*",
"verbose_level",
")",
")",
"root",
".",
"setLevel",
"(",
"level",
")",
"# Be verbose with messages.",
"if",
"verbose_level",
"<=",
"3",
":",
"fmt_string",
"=",
"'%(name)s: %(levelname)s: %(message)s'",
"else",
":",
"fmt_string",
"=",
"'%(name)s: %(levelname)s: %(funcName)s: %(message)s'",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stdout",
")",
"handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"fmt_string",
")",
")",
"root",
".",
"handlers",
"=",
"[",
"handler",
"]"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/tools/scan-build-py/libscanbuild/__init__.py#L82-L103 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/image_ops_impl.py | python | random_hue | (image, max_delta, seed=None) | return adjust_hue(image, delta) | Adjust the hue of RGB images by a random factor.
Equivalent to `adjust_hue()` but uses a `delta` randomly
picked in the interval `[-max_delta, max_delta)`.
`max_delta` must be in the interval `[0, 0.5]`.
Usage Example:
>>> x = [[[1.0, 2.0, 3.0],
... [4.0, 5.0, 6.0]],
... [[7.0, 8.0, 9.0],
... [10.0, 11.0, 12.0]]]
>>> tf.image.random_hue(x, 0.2)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=...>
For producing deterministic results given a `seed` value, use
`tf.image.stateless_random_hue`. Unlike using the `seed` param with
`tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the same
results given the same seed independent of how many times the function is
called, and independent of global seed settings (e.g. tf.random.set_seed).
Args:
image: RGB image or images. The size of the last dimension must be 3.
max_delta: float. The maximum value for the random delta.
seed: An operation-specific seed. It will be used in conjunction with the
graph-level seed to determine the real seeds that will be used in this
operation. Please see the documentation of set_random_seed for its
interaction with the graph-level random seed.
Returns:
Adjusted image(s), same shape and DType as `image`.
Raises:
ValueError: if `max_delta` is invalid. | Adjust the hue of RGB images by a random factor. | [
"Adjust",
"the",
"hue",
"of",
"RGB",
"images",
"by",
"a",
"random",
"factor",
"."
] | def random_hue(image, max_delta, seed=None):
"""Adjust the hue of RGB images by a random factor.
Equivalent to `adjust_hue()` but uses a `delta` randomly
picked in the interval `[-max_delta, max_delta)`.
`max_delta` must be in the interval `[0, 0.5]`.
Usage Example:
>>> x = [[[1.0, 2.0, 3.0],
... [4.0, 5.0, 6.0]],
... [[7.0, 8.0, 9.0],
... [10.0, 11.0, 12.0]]]
>>> tf.image.random_hue(x, 0.2)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=...>
For producing deterministic results given a `seed` value, use
`tf.image.stateless_random_hue`. Unlike using the `seed` param with
`tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the same
results given the same seed independent of how many times the function is
called, and independent of global seed settings (e.g. tf.random.set_seed).
Args:
image: RGB image or images. The size of the last dimension must be 3.
max_delta: float. The maximum value for the random delta.
seed: An operation-specific seed. It will be used in conjunction with the
graph-level seed to determine the real seeds that will be used in this
operation. Please see the documentation of set_random_seed for its
interaction with the graph-level random seed.
Returns:
Adjusted image(s), same shape and DType as `image`.
Raises:
ValueError: if `max_delta` is invalid.
"""
if max_delta > 0.5:
raise ValueError('max_delta must be <= 0.5.')
if max_delta < 0:
raise ValueError('max_delta must be non-negative.')
delta = random_ops.random_uniform([], -max_delta, max_delta, seed=seed)
return adjust_hue(image, delta) | [
"def",
"random_hue",
"(",
"image",
",",
"max_delta",
",",
"seed",
"=",
"None",
")",
":",
"if",
"max_delta",
">",
"0.5",
":",
"raise",
"ValueError",
"(",
"'max_delta must be <= 0.5.'",
")",
"if",
"max_delta",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'max_delta must be non-negative.'",
")",
"delta",
"=",
"random_ops",
".",
"random_uniform",
"(",
"[",
"]",
",",
"-",
"max_delta",
",",
"max_delta",
",",
"seed",
"=",
"seed",
")",
"return",
"adjust_hue",
"(",
"image",
",",
"delta",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/image_ops_impl.py#L2559-L2603 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py | python | TPen._update | (self, count=True, forced=False) | dummy method - to be overwritten by child class | dummy method - to be overwritten by child class | [
"dummy",
"method",
"-",
"to",
"be",
"overwritten",
"by",
"child",
"class"
] | def _update(self, count=True, forced=False):
"""dummy method - to be overwritten by child class""" | [
"def",
"_update",
"(",
"self",
",",
"count",
"=",
"True",
",",
"forced",
"=",
"False",
")",
":"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L2369-L2370 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/lib/dumping_callback.py | python | _DumpingCallback.callback | (self,
op_type,
inputs,
attrs,
outputs,
op_name=None,
graph=None) | Op callback for tracing (dumping) a TF program's execution. | Op callback for tracing (dumping) a TF program's execution. | [
"Op",
"callback",
"for",
"tracing",
"(",
"dumping",
")",
"a",
"TF",
"program",
"s",
"execution",
"."
] | def callback(self,
op_type,
inputs,
attrs,
outputs,
op_name=None,
graph=None):
"""Op callback for tracing (dumping) a TF program's execution."""
del attrs # Unused
writer = self.get_writer()
if graph:
is_v1_graph_mode = not ops.executing_eagerly_outside_functions()
context_id = self._get_context_id(graph) # Innermost context ID.
output_tensor_ids = self._get_symbolic_tensor_ids(len(outputs))
if op_type in ("Const", "Placeholder", "PlaceholderWithDefault"):
# In some cases, the op name of a Const or Placeholder op in a graph
# can be duplicate (e.g., `None` or "resource").
# When this happens, we use the output tensor name to infer
# the non-duplicated tensor name.
op_name = outputs[0].name.split(":")[0]
if is_v1_graph_mode:
for input_tensor in inputs:
if input_tensor in self._placeholder_to_debug_tensor and outputs:
outputs[0].op._add_control_input( # pylint: disable=protected-access
self._placeholder_to_debug_tensor[input_tensor].op)
graph_op_creation = debug_event_pb2.GraphOpCreation(
op_type=op_type,
op_name=op_name,
graph_name=graph.name if hasattr(graph, "name") else None,
graph_id=context_id,
input_names=[
self._lookup_tensor_name(input_tensor) for input_tensor in inputs
],
num_outputs=len(outputs),
output_tensor_ids=output_tensor_ids,
code_location=self._process_stack_frames())
writer.WriteGraphOpCreation(graph_op_creation)
if outputs and compat.as_bytes(
op_type) not in op_callbacks_common.OP_CALLBACK_SKIP_OPS:
return self._instrument_symbolic_tensors(
outputs, op_type, op_name, context_id, output_tensor_ids)
else:
op_type_bytes = compat.as_bytes(op_type)
if op_type_bytes == b"DebugNumericSummaryV2":
# TODO(b/140334369): Remove this special casing logic once op_callback.
# automatically prevents infinite recursion in eager mode.
return None
if op_type_bytes in op_callbacks_common.OP_CALLBACK_SKIP_OPS:
return None
context_id = self._func_graph_id_from_func_name(op_type)
input_ids = [t._id for t in inputs] # pylint:disable=protected-access
output_tensor_device_ids = [writer.RegisterDeviceAndGetId(output.device)
for output in outputs] if outputs else []
writer.WriteExecution(self._dump_eager_tensors(
outputs, op_type, input_ids, output_tensor_device_ids,
graph_id=context_id)) | [
"def",
"callback",
"(",
"self",
",",
"op_type",
",",
"inputs",
",",
"attrs",
",",
"outputs",
",",
"op_name",
"=",
"None",
",",
"graph",
"=",
"None",
")",
":",
"del",
"attrs",
"# Unused",
"writer",
"=",
"self",
".",
"get_writer",
"(",
")",
"if",
"graph",
":",
"is_v1_graph_mode",
"=",
"not",
"ops",
".",
"executing_eagerly_outside_functions",
"(",
")",
"context_id",
"=",
"self",
".",
"_get_context_id",
"(",
"graph",
")",
"# Innermost context ID.",
"output_tensor_ids",
"=",
"self",
".",
"_get_symbolic_tensor_ids",
"(",
"len",
"(",
"outputs",
")",
")",
"if",
"op_type",
"in",
"(",
"\"Const\"",
",",
"\"Placeholder\"",
",",
"\"PlaceholderWithDefault\"",
")",
":",
"# In some cases, the op name of a Const or Placeholder op in a graph",
"# can be duplicate (e.g., `None` or \"resource\").",
"# When this happens, we use the output tensor name to infer",
"# the non-duplicated tensor name.",
"op_name",
"=",
"outputs",
"[",
"0",
"]",
".",
"name",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"if",
"is_v1_graph_mode",
":",
"for",
"input_tensor",
"in",
"inputs",
":",
"if",
"input_tensor",
"in",
"self",
".",
"_placeholder_to_debug_tensor",
"and",
"outputs",
":",
"outputs",
"[",
"0",
"]",
".",
"op",
".",
"_add_control_input",
"(",
"# pylint: disable=protected-access",
"self",
".",
"_placeholder_to_debug_tensor",
"[",
"input_tensor",
"]",
".",
"op",
")",
"graph_op_creation",
"=",
"debug_event_pb2",
".",
"GraphOpCreation",
"(",
"op_type",
"=",
"op_type",
",",
"op_name",
"=",
"op_name",
",",
"graph_name",
"=",
"graph",
".",
"name",
"if",
"hasattr",
"(",
"graph",
",",
"\"name\"",
")",
"else",
"None",
",",
"graph_id",
"=",
"context_id",
",",
"input_names",
"=",
"[",
"self",
".",
"_lookup_tensor_name",
"(",
"input_tensor",
")",
"for",
"input_tensor",
"in",
"inputs",
"]",
",",
"num_outputs",
"=",
"len",
"(",
"outputs",
")",
",",
"output_tensor_ids",
"=",
"output_tensor_ids",
",",
"code_location",
"=",
"self",
".",
"_process_stack_frames",
"(",
")",
")",
"writer",
".",
"WriteGraphOpCreation",
"(",
"graph_op_creation",
")",
"if",
"outputs",
"and",
"compat",
".",
"as_bytes",
"(",
"op_type",
")",
"not",
"in",
"op_callbacks_common",
".",
"OP_CALLBACK_SKIP_OPS",
":",
"return",
"self",
".",
"_instrument_symbolic_tensors",
"(",
"outputs",
",",
"op_type",
",",
"op_name",
",",
"context_id",
",",
"output_tensor_ids",
")",
"else",
":",
"op_type_bytes",
"=",
"compat",
".",
"as_bytes",
"(",
"op_type",
")",
"if",
"op_type_bytes",
"==",
"b\"DebugNumericSummaryV2\"",
":",
"# TODO(b/140334369): Remove this special casing logic once op_callback.",
"# automatically prevents infinite recursion in eager mode.",
"return",
"None",
"if",
"op_type_bytes",
"in",
"op_callbacks_common",
".",
"OP_CALLBACK_SKIP_OPS",
":",
"return",
"None",
"context_id",
"=",
"self",
".",
"_func_graph_id_from_func_name",
"(",
"op_type",
")",
"input_ids",
"=",
"[",
"t",
".",
"_id",
"for",
"t",
"in",
"inputs",
"]",
"# pylint:disable=protected-access",
"output_tensor_device_ids",
"=",
"[",
"writer",
".",
"RegisterDeviceAndGetId",
"(",
"output",
".",
"device",
")",
"for",
"output",
"in",
"outputs",
"]",
"if",
"outputs",
"else",
"[",
"]",
"writer",
".",
"WriteExecution",
"(",
"self",
".",
"_dump_eager_tensors",
"(",
"outputs",
",",
"op_type",
",",
"input_ids",
",",
"output_tensor_device_ids",
",",
"graph_id",
"=",
"context_id",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/dumping_callback.py#L538-L594 | ||
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/engine/forces.py | python | ForceBeads.extra_gather | (self) | return [b.extra for b in self._forces] | Obtains the potential energy for each replica.
Returns:
A list of the potential energy of each replica of the system. | Obtains the potential energy for each replica. | [
"Obtains",
"the",
"potential",
"energy",
"for",
"each",
"replica",
"."
] | def extra_gather(self):
"""Obtains the potential energy for each replica.
Returns:
A list of the potential energy of each replica of the system.
"""
self.queue()
return [b.extra for b in self._forces] | [
"def",
"extra_gather",
"(",
"self",
")",
":",
"self",
".",
"queue",
"(",
")",
"return",
"[",
"b",
".",
"extra",
"for",
"b",
"in",
"self",
".",
"_forces",
"]"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/forces.py#L489-L497 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/packager.py | python | Distro.__init__ | (self, string) | Initialize Distro. | Initialize Distro. | [
"Initialize",
"Distro",
"."
] | def __init__(self, string):
"""Initialize Distro."""
self.dname = string | [
"def",
"__init__",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"dname",
"=",
"string"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/packager.py#L176-L178 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/utils/extract_docs.py | python | SubprocessLoader._receive | (self) | Receive response from worker's stdout | Receive response from worker's stdout | [
"Receive",
"response",
"from",
"worker",
"s",
"stdout"
] | def _receive(self):
""" Receive response from worker's stdout """
for line in iter(self._worker.stdout.readline, ''):
try:
key, cmd, args = json.loads(line.decode('utf-8'))
if key != self.AUTH_CODE:
raise ValueError('Got wrong auth code')
return cmd, args
except ValueError:
if self._worker.poll():
raise IOError("Worker died")
else:
continue # ignore invalid output from worker
else:
raise IOError("Can't read worker response") | [
"def",
"_receive",
"(",
"self",
")",
":",
"for",
"line",
"in",
"iter",
"(",
"self",
".",
"_worker",
".",
"stdout",
".",
"readline",
",",
"''",
")",
":",
"try",
":",
"key",
",",
"cmd",
",",
"args",
"=",
"json",
".",
"loads",
"(",
"line",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"if",
"key",
"!=",
"self",
".",
"AUTH_CODE",
":",
"raise",
"ValueError",
"(",
"'Got wrong auth code'",
")",
"return",
"cmd",
",",
"args",
"except",
"ValueError",
":",
"if",
"self",
".",
"_worker",
".",
"poll",
"(",
")",
":",
"raise",
"IOError",
"(",
"\"Worker died\"",
")",
"else",
":",
"continue",
"# ignore invalid output from worker",
"else",
":",
"raise",
"IOError",
"(",
"\"Can't read worker response\"",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/utils/extract_docs.py#L185-L199 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/closure_linter/closure_linter/gjslint.py | python | _PrintFileSummary | (paths, records) | Print a detailed summary of the number of errors in each file. | Print a detailed summary of the number of errors in each file. | [
"Print",
"a",
"detailed",
"summary",
"of",
"the",
"number",
"of",
"errors",
"in",
"each",
"file",
"."
] | def _PrintFileSummary(paths, records):
"""Print a detailed summary of the number of errors in each file."""
paths = list(paths)
paths.sort()
for path in paths:
path_errors = [e for e in records if e.path == path]
print '%s: %d' % (path, len(path_errors)) | [
"def",
"_PrintFileSummary",
"(",
"paths",
",",
"records",
")",
":",
"paths",
"=",
"list",
"(",
"paths",
")",
"paths",
".",
"sort",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"path_errors",
"=",
"[",
"e",
"for",
"e",
"in",
"records",
"if",
"e",
".",
"path",
"==",
"path",
"]",
"print",
"'%s: %d'",
"%",
"(",
"path",
",",
"len",
"(",
"path_errors",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/gjslint.py#L150-L158 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/nn_ops.py | python | bias_add_v1 | (value, bias, name=None) | Adds `bias` to `value`.
This is a deprecated version of bias_add and will soon to be removed.
This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.
Broadcasting is supported, so `value` may have any number of dimensions.
Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the
case where both types are quantized.
Args:
value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,
`int16`, `int8`, `complex64`, or `complex128`.
bias: A 1-D `Tensor` with size matching the last dimension of `value`.
Must be the same type as `value` unless `value` is a quantized type,
in which case a different quantized type may be used.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `value`. | Adds `bias` to `value`. | [
"Adds",
"bias",
"to",
"value",
"."
] | def bias_add_v1(value, bias, name=None):
"""Adds `bias` to `value`.
This is a deprecated version of bias_add and will soon to be removed.
This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.
Broadcasting is supported, so `value` may have any number of dimensions.
Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the
case where both types are quantized.
Args:
value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,
`int16`, `int8`, `complex64`, or `complex128`.
bias: A 1-D `Tensor` with size matching the last dimension of `value`.
Must be the same type as `value` unless `value` is a quantized type,
in which case a different quantized type may be used.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `value`.
"""
with ops.name_scope(name, "BiasAddV1", [value, bias]) as name:
value = ops.convert_to_tensor(value, name="input")
bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias")
return gen_nn_ops._bias_add_v1(value, bias, name=name) | [
"def",
"bias_add_v1",
"(",
"value",
",",
"bias",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"BiasAddV1\"",
",",
"[",
"value",
",",
"bias",
"]",
")",
"as",
"name",
":",
"value",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"value",
",",
"name",
"=",
"\"input\"",
")",
"bias",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"bias",
",",
"dtype",
"=",
"value",
".",
"dtype",
",",
"name",
"=",
"\"bias\"",
")",
"return",
"gen_nn_ops",
".",
"_bias_add_v1",
"(",
"value",
",",
"bias",
",",
"name",
"=",
"name",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/nn_ops.py#L1459-L1483 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/data_structures/sarray.py | python | SArray.fillna | (self, value) | Create new SArray with all missing values (None or NaN) filled in
with the given value.
The size of the new SArray will be the same as the original SArray. If
the given value is not the same type as the values in the SArray,
`fillna` will attempt to convert the value to the original SArray's
type. If this fails, an error will be raised.
Parameters
----------
value : type convertible to SArray's type
The value used to replace all missing values
Returns
-------
out : SArray
A new SArray with all missing values filled | Create new SArray with all missing values (None or NaN) filled in
with the given value. | [
"Create",
"new",
"SArray",
"with",
"all",
"missing",
"values",
"(",
"None",
"or",
"NaN",
")",
"filled",
"in",
"with",
"the",
"given",
"value",
"."
] | def fillna(self, value):
"""
Create new SArray with all missing values (None or NaN) filled in
with the given value.
The size of the new SArray will be the same as the original SArray. If
the given value is not the same type as the values in the SArray,
`fillna` will attempt to convert the value to the original SArray's
type. If this fails, an error will be raised.
Parameters
----------
value : type convertible to SArray's type
The value used to replace all missing values
Returns
-------
out : SArray
A new SArray with all missing values filled
"""
with cython_context():
return SArray(_proxy=self.__proxy__.fill_missing_values(value)) | [
"def",
"fillna",
"(",
"self",
",",
"value",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"SArray",
"(",
"_proxy",
"=",
"self",
".",
"__proxy__",
".",
"fill_missing_values",
"(",
"value",
")",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L2745-L2767 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/transforms.py | python | PassManagerBuilder.opt_level | (self) | return ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel(self) | The general optimization level as an integer between 0 and 3. | The general optimization level as an integer between 0 and 3. | [
"The",
"general",
"optimization",
"level",
"as",
"an",
"integer",
"between",
"0",
"and",
"3",
"."
] | def opt_level(self):
"""
The general optimization level as an integer between 0 and 3.
"""
return ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel(self) | [
"def",
"opt_level",
"(",
"self",
")",
":",
"return",
"ffi",
".",
"lib",
".",
"LLVMPY_PassManagerBuilderGetOptLevel",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/transforms.py#L20-L24 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/pySketch/pySketch.py | python | DrawingFrame.onIdle | (self, event) | If the size was changed then resize the bitmap used for double
buffering to match the window size. We do it in Idle time so
there is only one refresh after resizing is done, not lots while
it is happening. | If the size was changed then resize the bitmap used for double
buffering to match the window size. We do it in Idle time so
there is only one refresh after resizing is done, not lots while
it is happening. | [
"If",
"the",
"size",
"was",
"changed",
"then",
"resize",
"the",
"bitmap",
"used",
"for",
"double",
"buffering",
"to",
"match",
"the",
"window",
"size",
".",
"We",
"do",
"it",
"in",
"Idle",
"time",
"so",
"there",
"is",
"only",
"one",
"refresh",
"after",
"resizing",
"is",
"done",
"not",
"lots",
"while",
"it",
"is",
"happening",
"."
] | def onIdle(self, event):
"""
If the size was changed then resize the bitmap used for double
buffering to match the window size. We do it in Idle time so
there is only one refresh after resizing is done, not lots while
it is happening.
"""
if self._reInitBuffer and self.IsShown():
self._initBuffer()
self.drawPanel.Refresh(False) | [
"def",
"onIdle",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"_reInitBuffer",
"and",
"self",
".",
"IsShown",
"(",
")",
":",
"self",
".",
"_initBuffer",
"(",
")",
"self",
".",
"drawPanel",
".",
"Refresh",
"(",
"False",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/pySketch/pySketch.py#L598-L607 | ||
googlevr/seurat | 7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53 | seurat/generation/maya/seurat_rig.py | python | WorldFromEyeMatrixFromFace | (face_name) | Creates world-from-eye matrix for the given face of a cube map.
Args:
face_name: Name of the face. Must be one of 'front', 'back', 'left',
'right', 'bottom', 'top'.
Returns:
The world-from-eye matrix for the given face as a list in row-major order.
Raises:
ValueError: face_name is not the name of a cube map face. | Creates world-from-eye matrix for the given face of a cube map. | [
"Creates",
"world",
"-",
"from",
"-",
"eye",
"matrix",
"for",
"the",
"given",
"face",
"of",
"a",
"cube",
"map",
"."
] | def WorldFromEyeMatrixFromFace(face_name):
"""Creates world-from-eye matrix for the given face of a cube map.
Args:
face_name: Name of the face. Must be one of 'front', 'back', 'left',
'right', 'bottom', 'top'.
Returns:
The world-from-eye matrix for the given face as a list in row-major order.
Raises:
ValueError: face_name is not the name of a cube map face.
"""
# pylint: disable=bad-whitespace
# pylint: disable=bad-continuation
if face_name is 'front':
return [ 1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0] # pyformat: disable
elif face_name is 'back':
return [-1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, -1.0, 0.0,
0.0, 0.0, 0.0, 1.0] # pyformat: disable
elif face_name is 'left':
return [ 0.0, 0.0, 1.0, 0.0,
0.0, 1.0, 0.0, 0.0,
-1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0] # pyformat: disable
elif face_name is 'right':
return [ 0.0, 0.0, -1.0, 0.0,
0.0, 1.0, 0.0, 0.0,
1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0] # pyformat: disable
elif face_name is 'bottom':
return [ 1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, -1.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0] # pyformat: disable
elif face_name is 'top':
return [ 1.0, 0.0, 0.0, 0.0,
0.0, 0.0, -1.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0] # pyformat: disable
else:
raise ValueError('Invalid face_name') | [
"def",
"WorldFromEyeMatrixFromFace",
"(",
"face_name",
")",
":",
"# pylint: disable=bad-whitespace",
"# pylint: disable=bad-continuation",
"if",
"face_name",
"is",
"'front'",
":",
"return",
"[",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
"]",
"# pyformat: disable",
"elif",
"face_name",
"is",
"'back'",
":",
"return",
"[",
"-",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"-",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
"]",
"# pyformat: disable",
"elif",
"face_name",
"is",
"'left'",
":",
"return",
"[",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"-",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
"]",
"# pyformat: disable",
"elif",
"face_name",
"is",
"'right'",
":",
"return",
"[",
"0.0",
",",
"0.0",
",",
"-",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
"]",
"# pyformat: disable",
"elif",
"face_name",
"is",
"'bottom'",
":",
"return",
"[",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"-",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
"]",
"# pyformat: disable",
"elif",
"face_name",
"is",
"'top'",
":",
"return",
"[",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"-",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
"]",
"# pyformat: disable",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid face_name'",
")"
] | https://github.com/googlevr/seurat/blob/7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53/seurat/generation/maya/seurat_rig.py#L55-L101 | ||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/ansic/cparse.py | python | p_parameter_type_list_2 | (t) | parameter_type_list : parameter_list COMMA ELLIPSIS | parameter_type_list : parameter_list COMMA ELLIPSIS | [
"parameter_type_list",
":",
"parameter_list",
"COMMA",
"ELLIPSIS"
] | def p_parameter_type_list_2(t):
'parameter_type_list : parameter_list COMMA ELLIPSIS'
pass | [
"def",
"p_parameter_type_list_2",
"(",
"t",
")",
":",
"pass"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L330-L332 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py | python | Environment.__add__ | (self, other) | return new | Add an environment or distribution to an environment | Add an environment or distribution to an environment | [
"Add",
"an",
"environment",
"or",
"distribution",
"to",
"an",
"environment"
] | def __add__(self, other):
"""Add an environment or distribution to an environment"""
new = self.__class__([], platform=None, python=None)
for env in self, other:
new += env
return new | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"new",
"=",
"self",
".",
"__class__",
"(",
"[",
"]",
",",
"platform",
"=",
"None",
",",
"python",
"=",
"None",
")",
"for",
"env",
"in",
"self",
",",
"other",
":",
"new",
"+=",
"env",
"return",
"new"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py#L1095-L1100 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | Geometry3D.isStandalone | (self) | return _robotsim.Geometry3D_isStandalone(self) | isStandalone(Geometry3D self) -> bool
Returns true if this is a standalone geometry. | isStandalone(Geometry3D self) -> bool | [
"isStandalone",
"(",
"Geometry3D",
"self",
")",
"-",
">",
"bool"
] | def isStandalone(self):
"""
isStandalone(Geometry3D self) -> bool
Returns true if this is a standalone geometry.
"""
return _robotsim.Geometry3D_isStandalone(self) | [
"def",
"isStandalone",
"(",
"self",
")",
":",
"return",
"_robotsim",
".",
"Geometry3D_isStandalone",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L1924-L1933 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/symsrc/pefile.py | python | Structure.dump | (self, indentation=0) | return dump | Returns a string representation of the structure. | Returns a string representation of the structure. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"structure",
"."
] | def dump(self, indentation=0):
"""Returns a string representation of the structure."""
dump = []
dump.append('[%s]' % self.name)
# Refer to the __set_format__ method for an explanation
# of the following construct.
for keys in self.__keys__:
for key in keys:
val = getattr(self, key)
if isinstance(val, int) or isinstance(val, long):
val_str = '0x%-8X' % (val)
if key == 'TimeDateStamp' or key == 'dwTimeStamp':
try:
val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
except exceptions.ValueError, e:
val_str += ' [INVALID TIME]'
else:
val_str = ''.join(filter(lambda c:c != '\0', str(val)))
dump.append('%-30s %s' % (key+':', val_str))
return dump | [
"def",
"dump",
"(",
"self",
",",
"indentation",
"=",
"0",
")",
":",
"dump",
"=",
"[",
"]",
"dump",
".",
"append",
"(",
"'[%s]'",
"%",
"self",
".",
"name",
")",
"# Refer to the __set_format__ method for an explanation",
"# of the following construct.",
"for",
"keys",
"in",
"self",
".",
"__keys__",
":",
"for",
"key",
"in",
"keys",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"if",
"isinstance",
"(",
"val",
",",
"int",
")",
"or",
"isinstance",
"(",
"val",
",",
"long",
")",
":",
"val_str",
"=",
"'0x%-8X'",
"%",
"(",
"val",
")",
"if",
"key",
"==",
"'TimeDateStamp'",
"or",
"key",
"==",
"'dwTimeStamp'",
":",
"try",
":",
"val_str",
"+=",
"' [%s UTC]'",
"%",
"time",
".",
"asctime",
"(",
"time",
".",
"gmtime",
"(",
"val",
")",
")",
"except",
"exceptions",
".",
"ValueError",
",",
"e",
":",
"val_str",
"+=",
"' [INVALID TIME]'",
"else",
":",
"val_str",
"=",
"''",
".",
"join",
"(",
"filter",
"(",
"lambda",
"c",
":",
"c",
"!=",
"'\\0'",
",",
"str",
"(",
"val",
")",
")",
")",
"dump",
".",
"append",
"(",
"'%-30s %s'",
"%",
"(",
"key",
"+",
"':'",
",",
"val_str",
")",
")",
"return",
"dump"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/symsrc/pefile.py#L783-L808 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/animate.py | python | AnimationBase.GetDelay | (*args, **kwargs) | return _animate.AnimationBase_GetDelay(*args, **kwargs) | GetDelay(self, int i) -> int | GetDelay(self, int i) -> int | [
"GetDelay",
"(",
"self",
"int",
"i",
")",
"-",
">",
"int"
] | def GetDelay(*args, **kwargs):
"""GetDelay(self, int i) -> int"""
return _animate.AnimationBase_GetDelay(*args, **kwargs) | [
"def",
"GetDelay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_animate",
".",
"AnimationBase_GetDelay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/animate.py#L82-L84 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | MenuItem.GetLabelText | (*args, **kwargs) | return _core_.MenuItem_GetLabelText(*args, **kwargs) | GetLabelText(String label) -> String | GetLabelText(String label) -> String | [
"GetLabelText",
"(",
"String",
"label",
")",
"-",
">",
"String"
] | def GetLabelText(*args, **kwargs):
"""GetLabelText(String label) -> String"""
return _core_.MenuItem_GetLabelText(*args, **kwargs) | [
"def",
"GetLabelText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MenuItem_GetLabelText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12475-L12477 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Text.debug | (self, boolean=None) | Turn on the internal consistency checks of the B-Tree inside the text
widget according to BOOLEAN. | Turn on the internal consistency checks of the B-Tree inside the text
widget according to BOOLEAN. | [
"Turn",
"on",
"the",
"internal",
"consistency",
"checks",
"of",
"the",
"B",
"-",
"Tree",
"inside",
"the",
"text",
"widget",
"according",
"to",
"BOOLEAN",
"."
] | def debug(self, boolean=None):
"""Turn on the internal consistency checks of the B-Tree inside the text
widget according to BOOLEAN."""
if boolean is None:
return self.tk.getboolean(self.tk.call(self._w, 'debug'))
self.tk.call(self._w, 'debug', boolean) | [
"def",
"debug",
"(",
"self",
",",
"boolean",
"=",
"None",
")",
":",
"if",
"boolean",
"is",
"None",
":",
"return",
"self",
".",
"tk",
".",
"getboolean",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'debug'",
")",
")",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'debug'",
",",
"boolean",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3131-L3136 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/compiler-rt/lib/sanitizer_common/scripts/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/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L636-L638 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/utils.py | python | get_gcc_version | (path) | return exec_shell_cmd('gcc --version', path).splitlines()[0].split()[-1] | Return version of the GCC compiler installed in *path* | Return version of the GCC compiler installed in *path* | [
"Return",
"version",
"of",
"the",
"GCC",
"compiler",
"installed",
"in",
"*",
"path",
"*"
] | def get_gcc_version(path):
"""Return version of the GCC compiler installed in *path*"""
return exec_shell_cmd('gcc --version', path).splitlines()[0].split()[-1] | [
"def",
"get_gcc_version",
"(",
"path",
")",
":",
"return",
"exec_shell_cmd",
"(",
"'gcc --version'",
",",
"path",
")",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/utils.py#L205-L207 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchWall.py | python | _CommandWall.setContinue | (self,i) | Simple callback to set if the interactive mode will restart when finished.
This allows for several walls to be placed one after another. | Simple callback to set if the interactive mode will restart when finished. | [
"Simple",
"callback",
"to",
"set",
"if",
"the",
"interactive",
"mode",
"will",
"restart",
"when",
"finished",
"."
] | def setContinue(self,i):
"""Simple callback to set if the interactive mode will restart when finished.
This allows for several walls to be placed one after another.
"""
self.continueCmd = bool(i)
if hasattr(FreeCADGui,"draftToolBar"):
FreeCADGui.draftToolBar.continueMode = bool(i) | [
"def",
"setContinue",
"(",
"self",
",",
"i",
")",
":",
"self",
".",
"continueCmd",
"=",
"bool",
"(",
"i",
")",
"if",
"hasattr",
"(",
"FreeCADGui",
",",
"\"draftToolBar\"",
")",
":",
"FreeCADGui",
".",
"draftToolBar",
".",
"continueMode",
"=",
"bool",
"(",
"i",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchWall.py#L587-L595 | ||
Atarity/Lightpack | 4dee73a443cba4c4073291febe450e6c1941f3af | Software/apiexamples/liOSC/OSC.py | python | OSCServer.serverInfo_handler | (self, addr, tags, data, client_address) | return reply | Example handler for OSCMessages.
All registerd handlers must accept these three arguments:
- addr (string): The OSC-address pattern of the received Message
(the 'addr' string has already been matched against the handler's registerd OSC-address,
but may contain '*'s & such)
- tags (string): The OSC-typetags of the received message's arguments. (without the preceding comma)
- data (list): The OSCMessage's arguments
Note that len(tags) == len(data)
- client_address ((host, port) tuple): the host & port this message originated from.
a Message-handler function may return None, but it could also return an OSCMessage (or OSCBundle),
which then gets sent back to the client.
This handler returns a reply to the client, which can contain various bits of information
about this server, depending on the first argument of the received OSC-message:
- 'help' | 'info' : Reply contains server type & version info, plus a list of
available 'commands' understood by this handler
- 'list' | 'ls' : Reply is a bundle of 'address <string>' messages, listing the server's
OSC address-space.
- 'clients' | 'targets' : Reply is a bundle of 'target osc://<host>:<port>[<prefix>] [<filter>] [...]'
messages, listing the local Client-instance's subscribed remote clients. | Example handler for OSCMessages.
All registerd handlers must accept these three arguments:
- addr (string): The OSC-address pattern of the received Message
(the 'addr' string has already been matched against the handler's registerd OSC-address,
but may contain '*'s & such)
- tags (string): The OSC-typetags of the received message's arguments. (without the preceding comma)
- data (list): The OSCMessage's arguments
Note that len(tags) == len(data)
- client_address ((host, port) tuple): the host & port this message originated from.
a Message-handler function may return None, but it could also return an OSCMessage (or OSCBundle),
which then gets sent back to the client.
This handler returns a reply to the client, which can contain various bits of information
about this server, depending on the first argument of the received OSC-message:
- 'help' | 'info' : Reply contains server type & version info, plus a list of
available 'commands' understood by this handler
- 'list' | 'ls' : Reply is a bundle of 'address <string>' messages, listing the server's
OSC address-space.
- 'clients' | 'targets' : Reply is a bundle of 'target osc://<host>:<port>[<prefix>] [<filter>] [...]'
messages, listing the local Client-instance's subscribed remote clients. | [
"Example",
"handler",
"for",
"OSCMessages",
".",
"All",
"registerd",
"handlers",
"must",
"accept",
"these",
"three",
"arguments",
":",
"-",
"addr",
"(",
"string",
")",
":",
"The",
"OSC",
"-",
"address",
"pattern",
"of",
"the",
"received",
"Message",
"(",
"the",
"addr",
"string",
"has",
"already",
"been",
"matched",
"against",
"the",
"handler",
"s",
"registerd",
"OSC",
"-",
"address",
"but",
"may",
"contain",
"*",
"s",
"&",
"such",
")",
"-",
"tags",
"(",
"string",
")",
":",
"The",
"OSC",
"-",
"typetags",
"of",
"the",
"received",
"message",
"s",
"arguments",
".",
"(",
"without",
"the",
"preceding",
"comma",
")",
"-",
"data",
"(",
"list",
")",
":",
"The",
"OSCMessage",
"s",
"arguments",
"Note",
"that",
"len",
"(",
"tags",
")",
"==",
"len",
"(",
"data",
")",
"-",
"client_address",
"((",
"host",
"port",
")",
"tuple",
")",
":",
"the",
"host",
"&",
"port",
"this",
"message",
"originated",
"from",
".",
"a",
"Message",
"-",
"handler",
"function",
"may",
"return",
"None",
"but",
"it",
"could",
"also",
"return",
"an",
"OSCMessage",
"(",
"or",
"OSCBundle",
")",
"which",
"then",
"gets",
"sent",
"back",
"to",
"the",
"client",
".",
"This",
"handler",
"returns",
"a",
"reply",
"to",
"the",
"client",
"which",
"can",
"contain",
"various",
"bits",
"of",
"information",
"about",
"this",
"server",
"depending",
"on",
"the",
"first",
"argument",
"of",
"the",
"received",
"OSC",
"-",
"message",
":",
"-",
"help",
"|",
"info",
":",
"Reply",
"contains",
"server",
"type",
"&",
"version",
"info",
"plus",
"a",
"list",
"of",
"available",
"commands",
"understood",
"by",
"this",
"handler",
"-",
"list",
"|",
"ls",
":",
"Reply",
"is",
"a",
"bundle",
"of",
"address",
"<string",
">",
"messages",
"listing",
"the",
"server",
"s",
"OSC",
"address",
"-",
"space",
".",
"-",
"clients",
"|",
"targets",
":",
"Reply",
"is",
"a",
"bundle",
"of",
"target",
"osc",
":",
"//",
"<host",
">",
":",
"<port",
">",
"[",
"<prefix",
">",
"]",
"[",
"<filter",
">",
"]",
"[",
"...",
"]",
"messages",
"listing",
"the",
"local",
"Client",
"-",
"instance",
"s",
"subscribed",
"remote",
"clients",
"."
] | def serverInfo_handler(self, addr, tags, data, client_address):
"""Example handler for OSCMessages.
All registerd handlers must accept these three arguments:
- addr (string): The OSC-address pattern of the received Message
(the 'addr' string has already been matched against the handler's registerd OSC-address,
but may contain '*'s & such)
- tags (string): The OSC-typetags of the received message's arguments. (without the preceding comma)
- data (list): The OSCMessage's arguments
Note that len(tags) == len(data)
- client_address ((host, port) tuple): the host & port this message originated from.
a Message-handler function may return None, but it could also return an OSCMessage (or OSCBundle),
which then gets sent back to the client.
This handler returns a reply to the client, which can contain various bits of information
about this server, depending on the first argument of the received OSC-message:
- 'help' | 'info' : Reply contains server type & version info, plus a list of
available 'commands' understood by this handler
- 'list' | 'ls' : Reply is a bundle of 'address <string>' messages, listing the server's
OSC address-space.
- 'clients' | 'targets' : Reply is a bundle of 'target osc://<host>:<port>[<prefix>] [<filter>] [...]'
messages, listing the local Client-instance's subscribed remote clients.
"""
if len(data) == 0:
return None
cmd = data.pop(0)
reply = None
if cmd in ('help', 'info'):
reply = OSCBundle(self.info_prefix)
reply.append(('server', str(self)))
reply.append(('info_command', "ls | list : list OSC address-space"))
reply.append(('info_command', "clients | targets : list subscribed clients"))
elif cmd in ('ls', 'list'):
reply = OSCBundle(self.info_prefix)
for addr in self.callbacks.keys():
reply.append(('address', addr))
elif cmd in ('clients', 'targets'):
if hasattr(self.client, 'getOSCTargetStrings'):
reply = OSCBundle(self.info_prefix)
for trg in self.client.getOSCTargetStrings():
reply.append(('target',) + trg)
else:
cli_addr = self.client.address()
if cli_addr:
reply = OSCMessage(self.info_prefix)
reply.append(('target', "osc://%s/" % getUrlStr(cli_addr)))
else:
self.reportErr("unrecognized command '%s' in /info request from osc://%s. Try 'help'" % (cmd, getUrlStr(client_address)), client_address)
return reply | [
"def",
"serverInfo_handler",
"(",
"self",
",",
"addr",
",",
"tags",
",",
"data",
",",
"client_address",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"None",
"cmd",
"=",
"data",
".",
"pop",
"(",
"0",
")",
"reply",
"=",
"None",
"if",
"cmd",
"in",
"(",
"'help'",
",",
"'info'",
")",
":",
"reply",
"=",
"OSCBundle",
"(",
"self",
".",
"info_prefix",
")",
"reply",
".",
"append",
"(",
"(",
"'server'",
",",
"str",
"(",
"self",
")",
")",
")",
"reply",
".",
"append",
"(",
"(",
"'info_command'",
",",
"\"ls | list : list OSC address-space\"",
")",
")",
"reply",
".",
"append",
"(",
"(",
"'info_command'",
",",
"\"clients | targets : list subscribed clients\"",
")",
")",
"elif",
"cmd",
"in",
"(",
"'ls'",
",",
"'list'",
")",
":",
"reply",
"=",
"OSCBundle",
"(",
"self",
".",
"info_prefix",
")",
"for",
"addr",
"in",
"self",
".",
"callbacks",
".",
"keys",
"(",
")",
":",
"reply",
".",
"append",
"(",
"(",
"'address'",
",",
"addr",
")",
")",
"elif",
"cmd",
"in",
"(",
"'clients'",
",",
"'targets'",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"client",
",",
"'getOSCTargetStrings'",
")",
":",
"reply",
"=",
"OSCBundle",
"(",
"self",
".",
"info_prefix",
")",
"for",
"trg",
"in",
"self",
".",
"client",
".",
"getOSCTargetStrings",
"(",
")",
":",
"reply",
".",
"append",
"(",
"(",
"'target'",
",",
")",
"+",
"trg",
")",
"else",
":",
"cli_addr",
"=",
"self",
".",
"client",
".",
"address",
"(",
")",
"if",
"cli_addr",
":",
"reply",
"=",
"OSCMessage",
"(",
"self",
".",
"info_prefix",
")",
"reply",
".",
"append",
"(",
"(",
"'target'",
",",
"\"osc://%s/\"",
"%",
"getUrlStr",
"(",
"cli_addr",
")",
")",
")",
"else",
":",
"self",
".",
"reportErr",
"(",
"\"unrecognized command '%s' in /info request from osc://%s. Try 'help'\"",
"%",
"(",
"cmd",
",",
"getUrlStr",
"(",
"client_address",
")",
")",
",",
"client_address",
")",
"return",
"reply"
] | https://github.com/Atarity/Lightpack/blob/4dee73a443cba4c4073291febe450e6c1941f3af/Software/apiexamples/liOSC/OSC.py#L2065-L2116 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py | python | FlagValues.ShortestUniquePrefixes | (self, fl) | return shortest_matches | Returns: dictionary; maps flag names to their shortest unique prefix. | Returns: dictionary; maps flag names to their shortest unique prefix. | [
"Returns",
":",
"dictionary",
";",
"maps",
"flag",
"names",
"to",
"their",
"shortest",
"unique",
"prefix",
"."
] | def ShortestUniquePrefixes(self, fl):
"""Returns: dictionary; maps flag names to their shortest unique prefix."""
# Sort the list of flag names
sorted_flags = []
for name, flag in fl.items():
sorted_flags.append(name)
if flag.boolean:
sorted_flags.append('no%s' % name)
sorted_flags.sort()
# For each name in the sorted list, determine the shortest unique
# prefix by comparing itself to the next name and to the previous
# name (the latter check uses cached info from the previous loop).
shortest_matches = {}
prev_idx = 0
for flag_idx in range(len(sorted_flags)):
curr = sorted_flags[flag_idx]
if flag_idx == (len(sorted_flags) - 1):
next = None
else:
next = sorted_flags[flag_idx+1]
next_len = len(next)
for curr_idx in range(len(curr)):
if (next is None
or curr_idx >= next_len
or curr[curr_idx] != next[curr_idx]):
# curr longer than next or no more chars in common
shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1]
prev_idx = curr_idx
break
else:
# curr shorter than (or equal to) next
shortest_matches[curr] = curr
prev_idx = curr_idx + 1 # next will need at least one more char
return shortest_matches | [
"def",
"ShortestUniquePrefixes",
"(",
"self",
",",
"fl",
")",
":",
"# Sort the list of flag names",
"sorted_flags",
"=",
"[",
"]",
"for",
"name",
",",
"flag",
"in",
"fl",
".",
"items",
"(",
")",
":",
"sorted_flags",
".",
"append",
"(",
"name",
")",
"if",
"flag",
".",
"boolean",
":",
"sorted_flags",
".",
"append",
"(",
"'no%s'",
"%",
"name",
")",
"sorted_flags",
".",
"sort",
"(",
")",
"# For each name in the sorted list, determine the shortest unique",
"# prefix by comparing itself to the next name and to the previous",
"# name (the latter check uses cached info from the previous loop).",
"shortest_matches",
"=",
"{",
"}",
"prev_idx",
"=",
"0",
"for",
"flag_idx",
"in",
"range",
"(",
"len",
"(",
"sorted_flags",
")",
")",
":",
"curr",
"=",
"sorted_flags",
"[",
"flag_idx",
"]",
"if",
"flag_idx",
"==",
"(",
"len",
"(",
"sorted_flags",
")",
"-",
"1",
")",
":",
"next",
"=",
"None",
"else",
":",
"next",
"=",
"sorted_flags",
"[",
"flag_idx",
"+",
"1",
"]",
"next_len",
"=",
"len",
"(",
"next",
")",
"for",
"curr_idx",
"in",
"range",
"(",
"len",
"(",
"curr",
")",
")",
":",
"if",
"(",
"next",
"is",
"None",
"or",
"curr_idx",
">=",
"next_len",
"or",
"curr",
"[",
"curr_idx",
"]",
"!=",
"next",
"[",
"curr_idx",
"]",
")",
":",
"# curr longer than next or no more chars in common",
"shortest_matches",
"[",
"curr",
"]",
"=",
"curr",
"[",
":",
"max",
"(",
"prev_idx",
",",
"curr_idx",
")",
"+",
"1",
"]",
"prev_idx",
"=",
"curr_idx",
"break",
"else",
":",
"# curr shorter than (or equal to) next",
"shortest_matches",
"[",
"curr",
"]",
"=",
"curr",
"prev_idx",
"=",
"curr_idx",
"+",
"1",
"# next will need at least one more char",
"return",
"shortest_matches"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L1487-L1521 | |
OAID/Tengine | 66b2c22ad129d25e2fc6de3b22a608bb54dd90db | tools/optimize/segformer-opt.py | python | main | () | main function | main function | [
"main",
"function"
] | def main():
"""
main function
"""
print("---- Tengine Segformer Optimize Tool ----\n")
if args == None or args.input == None:
usage_info()
return None
print("Input model : %s" % (args.input))
print("Output model : %s" % (args.output))
print("Input tensor : %s" % (args.in_tensor))
print("Output tensor : %s" % (args.out_tensor))
in_tensor = args.in_tensor.split(',')
out_tensor = args.out_tensor.split(',')
# load original onnx model, graph, nodes
print("[Quant Tools Info]: Step 0, load original onnx model from %s." % (args.input))
onnx_model = onnx.load(args.input)
onnx_model, check = simplify(onnx_model)
graph = onnx_model.graph
init_dict = dict()
for init in onnx_model.graph.initializer:
init_dict[init.name]=init
# create the new nodes for optimize onnx model
old_node = graph.node
new_nodes = old_node[:-8]
# op fusion
print("[Quant Tools Info]: Step 1, fuse Gelu and LayerNorm.")
new_nodes = fusion_gelu(new_nodes)
new_nodes = fusion_layernorm(new_nodes,init_dict)
# rebuild new model, set the input and outputs nodes
print("[Quant Tools Info]: Step 2, Rebuild onnx graph nodes.")
del onnx_model.graph.node[:]
onnx_model.graph.node.extend(new_nodes)
# get input/output tensor index of value info
in_tensor_idx = [None] * len(in_tensor)
out_tensor_idx = [None] * len(out_tensor)
value = graph.value_info
for i, v in enumerate(value):
if v.name in in_tensor:
in_tensor_idx[in_tensor.index(v.name)] = i
if v.name in out_tensor:
out_tensor_idx[out_tensor.index(v.name)] = i
print("[Quant Tools Info]: Step 3, Update input and output tensor.")
keep_or_del_elem(onnx_model.graph.input, in_tensor, True)
for i in in_tensor_idx:
if i: onnx_model.graph.input.append(value[i])
keep_or_del_elem(onnx_model.graph.output, out_tensor, True)
for i in out_tensor_idx:
if i: onnx_model.graph.output.append(value[i])
# save the new optimize onnx model
print("[Quant Tools Info]: Step 4, save the new onnx model to %s." % (args.output))
onnx.save(onnx_model, args.output)
print("\n---- Tengine Segformer Optimize onnx create success, best wish for your inference has a high accuracy ...\\(^0^)/ ----") | [
"def",
"main",
"(",
")",
":",
"print",
"(",
"\"---- Tengine Segformer Optimize Tool ----\\n\"",
")",
"if",
"args",
"==",
"None",
"or",
"args",
".",
"input",
"==",
"None",
":",
"usage_info",
"(",
")",
"return",
"None",
"print",
"(",
"\"Input model : %s\"",
"%",
"(",
"args",
".",
"input",
")",
")",
"print",
"(",
"\"Output model : %s\"",
"%",
"(",
"args",
".",
"output",
")",
")",
"print",
"(",
"\"Input tensor : %s\"",
"%",
"(",
"args",
".",
"in_tensor",
")",
")",
"print",
"(",
"\"Output tensor : %s\"",
"%",
"(",
"args",
".",
"out_tensor",
")",
")",
"in_tensor",
"=",
"args",
".",
"in_tensor",
".",
"split",
"(",
"','",
")",
"out_tensor",
"=",
"args",
".",
"out_tensor",
".",
"split",
"(",
"','",
")",
"# load original onnx model, graph, nodes",
"print",
"(",
"\"[Quant Tools Info]: Step 0, load original onnx model from %s.\"",
"%",
"(",
"args",
".",
"input",
")",
")",
"onnx_model",
"=",
"onnx",
".",
"load",
"(",
"args",
".",
"input",
")",
"onnx_model",
",",
"check",
"=",
"simplify",
"(",
"onnx_model",
")",
"graph",
"=",
"onnx_model",
".",
"graph",
"init_dict",
"=",
"dict",
"(",
")",
"for",
"init",
"in",
"onnx_model",
".",
"graph",
".",
"initializer",
":",
"init_dict",
"[",
"init",
".",
"name",
"]",
"=",
"init",
"# create the new nodes for optimize onnx model",
"old_node",
"=",
"graph",
".",
"node",
"new_nodes",
"=",
"old_node",
"[",
":",
"-",
"8",
"]",
"# op fusion",
"print",
"(",
"\"[Quant Tools Info]: Step 1, fuse Gelu and LayerNorm.\"",
")",
"new_nodes",
"=",
"fusion_gelu",
"(",
"new_nodes",
")",
"new_nodes",
"=",
"fusion_layernorm",
"(",
"new_nodes",
",",
"init_dict",
")",
"# rebuild new model, set the input and outputs nodes",
"print",
"(",
"\"[Quant Tools Info]: Step 2, Rebuild onnx graph nodes.\"",
")",
"del",
"onnx_model",
".",
"graph",
".",
"node",
"[",
":",
"]",
"onnx_model",
".",
"graph",
".",
"node",
".",
"extend",
"(",
"new_nodes",
")",
"# get input/output tensor index of value info",
"in_tensor_idx",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"in_tensor",
")",
"out_tensor_idx",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"out_tensor",
")",
"value",
"=",
"graph",
".",
"value_info",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"value",
")",
":",
"if",
"v",
".",
"name",
"in",
"in_tensor",
":",
"in_tensor_idx",
"[",
"in_tensor",
".",
"index",
"(",
"v",
".",
"name",
")",
"]",
"=",
"i",
"if",
"v",
".",
"name",
"in",
"out_tensor",
":",
"out_tensor_idx",
"[",
"out_tensor",
".",
"index",
"(",
"v",
".",
"name",
")",
"]",
"=",
"i",
"print",
"(",
"\"[Quant Tools Info]: Step 3, Update input and output tensor.\"",
")",
"keep_or_del_elem",
"(",
"onnx_model",
".",
"graph",
".",
"input",
",",
"in_tensor",
",",
"True",
")",
"for",
"i",
"in",
"in_tensor_idx",
":",
"if",
"i",
":",
"onnx_model",
".",
"graph",
".",
"input",
".",
"append",
"(",
"value",
"[",
"i",
"]",
")",
"keep_or_del_elem",
"(",
"onnx_model",
".",
"graph",
".",
"output",
",",
"out_tensor",
",",
"True",
")",
"for",
"i",
"in",
"out_tensor_idx",
":",
"if",
"i",
":",
"onnx_model",
".",
"graph",
".",
"output",
".",
"append",
"(",
"value",
"[",
"i",
"]",
")",
"# save the new optimize onnx model",
"print",
"(",
"\"[Quant Tools Info]: Step 4, save the new onnx model to %s.\"",
"%",
"(",
"args",
".",
"output",
")",
")",
"onnx",
".",
"save",
"(",
"onnx_model",
",",
"args",
".",
"output",
")",
"print",
"(",
"\"\\n---- Tengine Segformer Optimize onnx create success, best wish for your inference has a high accuracy ...\\\\(^0^)/ ----\"",
")"
] | https://github.com/OAID/Tengine/blob/66b2c22ad129d25e2fc6de3b22a608bb54dd90db/tools/optimize/segformer-opt.py#L145-L209 | ||
nest/nest-simulator | f2623eb78518cdbd55e77e0ed486bf1111bcb62f | pynest/nest/lib/hl_api_spatial.py | python | _draw_extent | (ax, xctr, yctr, xext, yext) | Draw extent and set aspect ration, limits | Draw extent and set aspect ration, limits | [
"Draw",
"extent",
"and",
"set",
"aspect",
"ration",
"limits"
] | def _draw_extent(ax, xctr, yctr, xext, yext):
"""Draw extent and set aspect ration, limits"""
# import pyplot here and not at toplevel to avoid preventing users
# from changing matplotlib backend after importing nest
import matplotlib.pyplot as plt
# thin gray line indicating extent
llx, lly = xctr - xext / 2.0, yctr - yext / 2.0
urx, ury = llx + xext, lly + yext
ax.add_patch(
plt.Rectangle((llx, lly), xext, yext, fc='none', ec='0.5', lw=1,
zorder=1))
# set limits slightly outside extent
ax.set(aspect='equal',
xlim=(llx - 0.05 * xext, urx + 0.05 * xext),
ylim=(lly - 0.05 * yext, ury + 0.05 * yext),
xticks=tuple(), yticks=tuple()) | [
"def",
"_draw_extent",
"(",
"ax",
",",
"xctr",
",",
"yctr",
",",
"xext",
",",
"yext",
")",
":",
"# import pyplot here and not at toplevel to avoid preventing users",
"# from changing matplotlib backend after importing nest",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# thin gray line indicating extent",
"llx",
",",
"lly",
"=",
"xctr",
"-",
"xext",
"/",
"2.0",
",",
"yctr",
"-",
"yext",
"/",
"2.0",
"urx",
",",
"ury",
"=",
"llx",
"+",
"xext",
",",
"lly",
"+",
"yext",
"ax",
".",
"add_patch",
"(",
"plt",
".",
"Rectangle",
"(",
"(",
"llx",
",",
"lly",
")",
",",
"xext",
",",
"yext",
",",
"fc",
"=",
"'none'",
",",
"ec",
"=",
"'0.5'",
",",
"lw",
"=",
"1",
",",
"zorder",
"=",
"1",
")",
")",
"# set limits slightly outside extent",
"ax",
".",
"set",
"(",
"aspect",
"=",
"'equal'",
",",
"xlim",
"=",
"(",
"llx",
"-",
"0.05",
"*",
"xext",
",",
"urx",
"+",
"0.05",
"*",
"xext",
")",
",",
"ylim",
"=",
"(",
"lly",
"-",
"0.05",
"*",
"yext",
",",
"ury",
"+",
"0.05",
"*",
"yext",
")",
",",
"xticks",
"=",
"tuple",
"(",
")",
",",
"yticks",
"=",
"tuple",
"(",
")",
")"
] | https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/lib/hl_api_spatial.py#L849-L867 | ||
floatlazer/semantic_slam | 657814a1ba484de6b7f6f9d07c564566c8121f13 | semantic_cloud/include/ptsemseg/loader/pascal_voc_loader.py | python | pascalVOCLoader.get_pascal_labels | (self) | return np.asarray([[0,0,0], [128,0,0], [0,128,0], [128,128,0],
[0,0,128], [128,0,128], [0,128,128], [128,128,128],
[64,0,0], [192,0,0], [64,128,0], [192,128,0],
[64,0,128], [192,0,128], [64,128,128], [192,128,128],
[0, 64,0], [128, 64, 0], [0,192,0], [128,192,0],
[0,64,128]]) | Load the mapping that associates pascal classes with label colors
Returns:
np.ndarray with dimensions (21, 3) | Load the mapping that associates pascal classes with label colors | [
"Load",
"the",
"mapping",
"that",
"associates",
"pascal",
"classes",
"with",
"label",
"colors"
] | def get_pascal_labels(self):
"""Load the mapping that associates pascal classes with label colors
Returns:
np.ndarray with dimensions (21, 3)
"""
return np.asarray([[0,0,0], [128,0,0], [0,128,0], [128,128,0],
[0,0,128], [128,0,128], [0,128,128], [128,128,128],
[64,0,0], [192,0,0], [64,128,0], [192,128,0],
[64,0,128], [192,0,128], [64,128,128], [192,128,128],
[0, 64,0], [128, 64, 0], [0,192,0], [128,192,0],
[0,64,128]]) | [
"def",
"get_pascal_labels",
"(",
"self",
")",
":",
"return",
"np",
".",
"asarray",
"(",
"[",
"[",
"0",
",",
"0",
",",
"0",
"]",
",",
"[",
"128",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"128",
",",
"0",
"]",
",",
"[",
"128",
",",
"128",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"128",
"]",
",",
"[",
"128",
",",
"0",
",",
"128",
"]",
",",
"[",
"0",
",",
"128",
",",
"128",
"]",
",",
"[",
"128",
",",
"128",
",",
"128",
"]",
",",
"[",
"64",
",",
"0",
",",
"0",
"]",
",",
"[",
"192",
",",
"0",
",",
"0",
"]",
",",
"[",
"64",
",",
"128",
",",
"0",
"]",
",",
"[",
"192",
",",
"128",
",",
"0",
"]",
",",
"[",
"64",
",",
"0",
",",
"128",
"]",
",",
"[",
"192",
",",
"0",
",",
"128",
"]",
",",
"[",
"64",
",",
"128",
",",
"128",
"]",
",",
"[",
"192",
",",
"128",
",",
"128",
"]",
",",
"[",
"0",
",",
"64",
",",
"0",
"]",
",",
"[",
"128",
",",
"64",
",",
"0",
"]",
",",
"[",
"0",
",",
"192",
",",
"0",
"]",
",",
"[",
"128",
",",
"192",
",",
"0",
"]",
",",
"[",
"0",
",",
"64",
",",
"128",
"]",
"]",
")"
] | https://github.com/floatlazer/semantic_slam/blob/657814a1ba484de6b7f6f9d07c564566c8121f13/semantic_cloud/include/ptsemseg/loader/pascal_voc_loader.py#L116-L127 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/ciconfig/evergreen.py | python | Variant.is_required_variant | (self) | return self.display_name.startswith("! ") | Return True if the variant is a required variant. | Return True if the variant is a required variant. | [
"Return",
"True",
"if",
"the",
"variant",
"is",
"a",
"required",
"variant",
"."
] | def is_required_variant(self) -> bool:
"""Return True if the variant is a required variant."""
return self.display_name.startswith("! ") | [
"def",
"is_required_variant",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"display_name",
".",
"startswith",
"(",
"\"! \"",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/ciconfig/evergreen.py#L322-L324 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | SimJoint.addForce | (self, force: float) | return _robotsim.SimJoint_addForce(self, force) | r"""
Adds a torque for the hinge joint and a force for a slider joint.
Args:
force (float) | r"""
Adds a torque for the hinge joint and a force for a slider joint. | [
"r",
"Adds",
"a",
"torque",
"for",
"the",
"hinge",
"joint",
"and",
"a",
"force",
"for",
"a",
"slider",
"joint",
"."
] | def addForce(self, force: float) ->None:
r"""
Adds a torque for the hinge joint and a force for a slider joint.
Args:
force (float)
"""
return _robotsim.SimJoint_addForce(self, force) | [
"def",
"addForce",
"(",
"self",
",",
"force",
":",
"float",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"SimJoint_addForce",
"(",
"self",
",",
"force",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L7729-L7736 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | ScrolledCanvas.unbind | (self, *args, **kwargs) | 'forward' method, which canvas itself has inherited... | 'forward' method, which canvas itself has inherited... | [
"forward",
"method",
"which",
"canvas",
"itself",
"has",
"inherited",
"..."
] | def unbind(self, *args, **kwargs):
""" 'forward' method, which canvas itself has inherited...
"""
self._canvas.unbind(*args, **kwargs) | [
"def",
"unbind",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_canvas",
".",
"unbind",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L419-L422 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py | python | MaskedIterator.__next__ | (self) | return d | Return the next value, or raise StopIteration.
Examples
--------
>>> x = np.ma.array([3, 2], mask=[0, 1])
>>> fl = x.flat
>>> next(fl)
3
>>> next(fl)
masked
>>> next(fl)
Traceback (most recent call last):
...
StopIteration | Return the next value, or raise StopIteration. | [
"Return",
"the",
"next",
"value",
"or",
"raise",
"StopIteration",
"."
] | def __next__(self):
"""
Return the next value, or raise StopIteration.
Examples
--------
>>> x = np.ma.array([3, 2], mask=[0, 1])
>>> fl = x.flat
>>> next(fl)
3
>>> next(fl)
masked
>>> next(fl)
Traceback (most recent call last):
...
StopIteration
"""
d = next(self.dataiter)
if self.maskiter is not None:
m = next(self.maskiter)
if isinstance(m, np.void):
return mvoid(d, mask=m, hardmask=self.ma._hardmask)
elif m: # Just a scalar, masked
return masked
return d | [
"def",
"__next__",
"(",
"self",
")",
":",
"d",
"=",
"next",
"(",
"self",
".",
"dataiter",
")",
"if",
"self",
".",
"maskiter",
"is",
"not",
"None",
":",
"m",
"=",
"next",
"(",
"self",
".",
"maskiter",
")",
"if",
"isinstance",
"(",
"m",
",",
"np",
".",
"void",
")",
":",
"return",
"mvoid",
"(",
"d",
",",
"mask",
"=",
"m",
",",
"hardmask",
"=",
"self",
".",
"ma",
".",
"_hardmask",
")",
"elif",
"m",
":",
"# Just a scalar, masked",
"return",
"masked",
"return",
"d"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L2687-L2712 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.