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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/bnn_layers/conv_variational.py | python | ConvReparam._apply_variational_weight | (self, inputs) | return outputs | Calculate weight. | Calculate weight. | [
"Calculate",
"weight",
"."
] | def _apply_variational_weight(self, inputs):
"""Calculate weight."""
weight_posterior_tensor = self.weight_posterior("sample")
outputs = self.conv2d(inputs, weight_posterior_tensor)
return outputs | [
"def",
"_apply_variational_weight",
"(",
"self",
",",
"inputs",
")",
":",
"weight_posterior_tensor",
"=",
"self",
".",
"weight_posterior",
"(",
"\"sample\"",
")",
"outputs",
"=",
"self",
".",
"conv2d",
"(",
"inputs",
",",
"weight_posterior_tensor",
")",
"return",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/bnn_layers/conv_variational.py#L263-L267 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/filesystem.py | python | adjacent_tmp_file | (path, **kwargs) | Return a file-like object pointing to a tmp file next to path.
The file is created securely and is ensured to be written to disk
after the context reaches its end.
kwargs will be passed to tempfile.NamedTemporaryFile to control
the way the temporary file will be opened. | Return a file-like object pointing to a tmp file next to path. | [
"Return",
"a",
"file",
"-",
"like",
"object",
"pointing",
"to",
"a",
"tmp",
"file",
"next",
"to",
"path",
"."
] | def adjacent_tmp_file(path, **kwargs):
# type: (str, **Any) -> Iterator[BinaryIO]
"""Return a file-like object pointing to a tmp file next to path.
The file is created securely and is ensured to be written to disk
after the context reaches its end.
kwargs will be passed to tempfile.NamedTemporaryFile to control
the way the temporary file will be opened.
"""
with NamedTemporaryFile(
delete=False,
dir=os.path.dirname(path),
prefix=os.path.basename(path),
suffix='.tmp',
**kwargs
) as f:
result = cast('BinaryIO', f)
try:
yield result
finally:
result.flush()
os.fsync(result.fileno()) | [
"def",
"adjacent_tmp_file",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, **Any) -> Iterator[BinaryIO]",
"with",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
",",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"p... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/utils/filesystem.py#L163-L207 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-blocks/python/blocks/qa_rotator_cc.py | python | qa_rotator_cc._post_phase_inc_cmd | (self, new_phase_inc, offset=None) | Post phase increment update command to the rotator block | Post phase increment update command to the rotator block | [
"Post",
"phase",
"increment",
"update",
"command",
"to",
"the",
"rotator",
"block"
] | def _post_phase_inc_cmd(self, new_phase_inc, offset=None):
"""Post phase increment update command to the rotator block"""
cmd = pmt.make_dict()
cmd = pmt.dict_add(cmd, pmt.intern("inc"),
pmt.from_double(new_phase_inc))
if (offset is not None):
cmd = pmt.dict_add(cmd, pmt.intern("offset"),
pmt.from_uint64(offset))
self.rotator_cc.insert_tail(pmt.to_pmt("cmd"), cmd) | [
"def",
"_post_phase_inc_cmd",
"(",
"self",
",",
"new_phase_inc",
",",
"offset",
"=",
"None",
")",
":",
"cmd",
"=",
"pmt",
".",
"make_dict",
"(",
")",
"cmd",
"=",
"pmt",
".",
"dict_add",
"(",
"cmd",
",",
"pmt",
".",
"intern",
"(",
"\"inc\"",
")",
",",... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-blocks/python/blocks/qa_rotator_cc.py#L56-L64 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/optparse.py | python | OptionGroup.destroy | (self) | see OptionParser.destroy(). | see OptionParser.destroy(). | [
"see",
"OptionParser",
".",
"destroy",
"()",
"."
] | def destroy(self):
"""see OptionParser.destroy()."""
OptionContainer.destroy(self)
del self.option_list | [
"def",
"destroy",
"(",
"self",
")",
":",
"OptionContainer",
".",
"destroy",
"(",
"self",
")",
"del",
"self",
".",
"option_list"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/optparse.py#L1103-L1106 | ||
dmlc/xgboost | 2775c2a1abd4b5b759ff517617434c8b9aeb4cc0 | python-package/xgboost/dask.py | python | inplace_predict | ( # pylint: disable=unused-argument
client: "distributed.Client",
model: Union[TrainReturnT, Booster, "distributed.Future"],
data: _DaskCollection,
iteration_range: Tuple[int, int] = (0, 0),
predict_type: str = "value",
missing: float = numpy.nan,
validate_features: bool = True,
base_margin: Optional[_DaskCollection] = None,
strict_shape: bool = False,
) | return client.sync(
_inplace_predict_async, global_config=config.get_config(), **locals()
) | Inplace prediction. See doc in :py:meth:`xgboost.Booster.inplace_predict` for details.
.. versionadded:: 1.1.0
Parameters
----------
client:
Specify the dask client used for training. Use default client
returned from dask if it's set to None.
model:
See :py:func:`xgboost.dask.predict` for details.
data :
dask collection.
iteration_range:
See :py:meth:`xgboost.Booster.predict` for details.
predict_type:
See :py:meth:`xgboost.Booster.inplace_predict` for details.
missing:
Value in the input data which needs to be present as a missing
value. If None, defaults to np.nan.
base_margin:
See :py:obj:`xgboost.DMatrix` for details.
.. versionadded:: 1.4.0
strict_shape:
See :py:meth:`xgboost.Booster.predict` for details.
.. versionadded:: 1.4.0
Returns
-------
prediction :
When input data is ``dask.array.Array``, the return value is an array, when input
data is ``dask.dataframe.DataFrame``, return value can be
``dask.dataframe.Series``, ``dask.dataframe.DataFrame``, depending on the output
shape. | Inplace prediction. See doc in :py:meth:`xgboost.Booster.inplace_predict` for details. | [
"Inplace",
"prediction",
".",
"See",
"doc",
"in",
":",
"py",
":",
"meth",
":",
"xgboost",
".",
"Booster",
".",
"inplace_predict",
"for",
"details",
"."
] | def inplace_predict( # pylint: disable=unused-argument
client: "distributed.Client",
model: Union[TrainReturnT, Booster, "distributed.Future"],
data: _DaskCollection,
iteration_range: Tuple[int, int] = (0, 0),
predict_type: str = "value",
missing: float = numpy.nan,
validate_features: bool = True,
base_margin: Optional[_DaskCollection] = None,
strict_shape: bool = False,
) -> Any:
"""Inplace prediction. See doc in :py:meth:`xgboost.Booster.inplace_predict` for details.
.. versionadded:: 1.1.0
Parameters
----------
client:
Specify the dask client used for training. Use default client
returned from dask if it's set to None.
model:
See :py:func:`xgboost.dask.predict` for details.
data :
dask collection.
iteration_range:
See :py:meth:`xgboost.Booster.predict` for details.
predict_type:
See :py:meth:`xgboost.Booster.inplace_predict` for details.
missing:
Value in the input data which needs to be present as a missing
value. If None, defaults to np.nan.
base_margin:
See :py:obj:`xgboost.DMatrix` for details.
.. versionadded:: 1.4.0
strict_shape:
See :py:meth:`xgboost.Booster.predict` for details.
.. versionadded:: 1.4.0
Returns
-------
prediction :
When input data is ``dask.array.Array``, the return value is an array, when input
data is ``dask.dataframe.DataFrame``, return value can be
``dask.dataframe.Series``, ``dask.dataframe.DataFrame``, depending on the output
shape.
"""
_assert_dask_support()
client = _xgb_get_client(client)
# When used in asynchronous environment, the `client` object should have
# `asynchronous` attribute as True. When invoked by the skl interface, it's
# responsible for setting up the client.
return client.sync(
_inplace_predict_async, global_config=config.get_config(), **locals()
) | [
"def",
"inplace_predict",
"(",
"# pylint: disable=unused-argument",
"client",
":",
"\"distributed.Client\"",
",",
"model",
":",
"Union",
"[",
"TrainReturnT",
",",
"Booster",
",",
"\"distributed.Future\"",
"]",
",",
"data",
":",
"_DaskCollection",
",",
"iteration_range",... | https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/python-package/xgboost/dask.py#L1447-L1504 | |
SGL-UT/GPSTk | 2340ec1cbdbd0b80a204920127798697bc616b30 | swig/doxy2swig.py | python | Doxy2SWIG.add_text | (self, value) | Adds text corresponding to `value` into `self.pieces`. | Adds text corresponding to `value` into `self.pieces`. | [
"Adds",
"text",
"corresponding",
"to",
"value",
"into",
"self",
".",
"pieces",
"."
] | def add_text(self, value):
"""Adds text corresponding to `value` into `self.pieces`."""
if isinstance(value, (list, tuple)):
self.pieces.extend(value)
else:
self.pieces.append(value) | [
"def",
"add_text",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"self",
".",
"pieces",
".",
"extend",
"(",
"value",
")",
"else",
":",
"self",
".",
"pieces",
".",
"append",
"... | https://github.com/SGL-UT/GPSTk/blob/2340ec1cbdbd0b80a204920127798697bc616b30/swig/doxy2swig.py#L150-L155 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/btm_matcher.py | python | BottomMatcher.run | (self, leaves) | return results | The main interface with the bottom matcher. The tree is
traversed from the bottom using the constructed
automaton. Nodes are only checked once as the tree is
retraversed. When the automaton fails, we give it one more
shot(in case the above tree matches as a whole with the
rejected leaf), then we break for the next leaf. There is the
special case of multiple arguments(see code comments) where we
recheck the nodes
Args:
The leaves of the AST tree to be matched
Returns:
A dictionary of node matches with fixers as the keys | The main interface with the bottom matcher. The tree is
traversed from the bottom using the constructed
automaton. Nodes are only checked once as the tree is
retraversed. When the automaton fails, we give it one more
shot(in case the above tree matches as a whole with the
rejected leaf), then we break for the next leaf. There is the
special case of multiple arguments(see code comments) where we
recheck the nodes | [
"The",
"main",
"interface",
"with",
"the",
"bottom",
"matcher",
".",
"The",
"tree",
"is",
"traversed",
"from",
"the",
"bottom",
"using",
"the",
"constructed",
"automaton",
".",
"Nodes",
"are",
"only",
"checked",
"once",
"as",
"the",
"tree",
"is",
"retraverse... | def run(self, leaves):
"""The main interface with the bottom matcher. The tree is
traversed from the bottom using the constructed
automaton. Nodes are only checked once as the tree is
retraversed. When the automaton fails, we give it one more
shot(in case the above tree matches as a whole with the
rejected leaf), then we break for the next leaf. There is the
special case of multiple arguments(see code comments) where we
recheck the nodes
Args:
The leaves of the AST tree to be matched
Returns:
A dictionary of node matches with fixers as the keys
"""
current_ac_node = self.root
results = defaultdict(list)
for leaf in leaves:
current_ast_node = leaf
while current_ast_node:
current_ast_node.was_checked = True
for child in current_ast_node.children:
# multiple statements, recheck
if isinstance(child, pytree.Leaf) and child.value == u";":
current_ast_node.was_checked = False
break
if current_ast_node.type == 1:
#name
node_token = current_ast_node.value
else:
node_token = current_ast_node.type
if node_token in current_ac_node.transition_table:
#token matches
current_ac_node = current_ac_node.transition_table[node_token]
for fixer in current_ac_node.fixers:
if not fixer in results:
results[fixer] = []
results[fixer].append(current_ast_node)
else:
#matching failed, reset automaton
current_ac_node = self.root
if (current_ast_node.parent is not None
and current_ast_node.parent.was_checked):
#the rest of the tree upwards has been checked, next leaf
break
#recheck the rejected node once from the root
if node_token in current_ac_node.transition_table:
#token matches
current_ac_node = current_ac_node.transition_table[node_token]
for fixer in current_ac_node.fixers:
if not fixer in results.keys():
results[fixer] = []
results[fixer].append(current_ast_node)
current_ast_node = current_ast_node.parent
return results | [
"def",
"run",
"(",
"self",
",",
"leaves",
")",
":",
"current_ac_node",
"=",
"self",
".",
"root",
"results",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"leaf",
"in",
"leaves",
":",
"current_ast_node",
"=",
"leaf",
"while",
"current_ast_node",
":",
"curren... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/btm_matcher.py#L83-L142 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/quoprimime.py | python | _unquote_match | (match) | return unquote(s) | Turn a match in the form =AB to the ASCII character with value 0xab | Turn a match in the form =AB to the ASCII character with value 0xab | [
"Turn",
"a",
"match",
"in",
"the",
"form",
"=",
"AB",
"to",
"the",
"ASCII",
"character",
"with",
"value",
"0xab"
] | def _unquote_match(match):
"""Turn a match in the form =AB to the ASCII character with value 0xab"""
s = match.group(0)
return unquote(s) | [
"def",
"_unquote_match",
"(",
"match",
")",
":",
"s",
"=",
"match",
".",
"group",
"(",
"0",
")",
"return",
"unquote",
"(",
"s",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/quoprimime.py#L284-L287 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/series.py | python | _align_indices | (series_list, how="outer", allow_non_unique=False) | return result | Internal util to align the indices of a list of Series objects
series_list : list of Series objects
how : {"outer", "inner"}
If "outer", the values of the resulting index are the
unique values of the index obtained by concatenating
the indices of all the series.
If "inner", the values of the resulting index are
the values common to the indices of all series.
allow_non_unique : bool
Whether or not to allow non-unique valued indices in the input
series. | Internal util to align the indices of a list of Series objects | [
"Internal",
"util",
"to",
"align",
"the",
"indices",
"of",
"a",
"list",
"of",
"Series",
"objects"
] | def _align_indices(series_list, how="outer", allow_non_unique=False):
"""
Internal util to align the indices of a list of Series objects
series_list : list of Series objects
how : {"outer", "inner"}
If "outer", the values of the resulting index are the
unique values of the index obtained by concatenating
the indices of all the series.
If "inner", the values of the resulting index are
the values common to the indices of all series.
allow_non_unique : bool
Whether or not to allow non-unique valued indices in the input
series.
"""
if len(series_list) <= 1:
return series_list
# check if all indices are the same
head = series_list[0].index
all_index_equal = True
for sr in series_list[1:]:
if not sr.index.equals(head):
all_index_equal = False
break
# check if all names are the same
all_names_equal = True
for sr in series_list[1:]:
if not sr.index.names == head.names:
all_names_equal = False
new_index_names = [None] * head.nlevels
if all_names_equal:
new_index_names = head.names
if all_index_equal:
return series_list
if how == "outer":
combined_index = cudf.core.reshape.concat(
[sr.index for sr in series_list]
).unique()
combined_index.names = new_index_names
else:
combined_index = series_list[0].index
for sr in series_list[1:]:
combined_index = (
cudf.DataFrame(index=sr.index).join(
cudf.DataFrame(index=combined_index),
sort=True,
how="inner",
)
).index
combined_index.names = new_index_names
# align all Series to the combined index
result = [
sr._align_to_index(
combined_index, how=how, allow_non_unique=allow_non_unique
)
for sr in series_list
]
return result | [
"def",
"_align_indices",
"(",
"series_list",
",",
"how",
"=",
"\"outer\"",
",",
"allow_non_unique",
"=",
"False",
")",
":",
"if",
"len",
"(",
"series_list",
")",
"<=",
"1",
":",
"return",
"series_list",
"# check if all indices are the same",
"head",
"=",
"series... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/series.py#L4786-L4850 | |
Dobiasd/frugally-deep | 99d9378c6ef537a209bcb2a102e953899a6ab0e3 | keras_export/convert_model.py | python | show_tensor | (tens) | return {
'shape': tens.shape[1:],
'values': encode_floats(tens.flatten())
} | Serialize 3-tensor to a dict | Serialize 3-tensor to a dict | [
"Serialize",
"3",
"-",
"tensor",
"to",
"a",
"dict"
] | def show_tensor(tens):
"""Serialize 3-tensor to a dict"""
return {
'shape': tens.shape[1:],
'values': encode_floats(tens.flatten())
} | [
"def",
"show_tensor",
"(",
"tens",
")",
":",
"return",
"{",
"'shape'",
":",
"tens",
".",
"shape",
"[",
"1",
":",
"]",
",",
"'values'",
":",
"encode_floats",
"(",
"tens",
".",
"flatten",
"(",
")",
")",
"}"
] | https://github.com/Dobiasd/frugally-deep/blob/99d9378c6ef537a209bcb2a102e953899a6ab0e3/keras_export/convert_model.py#L84-L89 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlNode.searchNs | (self, doc, nameSpace) | return __tmp | Search a Ns registered under a given name space for a
document. recurse on the parents until it finds the defined
namespace or return None otherwise. @nameSpace can be None,
this is a search for the default namespace. We don't allow
to cross entities boundaries. If you don't declare the
namespace within those you will be in troubles !!! A
warning is generated to cover this case. | Search a Ns registered under a given name space for a
document. recurse on the parents until it finds the defined
namespace or return None otherwise. | [
"Search",
"a",
"Ns",
"registered",
"under",
"a",
"given",
"name",
"space",
"for",
"a",
"document",
".",
"recurse",
"on",
"the",
"parents",
"until",
"it",
"finds",
"the",
"defined",
"namespace",
"or",
"return",
"None",
"otherwise",
"."
] | def searchNs(self, doc, nameSpace):
"""Search a Ns registered under a given name space for a
document. recurse on the parents until it finds the defined
namespace or return None otherwise. @nameSpace can be None,
this is a search for the default namespace. We don't allow
to cross entities boundaries. If you don't declare the
namespace within those you will be in troubles !!! A
warning is generated to cover this case. """
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlSearchNs(doc__o, self._o, nameSpace)
if ret is None:raise treeError('xmlSearchNs() failed')
__tmp = xmlNs(_obj=ret)
return __tmp | [
"def",
"searchNs",
"(",
"self",
",",
"doc",
",",
"nameSpace",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlSearchNs",
"(",
"doc__o",
",",
"self",
"... | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L3455-L3468 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py | python | AttentionWrapper.call | (self, inputs, state) | Perform a step of attention-wrapped RNN.
- Step 1: Mix the `inputs` and previous step's `attention` output via
`cell_input_fn`.
- Step 2: Call the wrapped `cell` with this input and its previous state.
- Step 3: Score the cell's output with `attention_mechanism`.
- Step 4: Calculate the alignments by passing the score through the
`normalizer`.
- Step 5: Calculate the context vector as the inner product between the
alignments and the attention_mechanism's values (memory).
- Step 6: Calculate the attention output by concatenating the cell output
and context through the attention layer (a linear layer with
`attention_layer_size` outputs).
Args:
inputs: (Possibly nested tuple of) Tensor, the input at this time step.
state: An instance of `AttentionWrapperState` containing tensors from the
previous time step.
Returns:
A tuple `(attention_or_cell_output, next_state)`, where:
- `attention_or_cell_output` depending on `output_attention`.
- `next_state` is an instance of `AttentionWrapperState`
containing the state calculated at this time step.
Raises:
TypeError: If `state` is not an instance of `AttentionWrapperState`. | Perform a step of attention-wrapped RNN. | [
"Perform",
"a",
"step",
"of",
"attention",
"-",
"wrapped",
"RNN",
"."
] | def call(self, inputs, state):
"""Perform a step of attention-wrapped RNN.
- Step 1: Mix the `inputs` and previous step's `attention` output via
`cell_input_fn`.
- Step 2: Call the wrapped `cell` with this input and its previous state.
- Step 3: Score the cell's output with `attention_mechanism`.
- Step 4: Calculate the alignments by passing the score through the
`normalizer`.
- Step 5: Calculate the context vector as the inner product between the
alignments and the attention_mechanism's values (memory).
- Step 6: Calculate the attention output by concatenating the cell output
and context through the attention layer (a linear layer with
`attention_layer_size` outputs).
Args:
inputs: (Possibly nested tuple of) Tensor, the input at this time step.
state: An instance of `AttentionWrapperState` containing tensors from the
previous time step.
Returns:
A tuple `(attention_or_cell_output, next_state)`, where:
- `attention_or_cell_output` depending on `output_attention`.
- `next_state` is an instance of `AttentionWrapperState`
containing the state calculated at this time step.
Raises:
TypeError: If `state` is not an instance of `AttentionWrapperState`.
"""
if not isinstance(state, AttentionWrapperState):
raise TypeError("Expected state to be instance of AttentionWrapperState. "
"Received type %s instead." % type(state))
# Step 1: Calculate the true inputs to the cell based on the
# previous attention value.
cell_inputs = self._cell_input_fn(inputs, state.attention)
cell_state = state.cell_state
cell_output, next_cell_state = self._cell(cell_inputs, cell_state)
cell_batch_size = (
tensor_shape.dimension_value(cell_output.shape[0]) or
array_ops.shape(cell_output)[0])
error_message = (
"When applying AttentionWrapper %s: " % self.name +
"Non-matching batch sizes between the memory "
"(encoder output) and the query (decoder output). Are you using "
"the BeamSearchDecoder? You may need to tile your memory input via "
"the tf.contrib.seq2seq.tile_batch function with argument "
"multiple=beam_width.")
with ops.control_dependencies(
self._batch_size_checks(cell_batch_size, error_message)):
cell_output = array_ops.identity(cell_output, name="checked_cell_output")
if self._is_multi:
previous_attention_state = state.attention_state
previous_alignment_history = state.alignment_history
else:
previous_attention_state = [state.attention_state]
previous_alignment_history = [state.alignment_history]
all_alignments = []
all_attentions = []
all_attention_states = []
maybe_all_histories = []
for i, attention_mechanism in enumerate(self._attention_mechanisms):
attention, alignments, next_attention_state = self._attention_fn(
attention_mechanism, cell_output, previous_attention_state[i],
self._attention_layers[i] if self._attention_layers else None)
alignment_history = previous_alignment_history[i].write(
state.time, alignments) if self._alignment_history else ()
all_attention_states.append(next_attention_state)
all_alignments.append(alignments)
all_attentions.append(attention)
maybe_all_histories.append(alignment_history)
attention = array_ops.concat(all_attentions, 1)
next_state = AttentionWrapperState(
time=state.time + 1,
cell_state=next_cell_state,
attention=attention,
attention_state=self._item_or_tuple(all_attention_states),
alignments=self._item_or_tuple(all_alignments),
alignment_history=self._item_or_tuple(maybe_all_histories))
if self._output_attention:
return attention, next_state
else:
return cell_output, next_state | [
"def",
"call",
"(",
"self",
",",
"inputs",
",",
"state",
")",
":",
"if",
"not",
"isinstance",
"(",
"state",
",",
"AttentionWrapperState",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected state to be instance of AttentionWrapperState. \"",
"\"Received type %s instead.\""... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py#L2449-L2538 | ||
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/swift_build_sdk_interfaces.py | python | run_with_module_cache_retry | (command_args, module_cache_path, dry_run) | return (status, stdout, stderr) | Hack: runs a command several times, clearing the module cache if we get
an error about header files being modified during the run.
This shouldn't be necessary (the cached PCM files should automatically be
regenerated) but there seems to still be a bug in Clang that we haven't
tracked down yet. | Hack: runs a command several times, clearing the module cache if we get
an error about header files being modified during the run. | [
"Hack",
":",
"runs",
"a",
"command",
"several",
"times",
"clearing",
"the",
"module",
"cache",
"if",
"we",
"get",
"an",
"error",
"about",
"header",
"files",
"being",
"modified",
"during",
"the",
"run",
"."
] | def run_with_module_cache_retry(command_args, module_cache_path, dry_run):
"""Hack: runs a command several times, clearing the module cache if we get
an error about header files being modified during the run.
This shouldn't be necessary (the cached PCM files should automatically be
regenerated) but there seems to still be a bug in Clang that we haven't
tracked down yet.
"""
RETRIES = 3
attempts_stderr = ""
for r in range(RETRIES):
status, stdout, stderr = run_command(command_args, dry_run)
if status == 0:
break
if not should_retry_compilation(stderr):
break
if module_cache_path:
shutil.rmtree(module_cache_path, ignore_errors=True)
# If all retries fail, output information for each instance.
attempts_stderr += (
"\n*** Compilation attempt {}/{} failed with modules bugs. "
"Error output:\n".format(r + 1, RETRIES))
attempts_stderr += stderr
stderr = attempts_stderr
return (status, stdout, stderr) | [
"def",
"run_with_module_cache_retry",
"(",
"command_args",
",",
"module_cache_path",
",",
"dry_run",
")",
":",
"RETRIES",
"=",
"3",
"attempts_stderr",
"=",
"\"\"",
"for",
"r",
"in",
"range",
"(",
"RETRIES",
")",
":",
"status",
",",
"stdout",
",",
"stderr",
"... | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_sdk_interfaces.py#L201-L225 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/libs/metaparse/tools/string_headers.py | python | filename | (out_dir, name, undefine=False) | return os.path.join(out_dir, '{0}{1}.hpp'.format(prefix, name.lower())) | Generate the filename | Generate the filename | [
"Generate",
"the",
"filename"
] | def filename(out_dir, name, undefine=False):
"""Generate the filename"""
if undefine:
prefix = 'undef_'
else:
prefix = ''
return os.path.join(out_dir, '{0}{1}.hpp'.format(prefix, name.lower())) | [
"def",
"filename",
"(",
"out_dir",
",",
"name",
",",
"undefine",
"=",
"False",
")",
":",
"if",
"undefine",
":",
"prefix",
"=",
"'undef_'",
"else",
":",
"prefix",
"=",
"''",
"return",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"'{0}{1}.hpp'",
... | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/libs/metaparse/tools/string_headers.py#L118-L124 | |
openweave/openweave-core | 11ceb6b7efd39fe05de7f79229247a5774d56766 | src/device-manager/python/weave-device-mgr.py | python | DeviceMgrCmd.do_remotepassiverendezvous | (self, line) | remote-passive-rendezvous [ <options> ]
passive-rendezvous <pairing-code>
Options:
--pairing-code <pairing-code>
Specifies a pairing code string to be used to authenticate the device.
--access-token <access-token>
Specifies a base-64 encoded access token to be used to authenticate the device.
--use-dummy-access-token
Authenticate using the built-in dummy access token.
--joiner-address <joiner-address>
Specifies the expected IPv6 address of the joiner. The assisting device will not connect a remote device
to the client unless the remote device's address matches this value.
--rendezvous-timeout <rendezous-timeout>
Specifies a timeout in seconds for the completion of the Remote Passive Rendezvous. Both the Device
Manager and assisting device will close their end of the RPR connection if no remote host rendezvouses
with the assisting device prior to this timeout's expiration.
--inactivity-timeout <inactivity-timeout>
Specifies an inactivity timeout in seconds for use by the assisting device after the Remote Passive
Rendezvous completes. If the assisting device does not observe traffic across the tunnel from both
sides within a period of time equal to or great than this timeout, it will close the tunnel. | remote-passive-rendezvous [ <options> ]
passive-rendezvous <pairing-code> | [
"remote",
"-",
"passive",
"-",
"rendezvous",
"[",
"<options",
">",
"]",
"passive",
"-",
"rendezvous",
"<pairing",
"-",
"code",
">"
] | def do_remotepassiverendezvous(self, line):
"""
remote-passive-rendezvous [ <options> ]
passive-rendezvous <pairing-code>
Options:
--pairing-code <pairing-code>
Specifies a pairing code string to be used to authenticate the device.
--access-token <access-token>
Specifies a base-64 encoded access token to be used to authenticate the device.
--use-dummy-access-token
Authenticate using the built-in dummy access token.
--joiner-address <joiner-address>
Specifies the expected IPv6 address of the joiner. The assisting device will not connect a remote device
to the client unless the remote device's address matches this value.
--rendezvous-timeout <rendezous-timeout>
Specifies a timeout in seconds for the completion of the Remote Passive Rendezvous. Both the Device
Manager and assisting device will close their end of the RPR connection if no remote host rendezvouses
with the assisting device prior to this timeout's expiration.
--inactivity-timeout <inactivity-timeout>
Specifies an inactivity timeout in seconds for use by the assisting device after the Remote Passive
Rendezvous completes. If the assisting device does not observe traffic across the tunnel from both
sides within a period of time equal to or great than this timeout, it will close the tunnel.
"""
args = shlex.split(line)
optParser = OptionParser(usage=optparse.SUPPRESS_USAGE, option_class=ExtendedOption)
optParser.add_option("-p", "--pairing-code", action="store", dest="pairingCode", type="string")
optParser.add_option("-t", "--access-token", action="store", dest="accessToken", type="base64")
optParser.add_option("-d", "--use-dummy-access-token", action="store_true", dest="useDummyAccessToken")
optParser.add_option("-j", "--joiner-address", action="store", dest="joinerAddr", type="string")
optParser.add_option("-r", "--rendezvous-timeout", action="store", dest="rendezvousTimeout", type="int")
optParser.add_option("-i", "--inactivity-timeout", action="store", dest="inactivityTimeout", type="int")
try:
(options, remainingArgs) = optParser.parse_args(args)
except SystemExit:
return
if (len(remainingArgs) > 1):
print("Unexpected argument: " + remainingArgs[1])
return
if (len(remainingArgs) == 1):
options.pairingCode = remainingArgs[0]
if (options.useDummyAccessToken and not options.accessToken):
options.accessToken = base64.standard_b64decode(dummyAccessToken)
if (options.pairingCode and options.accessToken):
print("Cannot specify both pairing code and access token")
return
try:
self.devMgr.RemotePassiveRendezvous(rendezvousDeviceAddr=options.joinerAddr,
pairingCode=options.pairingCode, accessToken=options.accessToken,
rendezvousTimeout=options.rendezvousTimeout, inactivityTimeout=options.inactivityTimeout)
except WeaveStack.WeaveStackException as ex:
print(str(ex))
return
print("Successfully connected to remote device %X" % (self.devMgr.DeviceId())) | [
"def",
"do_remotepassiverendezvous",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"line",
")",
"optParser",
"=",
"OptionParser",
"(",
"usage",
"=",
"optparse",
".",
"SUPPRESS_USAGE",
",",
"option_class",
"=",
"ExtendedOption",
... | https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/weave-device-mgr.py#L916-L988 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.IndicatorSetStyle | (*args, **kwargs) | return _stc.StyledTextCtrl_IndicatorSetStyle(*args, **kwargs) | IndicatorSetStyle(self, int indic, int style)
Set an indicator to plain, squiggle or TT. | IndicatorSetStyle(self, int indic, int style) | [
"IndicatorSetStyle",
"(",
"self",
"int",
"indic",
"int",
"style",
")"
] | def IndicatorSetStyle(*args, **kwargs):
"""
IndicatorSetStyle(self, int indic, int style)
Set an indicator to plain, squiggle or TT.
"""
return _stc.StyledTextCtrl_IndicatorSetStyle(*args, **kwargs) | [
"def",
"IndicatorSetStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_IndicatorSetStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2865-L2871 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | python/lammps/numpy_wrapper.py | python | numpy_wrapper.extract_atom | (self, name, dtype=LAMMPS_AUTODETECT, nelem=LAMMPS_AUTODETECT, dim=LAMMPS_AUTODETECT) | return raw_ptr | Retrieve per-atom properties from LAMMPS as NumPy arrays
This is a wrapper around the :py:meth:`lammps.extract_atom()` method.
It behaves the same as the original method, but returns NumPy arrays
instead of ``ctypes`` pointers.
.. note::
While the returned arrays of per-atom data are dimensioned
for the range [0:nmax] - as is the underlying storage -
the data is usually only valid for the range of [0:nlocal],
unless the property of interest is also updated for ghost
atoms. In some cases, this depends on a LAMMPS setting, see
for example :doc:`comm_modify vel yes <comm_modify>`.
:param name: name of the property
:type name: string
:param dtype: type of the returned data (see :ref:`py_datatype_constants`)
:type dtype: int, optional
:param nelem: number of elements in array
:type nelem: int, optional
:param dim: dimension of each element
:type dim: int, optional
:return: requested data as NumPy array with direct access to C data or None
:rtype: numpy.array or NoneType | Retrieve per-atom properties from LAMMPS as NumPy arrays | [
"Retrieve",
"per",
"-",
"atom",
"properties",
"from",
"LAMMPS",
"as",
"NumPy",
"arrays"
] | def extract_atom(self, name, dtype=LAMMPS_AUTODETECT, nelem=LAMMPS_AUTODETECT, dim=LAMMPS_AUTODETECT):
"""Retrieve per-atom properties from LAMMPS as NumPy arrays
This is a wrapper around the :py:meth:`lammps.extract_atom()` method.
It behaves the same as the original method, but returns NumPy arrays
instead of ``ctypes`` pointers.
.. note::
While the returned arrays of per-atom data are dimensioned
for the range [0:nmax] - as is the underlying storage -
the data is usually only valid for the range of [0:nlocal],
unless the property of interest is also updated for ghost
atoms. In some cases, this depends on a LAMMPS setting, see
for example :doc:`comm_modify vel yes <comm_modify>`.
:param name: name of the property
:type name: string
:param dtype: type of the returned data (see :ref:`py_datatype_constants`)
:type dtype: int, optional
:param nelem: number of elements in array
:type nelem: int, optional
:param dim: dimension of each element
:type dim: int, optional
:return: requested data as NumPy array with direct access to C data or None
:rtype: numpy.array or NoneType
"""
if dtype == LAMMPS_AUTODETECT:
dtype = self.lmp.extract_atom_datatype(name)
if nelem == LAMMPS_AUTODETECT:
if name == "mass":
nelem = self.lmp.extract_global("ntypes") + 1
else:
nelem = self.lmp.extract_global("nlocal")
if dim == LAMMPS_AUTODETECT:
if dtype in (LAMMPS_INT_2D, LAMMPS_DOUBLE_2D, LAMMPS_INT64_2D):
# TODO add other fields
if name in ("x", "v", "f", "x0","omega", "angmom", "torque", "csforce", "vforce", "vest"):
dim = 3
elif name == "smd_data_9":
dim = 9
elif name == "smd_stress":
dim = 6
else:
dim = 2
else:
dim = 1
raw_ptr = self.lmp.extract_atom(name, dtype)
if dtype in (LAMMPS_DOUBLE, LAMMPS_DOUBLE_2D):
return self.darray(raw_ptr, nelem, dim)
elif dtype in (LAMMPS_INT, LAMMPS_INT_2D):
return self.iarray(c_int32, raw_ptr, nelem, dim)
elif dtype in (LAMMPS_INT64, LAMMPS_INT64_2D):
return self.iarray(c_int64, raw_ptr, nelem, dim)
return raw_ptr | [
"def",
"extract_atom",
"(",
"self",
",",
"name",
",",
"dtype",
"=",
"LAMMPS_AUTODETECT",
",",
"nelem",
"=",
"LAMMPS_AUTODETECT",
",",
"dim",
"=",
"LAMMPS_AUTODETECT",
")",
":",
"if",
"dtype",
"==",
"LAMMPS_AUTODETECT",
":",
"dtype",
"=",
"self",
".",
"lmp",
... | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/python/lammps/numpy_wrapper.py#L57-L114 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/preimage-size-of-factorial-zeroes-function.py | python | Solution.preimageSizeFZF | (self, K) | return p if count_of_factorial_primes(left, p) == K else 0 | :type K: int
:rtype: int | :type K: int
:rtype: int | [
":",
"type",
"K",
":",
"int",
":",
"rtype",
":",
"int"
] | def preimageSizeFZF(self, K):
"""
:type K: int
:rtype: int
"""
def count_of_factorial_primes(n, p):
cnt = 0
while n > 0:
cnt += n//p
n //= p
return cnt
p = 5
left, right = 0, p*K
while left <= right:
mid = left + (right-left)//2
if count_of_factorial_primes(mid, p) >= K:
right = mid-1
else:
left = mid+1
return p if count_of_factorial_primes(left, p) == K else 0 | [
"def",
"preimageSizeFZF",
"(",
"self",
",",
"K",
")",
":",
"def",
"count_of_factorial_primes",
"(",
"n",
",",
"p",
")",
":",
"cnt",
"=",
"0",
"while",
"n",
">",
"0",
":",
"cnt",
"+=",
"n",
"//",
"p",
"n",
"//=",
"p",
"return",
"cnt",
"p",
"=",
... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/preimage-size-of-factorial-zeroes-function.py#L5-L25 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | lldb/utils/lui/lldbutil.py | python | sort_stopped_threads | (process,
breakpoint_threads=None,
crashed_threads=None,
watchpoint_threads=None,
signal_threads=None,
exiting_threads=None,
other_threads=None) | Fills array *_threads with threads stopped for the corresponding stop
reason. | Fills array *_threads with threads stopped for the corresponding stop
reason. | [
"Fills",
"array",
"*",
"_threads",
"with",
"threads",
"stopped",
"for",
"the",
"corresponding",
"stop",
"reason",
"."
] | def sort_stopped_threads(process,
breakpoint_threads=None,
crashed_threads=None,
watchpoint_threads=None,
signal_threads=None,
exiting_threads=None,
other_threads=None):
""" Fills array *_threads with threads stopped for the corresponding stop
reason.
"""
for lst in [breakpoint_threads,
watchpoint_threads,
signal_threads,
exiting_threads,
other_threads]:
if lst is not None:
lst[:] = []
for thread in process:
dispatched = False
for (reason, list) in [(lldb.eStopReasonBreakpoint, breakpoint_threads),
(lldb.eStopReasonException, crashed_threads),
(lldb.eStopReasonWatchpoint, watchpoint_threads),
(lldb.eStopReasonSignal, signal_threads),
(lldb.eStopReasonThreadExiting, exiting_threads),
(None, other_threads)]:
if not dispatched and list is not None:
if thread.GetStopReason() == reason or reason is None:
list.append(thread)
dispatched = True | [
"def",
"sort_stopped_threads",
"(",
"process",
",",
"breakpoint_threads",
"=",
"None",
",",
"crashed_threads",
"=",
"None",
",",
"watchpoint_threads",
"=",
"None",
",",
"signal_threads",
"=",
"None",
",",
"exiting_threads",
"=",
"None",
",",
"other_threads",
"=",
... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/utils/lui/lldbutil.py#L285-L314 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_generator.py | python | _make_execution_function | (model, mode, class_weight=None) | return f | Makes function to run one step of model execution. | Makes function to run one step of model execution. | [
"Makes",
"function",
"to",
"run",
"one",
"step",
"of",
"model",
"execution",
"."
] | def _make_execution_function(model, mode, class_weight=None):
"""Makes function to run one step of model execution."""
if mode == ModeKeys.TRAIN:
f = functools.partial(model.train_on_batch, class_weight=class_weight)
elif mode == ModeKeys.TEST:
f = model.test_on_batch
else:
# Match signature of other modes to allow
# 1, 2, or 3-tuples from generator
def predict_on_batch(x, y=None, sample_weights=None): # pylint: disable=unused-argument
return model.predict_on_batch(x)
f = predict_on_batch
# Maintain stateful metrics across batch-level calls.
if mode != ModeKeys.PREDICT:
f = functools.partial(f, reset_metrics=False)
return f | [
"def",
"_make_execution_function",
"(",
"model",
",",
"mode",
",",
"class_weight",
"=",
"None",
")",
":",
"if",
"mode",
"==",
"ModeKeys",
".",
"TRAIN",
":",
"f",
"=",
"functools",
".",
"partial",
"(",
"model",
".",
"train_on_batch",
",",
"class_weight",
"=... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_generator.py#L525-L543 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/_pyio.py | python | FileIO.readinto | (self, b) | return n | Same as RawIOBase.readinto(). | Same as RawIOBase.readinto(). | [
"Same",
"as",
"RawIOBase",
".",
"readinto",
"()",
"."
] | def readinto(self, b):
"""Same as RawIOBase.readinto()."""
m = memoryview(b).cast('B')
data = self.read(len(m))
n = len(data)
m[:n] = data
return n | [
"def",
"readinto",
"(",
"self",
",",
"b",
")",
":",
"m",
"=",
"memoryview",
"(",
"b",
")",
".",
"cast",
"(",
"'B'",
")",
"data",
"=",
"self",
".",
"read",
"(",
"len",
"(",
"m",
")",
")",
"n",
"=",
"len",
"(",
"data",
")",
"m",
"[",
":",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pyio.py#L1689-L1695 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/substring-with-concatenation-of-all-words.py | python | Solution.findSubstring | (self, s, words) | return result | :type s: str
:type words: List[str]
:rtype: List[int] | :type s: str
:type words: List[str]
:rtype: List[int] | [
":",
"type",
"s",
":",
"str",
":",
"type",
"words",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if not words:
return []
result, m, n, k = [], len(s), len(words), len(words[0])
if m < n*k:
return result
lookup = collections.defaultdict(int)
for i in words:
lookup[i] += 1 # Space: O(n * k)
for i in xrange(k): # Time: O(k)
left, count = i, 0
tmp = collections.defaultdict(int)
for j in xrange(i, m-k+1, k): # Time: O(m / k)
s1 = s[j:j+k] # Time: O(k)
if s1 in lookup:
tmp[s1] += 1
count += 1
while tmp[s1] > lookup[s1]:
tmp[s[left:left+k]] -= 1
count -= 1
left += k
if count == n:
result.append(left)
else:
tmp = collections.defaultdict(int)
count = 0
left = j+k
return result | [
"def",
"findSubstring",
"(",
"self",
",",
"s",
",",
"words",
")",
":",
"if",
"not",
"words",
":",
"return",
"[",
"]",
"result",
",",
"m",
",",
"n",
",",
"k",
"=",
"[",
"]",
",",
"len",
"(",
"s",
")",
",",
"len",
"(",
"words",
")",
",",
"len... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/substring-with-concatenation-of-all-words.py#L8-L43 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/psro_v2/abstract_meta_trainer.py | python | AbstractMetaTrainer.__init__ | (self,
game,
oracle,
initial_policies=None,
meta_strategy_method=_DEFAULT_META_STRATEGY_METHOD,
training_strategy_selector=_DEFAULT_STRATEGY_SELECTION_METHOD,
symmetric_game=False,
number_policies_selected=1,
**kwargs) | Abstract Initialization for meta trainers.
Args:
game: A pyspiel game object.
oracle: An oracle object, from an implementation of the AbstractOracle
class.
initial_policies: A list of initial policies, to set up a default for
training. Resorts to tabular policies if not set.
meta_strategy_method: String, or callable taking a MetaTrainer object and
returning a list of meta strategies (One list entry per player).
String value can be:
- "uniform": Uniform distribution on policies.
- "nash": Taking nash distribution. Only works for 2 player, 0-sum
games.
- "prd": Projected Replicator Dynamics, as described in Lanctot et
Al.
training_strategy_selector: A callable or a string. If a callable, takes
as arguments: - An instance of `PSROSolver`, - a
`number_policies_selected` integer. and returning a list of
`num_players` lists of selected policies to train from.
When a string, supported values are:
- "top_k_probabilites": selects the first
'number_policies_selected' policies with highest selection
probabilities.
- "probabilistic": randomly selects 'number_policies_selected'
with probabilities determined by the meta strategies.
- "exhaustive": selects every policy of every player.
- "rectified": only selects strategies that have nonzero chance of
being selected.
- "uniform": randomly selects 'number_policies_selected' policies
with uniform probabilities.
symmetric_game: Whether to consider the current game as symmetric (True)
game or not (False).
number_policies_selected: Maximum number of new policies to train for each
player at each PSRO iteration.
**kwargs: kwargs for meta strategy computation and training strategy
selection | Abstract Initialization for meta trainers. | [
"Abstract",
"Initialization",
"for",
"meta",
"trainers",
"."
] | def __init__(self,
game,
oracle,
initial_policies=None,
meta_strategy_method=_DEFAULT_META_STRATEGY_METHOD,
training_strategy_selector=_DEFAULT_STRATEGY_SELECTION_METHOD,
symmetric_game=False,
number_policies_selected=1,
**kwargs):
"""Abstract Initialization for meta trainers.
Args:
game: A pyspiel game object.
oracle: An oracle object, from an implementation of the AbstractOracle
class.
initial_policies: A list of initial policies, to set up a default for
training. Resorts to tabular policies if not set.
meta_strategy_method: String, or callable taking a MetaTrainer object and
returning a list of meta strategies (One list entry per player).
String value can be:
- "uniform": Uniform distribution on policies.
- "nash": Taking nash distribution. Only works for 2 player, 0-sum
games.
- "prd": Projected Replicator Dynamics, as described in Lanctot et
Al.
training_strategy_selector: A callable or a string. If a callable, takes
as arguments: - An instance of `PSROSolver`, - a
`number_policies_selected` integer. and returning a list of
`num_players` lists of selected policies to train from.
When a string, supported values are:
- "top_k_probabilites": selects the first
'number_policies_selected' policies with highest selection
probabilities.
- "probabilistic": randomly selects 'number_policies_selected'
with probabilities determined by the meta strategies.
- "exhaustive": selects every policy of every player.
- "rectified": only selects strategies that have nonzero chance of
being selected.
- "uniform": randomly selects 'number_policies_selected' policies
with uniform probabilities.
symmetric_game: Whether to consider the current game as symmetric (True)
game or not (False).
number_policies_selected: Maximum number of new policies to train for each
player at each PSRO iteration.
**kwargs: kwargs for meta strategy computation and training strategy
selection
"""
self._iterations = 0
self._game = game
self._oracle = oracle
self._num_players = self._game.num_players()
self.symmetric_game = symmetric_game
self._game_num_players = self._num_players
self._num_players = 1 if symmetric_game else self._num_players
self._number_policies_selected = number_policies_selected
meta_strategy_method = _process_string_or_callable(
meta_strategy_method, meta_strategies.META_STRATEGY_METHODS)
print("Using {} as strategy method.".format(meta_strategy_method))
self._training_strategy_selector = _process_string_or_callable(
training_strategy_selector,
strategy_selectors.TRAINING_STRATEGY_SELECTORS)
print("Using {} as training strategy selector.".format(
self._training_strategy_selector))
self._meta_strategy_method = meta_strategy_method
self._kwargs = kwargs
self._initialize_policy(initial_policies)
self._initialize_game_state()
self.update_meta_strategies() | [
"def",
"__init__",
"(",
"self",
",",
"game",
",",
"oracle",
",",
"initial_policies",
"=",
"None",
",",
"meta_strategy_method",
"=",
"_DEFAULT_META_STRATEGY_METHOD",
",",
"training_strategy_selector",
"=",
"_DEFAULT_STRATEGY_SELECTION_METHOD",
",",
"symmetric_game",
"=",
... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/psro_v2/abstract_meta_trainer.py#L102-L175 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py | python | KScriptGenerator.setCallWeighting | (self, weight) | Sets the probably of generating a function call | Sets the probably of generating a function call | [
"Sets",
"the",
"probably",
"of",
"generating",
"a",
"function",
"call"
] | def setCallWeighting(self, weight):
""" Sets the probably of generating a function call"""
self.callWeighting = weight | [
"def",
"setCallWeighting",
"(",
"self",
",",
"weight",
")",
":",
"self",
".",
"callWeighting",
"=",
"weight"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py#L82-L84 | ||
facebook/wangle | 2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3 | build/fbcode_builder/shell_quoting.py | python | raw_shell | (s) | Not a member of ShellQuoted so we get a useful error for raw strings | Not a member of ShellQuoted so we get a useful error for raw strings | [
"Not",
"a",
"member",
"of",
"ShellQuoted",
"so",
"we",
"get",
"a",
"useful",
"error",
"for",
"raw",
"strings"
] | def raw_shell(s):
"Not a member of ShellQuoted so we get a useful error for raw strings"
if isinstance(s, ShellQuoted):
return s.do_not_use_raw_str
raise RuntimeError("{0} should have been ShellQuoted".format(s)) | [
"def",
"raw_shell",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"ShellQuoted",
")",
":",
"return",
"s",
".",
"do_not_use_raw_str",
"raise",
"RuntimeError",
"(",
"\"{0} should have been ShellQuoted\"",
".",
"format",
"(",
"s",
")",
")"
] | https://github.com/facebook/wangle/blob/2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3/build/fbcode_builder/shell_quoting.py#L77-L81 | ||
cocos2d/cocos2d-js | f0a7d4fa454de7076c054b677a36c5968a160901 | build/android-build.py | python | get_num_of_cpu | () | The build process can be accelerated by running multiple concurrent job processes using the -j-option. | The build process can be accelerated by running multiple concurrent job processes using the -j-option. | [
"The",
"build",
"process",
"can",
"be",
"accelerated",
"by",
"running",
"multiple",
"concurrent",
"job",
"processes",
"using",
"the",
"-",
"j",
"-",
"option",
"."
] | def get_num_of_cpu():
''' The build process can be accelerated by running multiple concurrent job processes using the -j-option.
'''
try:
platform = sys.platform
if platform == 'win32':
if 'NUMBER_OF_PROCESSORS' in os.environ:
return int(os.environ['NUMBER_OF_PROCESSORS'])
else:
return 1
else:
from numpy.distutils import cpuinfo
return cpuinfo.cpu._getNCPUs()
except Exception:
print "Can't know cpuinfo, use default 1 cpu"
return 1 | [
"def",
"get_num_of_cpu",
"(",
")",
":",
"try",
":",
"platform",
"=",
"sys",
".",
"platform",
"if",
"platform",
"==",
"'win32'",
":",
"if",
"'NUMBER_OF_PROCESSORS'",
"in",
"os",
".",
"environ",
":",
"return",
"int",
"(",
"os",
".",
"environ",
"[",
"'NUMBE... | https://github.com/cocos2d/cocos2d-js/blob/f0a7d4fa454de7076c054b677a36c5968a160901/build/android-build.py#L11-L26 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/logging.py | python | IndentingFormatter.format | (self, record) | return formatted | Calls the standard formatter, but will indent all of the log messages
by our current indentation level. | Calls the standard formatter, but will indent all of the log messages
by our current indentation level. | [
"Calls",
"the",
"standard",
"formatter",
"but",
"will",
"indent",
"all",
"of",
"the",
"log",
"messages",
"by",
"our",
"current",
"indentation",
"level",
"."
] | def format(self, record):
"""
Calls the standard formatter, but will indent all of the log messages
by our current indentation level.
"""
formatted = super(IndentingFormatter, self).format(record)
prefix = ''
if self.add_timestamp:
prefix = self.formatTime(record, "%Y-%m-%dT%H:%M:%S ")
prefix += " " * get_indentation()
formatted = "".join([
prefix + line
for line in formatted.splitlines(True)
])
return formatted | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"formatted",
"=",
"super",
"(",
"IndentingFormatter",
",",
"self",
")",
".",
"format",
"(",
"record",
")",
"prefix",
"=",
"''",
"if",
"self",
".",
"add_timestamp",
":",
"prefix",
"=",
"self",
".",
... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/logging.py#L103-L117 | |
genn-team/genn | 75e1eb218cafa228bf36ae4613d1ce26e877b12c | pygenn/genn_model.py | python | GeNNModel.pull_var_from_device | (self, pop_name, var_name) | Pull variable from the device for a given population | Pull variable from the device for a given population | [
"Pull",
"variable",
"from",
"the",
"device",
"for",
"a",
"given",
"population"
] | def pull_var_from_device(self, pop_name, var_name):
"""Pull variable from the device for a given population"""
if not self._loaded:
raise Exception("GeNN model has to be loaded before pulling")
self._slm.pull_var_from_device(pop_name, var_name) | [
"def",
"pull_var_from_device",
"(",
"self",
",",
"pop_name",
",",
"var_name",
")",
":",
"if",
"not",
"self",
".",
"_loaded",
":",
"raise",
"Exception",
"(",
"\"GeNN model has to be loaded before pulling\"",
")",
"self",
".",
"_slm",
".",
"pull_var_from_device",
"(... | https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_model.py#L748-L753 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/PositionalEmbedding.py | python | PositionalEmbedding.type | (self) | return self.types[self._internal.get_type()] | Gets the type of operation the layer performs. | Gets the type of operation the layer performs. | [
"Gets",
"the",
"type",
"of",
"operation",
"the",
"layer",
"performs",
"."
] | def type(self):
"""Gets the type of operation the layer performs.
"""
return self.types[self._internal.get_type()] | [
"def",
"type",
"(",
"self",
")",
":",
"return",
"self",
".",
"types",
"[",
"self",
".",
"_internal",
".",
"get_type",
"(",
")",
"]"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/PositionalEmbedding.py#L84-L87 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/handlers.py | python | SocketHandler.makeSocket | (self, timeout=1) | return s | A factory method which allows subclasses to define the precise
type of socket they want. | A factory method which allows subclasses to define the precise
type of socket they want. | [
"A",
"factory",
"method",
"which",
"allows",
"subclasses",
"to",
"define",
"the",
"precise",
"type",
"of",
"socket",
"they",
"want",
"."
] | def makeSocket(self, timeout=1):
"""
A factory method which allows subclasses to define the precise
type of socket they want.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if hasattr(s, 'settimeout'):
s.settimeout(timeout)
s.connect((self.host, self.port))
return s | [
"def",
"makeSocket",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"if",
"hasattr",
"(",
"s",
",",
"'settimeout'",
")",
":",
"s",
".",
"set... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/handlers.py#L466-L475 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Diffraction/isis_powder/routines/common.py | python | generate_summed_runs | (empty_sample_ws_string, instrument, scale_factor=None) | return empty_sample | Loads the list of empty runs specified by the empty_sample_ws_string and sums
them (and optionally scales). Returns the summed workspace.
:param empty_sample_ws_string: The empty run numbers to sum
:param instrument: The instrument object these runs belong to
:param scale_factor: The percentage to scale the loaded runs by
:return: The summed and normalised empty runs | Loads the list of empty runs specified by the empty_sample_ws_string and sums
them (and optionally scales). Returns the summed workspace.
:param empty_sample_ws_string: The empty run numbers to sum
:param instrument: The instrument object these runs belong to
:param scale_factor: The percentage to scale the loaded runs by
:return: The summed and normalised empty runs | [
"Loads",
"the",
"list",
"of",
"empty",
"runs",
"specified",
"by",
"the",
"empty_sample_ws_string",
"and",
"sums",
"them",
"(",
"and",
"optionally",
"scales",
")",
".",
"Returns",
"the",
"summed",
"workspace",
".",
":",
"param",
"empty_sample_ws_string",
":",
"... | def generate_summed_runs(empty_sample_ws_string, instrument, scale_factor=None):
"""
Loads the list of empty runs specified by the empty_sample_ws_string and sums
them (and optionally scales). Returns the summed workspace.
:param empty_sample_ws_string: The empty run numbers to sum
:param instrument: The instrument object these runs belong to
:param scale_factor: The percentage to scale the loaded runs by
:return: The summed and normalised empty runs
"""
empty_sample = load_current_normalised_ws_list(run_number_string=empty_sample_ws_string, instrument=instrument,
input_batching=INPUT_BATCHING.Summed)
empty_sample = empty_sample[0]
if scale_factor:
empty_sample = mantid.Scale(InputWorkspace=empty_sample, OutputWorkspace=empty_sample, Factor=scale_factor,
Operation="Multiply")
return empty_sample | [
"def",
"generate_summed_runs",
"(",
"empty_sample_ws_string",
",",
"instrument",
",",
"scale_factor",
"=",
"None",
")",
":",
"empty_sample",
"=",
"load_current_normalised_ws_list",
"(",
"run_number_string",
"=",
"empty_sample_ws_string",
",",
"instrument",
"=",
"instrumen... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Diffraction/isis_powder/routines/common.py#L501-L517 | |
facebookresearch/mvfst-rl | 778bc4259ae7277e67c2ead593a493845c93db83 | train/utils.py | python | get_slurm_constraint | (partition: str, gpus_per_node: int) | return None | Return the constraint to be used by the `submitit_slurm` launcher | Return the constraint to be used by the `submitit_slurm` launcher | [
"Return",
"the",
"constraint",
"to",
"be",
"used",
"by",
"the",
"submitit_slurm",
"launcher"
] | def get_slurm_constraint(partition: str, gpus_per_node: int) -> Optional[str]:
"""Return the constraint to be used by the `submitit_slurm` launcher"""
if partition in ["priority", "learnfair"] and gpus_per_node <= 2:
# If we are on the right environment, use constraint "gpu2".
host = socket.gethostname()
if host.startswith("devfair") and len(host) == 11: # H2?
return "gpu2"
return None | [
"def",
"get_slurm_constraint",
"(",
"partition",
":",
"str",
",",
"gpus_per_node",
":",
"int",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"partition",
"in",
"[",
"\"priority\"",
",",
"\"learnfair\"",
"]",
"and",
"gpus_per_node",
"<=",
"2",
":",
"# ... | https://github.com/facebookresearch/mvfst-rl/blob/778bc4259ae7277e67c2ead593a493845c93db83/train/utils.py#L201-L208 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/json_schema_compiler/code.py | python | Code.Sblock | (self, line='') | return self | Starts a code block.
Appends a line of code and then increases the indent level. | Starts a code block. | [
"Starts",
"a",
"code",
"block",
"."
] | def Sblock(self, line=''):
"""Starts a code block.
Appends a line of code and then increases the indent level.
"""
self.Append(line)
self._indent_level += self._indent_size
return self | [
"def",
"Sblock",
"(",
"self",
",",
"line",
"=",
"''",
")",
":",
"self",
".",
"Append",
"(",
"line",
")",
"self",
".",
"_indent_level",
"+=",
"self",
".",
"_indent_size",
"return",
"self"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/json_schema_compiler/code.py#L57-L64 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Build.py | python | inst.post_run | (self) | Disables any post-run operations | Disables any post-run operations | [
"Disables",
"any",
"post",
"-",
"run",
"operations"
] | def post_run(self):
"""
Disables any post-run operations
"""
pass | [
"def",
"post_run",
"(",
"self",
")",
":",
"pass"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Build.py#L1050-L1054 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/setobj.py | python | _SetPayload._iterate | (self, start=None) | Iterate over the payload's entries. Yield a SetLoop. | Iterate over the payload's entries. Yield a SetLoop. | [
"Iterate",
"over",
"the",
"payload",
"s",
"entries",
".",
"Yield",
"a",
"SetLoop",
"."
] | def _iterate(self, start=None):
"""
Iterate over the payload's entries. Yield a SetLoop.
"""
context = self._context
builder = self._builder
intp_t = context.get_value_type(types.intp)
one = ir.Constant(intp_t, 1)
size = builder.add(self.mask, one)
with cgutils.for_range(builder, size, start=start) as range_loop:
entry = self.get_entry(range_loop.index)
is_used = is_hash_used(context, builder, entry.hash)
with builder.if_then(is_used):
loop = SetLoop(index=range_loop.index, entry=entry,
do_break=range_loop.do_break)
yield loop | [
"def",
"_iterate",
"(",
"self",
",",
"start",
"=",
"None",
")",
":",
"context",
"=",
"self",
".",
"_context",
"builder",
"=",
"self",
".",
"_builder",
"intp_t",
"=",
"context",
".",
"get_value_type",
"(",
"types",
".",
"intp",
")",
"one",
"=",
"ir",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/setobj.py#L290-L307 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | python | Duration.FromJsonString | (self, value) | Converts a string to Duration.
Args:
value: A string to be converted. The string must end with 's'. Any
fractional digits (or none) are accepted as long as they fit into
precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s
Raises:
ParseError: On parsing problems. | Converts a string to Duration. | [
"Converts",
"a",
"string",
"to",
"Duration",
"."
] | def FromJsonString(self, value):
"""Converts a string to Duration.
Args:
value: A string to be converted. The string must end with 's'. Any
fractional digits (or none) are accepted as long as they fit into
precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s
Raises:
ParseError: On parsing problems.
"""
if len(value) < 1 or value[-1] != 's':
raise ParseError(
'Duration must end with letter "s": {0}.'.format(value))
try:
pos = value.find('.')
if pos == -1:
seconds = int(value[:-1])
nanos = 0
else:
seconds = int(value[:pos])
if value[0] == '-':
nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9))
else:
nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9))
_CheckDurationValid(seconds, nanos)
self.seconds = seconds
self.nanos = nanos
except ValueError:
raise ParseError(
'Couldn\'t parse duration: {0}.'.format(value)) | [
"def",
"FromJsonString",
"(",
"self",
",",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"<",
"1",
"or",
"value",
"[",
"-",
"1",
"]",
"!=",
"'s'",
":",
"raise",
"ParseError",
"(",
"'Duration must end with letter \"s\": {0}.'",
".",
"format",
"(",
"v... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L274-L304 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/serve/http_io.py | python | Response.AddJsonStrBody | (self, status_code, results) | Adds json-formatted body using results-value as a json-string.
Builds json-formatted response adding json-formatted string 'results'
as results.
Format: {"status_code": status_code, "results": results)}
Args:
status_code: status code of request processing.
results: json-formatted string to be added as results into response. | Adds json-formatted body using results-value as a json-string. | [
"Adds",
"json",
"-",
"formatted",
"body",
"using",
"results",
"-",
"value",
"as",
"a",
"json",
"-",
"string",
"."
] | def AddJsonStrBody(self, status_code, results):
"""Adds json-formatted body using results-value as a json-string.
Builds json-formatted response adding json-formatted string 'results'
as results.
Format: {"status_code": status_code, "results": results)}
Args:
status_code: status code of request processing.
results: json-formatted string to be added as results into response.
"""
assert status_code != constants.STATUS_FAILURE
assert isinstance(results, str)
self.body.append("""{"%s": %s, "%s": %s}""" % (
constants.HDR_JSON_STATUS_CODE, status_code,
constants.HDR_JSON_RESULTS, results)) | [
"def",
"AddJsonStrBody",
"(",
"self",
",",
"status_code",
",",
"results",
")",
":",
"assert",
"status_code",
"!=",
"constants",
".",
"STATUS_FAILURE",
"assert",
"isinstance",
"(",
"results",
",",
"str",
")",
"self",
".",
"body",
".",
"append",
"(",
"\"\"\"{\... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/http_io.py#L221-L236 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/media.py | python | MediaCtrl.GetDownloadTotal | (*args, **kwargs) | return _media.MediaCtrl_GetDownloadTotal(*args, **kwargs) | GetDownloadTotal(self) -> wxFileOffset | GetDownloadTotal(self) -> wxFileOffset | [
"GetDownloadTotal",
"(",
"self",
")",
"-",
">",
"wxFileOffset"
] | def GetDownloadTotal(*args, **kwargs):
"""GetDownloadTotal(self) -> wxFileOffset"""
return _media.MediaCtrl_GetDownloadTotal(*args, **kwargs) | [
"def",
"GetDownloadTotal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_media",
".",
"MediaCtrl_GetDownloadTotal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/media.py#L174-L176 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/buttonpanel.py | python | BPArt.SetFont | (self, id, font) | Sets the option value for the specified font `id`.
:param integer `id`: the identification bit for the font value;
:param `colour`: the new value for the font (a valid :class:`Font` instance).
:raise: `Exception` if the `id` is not recognized.
:see: :meth:`~BPArt.GetFont` for a list of meaningful font ids. | Sets the option value for the specified font `id`. | [
"Sets",
"the",
"option",
"value",
"for",
"the",
"specified",
"font",
"id",
"."
] | def SetFont(self, id, font):
"""
Sets the option value for the specified font `id`.
:param integer `id`: the identification bit for the font value;
:param `colour`: the new value for the font (a valid :class:`Font` instance).
:raise: `Exception` if the `id` is not recognized.
:see: :meth:`~BPArt.GetFont` for a list of meaningful font ids.
"""
if id == BP_TEXT_FONT:
self._caption_font = font
elif id == BP_BUTTONTEXT_FONT:
self._buttontext_font = font | [
"def",
"SetFont",
"(",
"self",
",",
"id",
",",
"font",
")",
":",
"if",
"id",
"==",
"BP_TEXT_FONT",
":",
"self",
".",
"_caption_font",
"=",
"font",
"elif",
"id",
"==",
"BP_BUTTONTEXT_FONT",
":",
"self",
".",
"_buttontext_font",
"=",
"font"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L547-L562 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/autoexpand.py | python | AutoExpand.expand_word_event | (self, event) | return "break" | Replace the current word with the next expansion. | Replace the current word with the next expansion. | [
"Replace",
"the",
"current",
"word",
"with",
"the",
"next",
"expansion",
"."
] | def expand_word_event(self, event):
"Replace the current word with the next expansion."
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
if not self.state:
words = self.getwords()
index = 0
else:
words, index, insert, line = self.state
if insert != curinsert or line != curline:
words = self.getwords()
index = 0
if not words:
self.bell()
return "break"
word = self.getprevword()
self.text.delete("insert - %d chars" % len(word), "insert")
newword = words[index]
index = (index + 1) % len(words)
if index == 0:
self.bell() # Warn we cycled around
self.text.insert("insert", newword)
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
self.state = words, index, curinsert, curline
return "break" | [
"def",
"expand_word_event",
"(",
"self",
",",
"event",
")",
":",
"curinsert",
"=",
"self",
".",
"text",
".",
"index",
"(",
"\"insert\"",
")",
"curline",
"=",
"self",
".",
"text",
".",
"get",
"(",
"\"insert linestart\"",
",",
"\"insert lineend\"",
")",
"if"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/autoexpand.py#L27-L52 | |
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/python_message.py | python | _AddMessageMethods | (message_descriptor, cls) | Adds implementations of all Message methods to cls. | Adds implementations of all Message methods to cls. | [
"Adds",
"implementations",
"of",
"all",
"Message",
"methods",
"to",
"cls",
"."
] | def _AddMessageMethods(message_descriptor, cls):
"""Adds implementations of all Message methods to cls."""
_AddListFieldsMethod(message_descriptor, cls)
_AddHasFieldMethod(message_descriptor, cls)
_AddClearFieldMethod(message_descriptor, cls)
if message_descriptor.is_extendable:
_AddClearExtensionMethod(cls)
_AddHasExtensionMethod(cls)
_AddClearMethod(message_descriptor, cls)
_AddEqualsMethod(message_descriptor, cls)
_AddStrMethod(message_descriptor, cls)
_AddUnicodeMethod(message_descriptor, cls)
_AddSetListenerMethod(cls)
_AddByteSizeMethod(message_descriptor, cls)
_AddSerializeToStringMethod(message_descriptor, cls)
_AddSerializePartialToStringMethod(message_descriptor, cls)
_AddMergeFromStringMethod(message_descriptor, cls)
_AddIsInitializedMethod(message_descriptor, cls)
_AddMergeFromMethod(cls) | [
"def",
"_AddMessageMethods",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"_AddListFieldsMethod",
"(",
"message_descriptor",
",",
"cls",
")",
"_AddHasFieldMethod",
"(",
"message_descriptor",
",",
"cls",
")",
"_AddClearFieldMethod",
"(",
"message_descriptor",
",",
... | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/python_message.py#L956-L974 | ||
tomahawk-player/tomahawk-resolvers | 7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d | archive/spotify/breakpad/third_party/protobuf/protobuf/python/mox.py | python | MockAnything.__getattr__ | (self, method_name) | return self._CreateMockMethod(method_name) | Intercept method calls on this object.
A new MockMethod is returned that is aware of the MockAnything's
state (record or replay). The call will be recorded or replayed
by the MockMethod's __call__.
Args:
# method name: the name of the method being called.
method_name: str
Returns:
A new MockMethod aware of MockAnything's state (record or replay). | Intercept method calls on this object. | [
"Intercept",
"method",
"calls",
"on",
"this",
"object",
"."
] | def __getattr__(self, method_name):
"""Intercept method calls on this object.
A new MockMethod is returned that is aware of the MockAnything's
state (record or replay). The call will be recorded or replayed
by the MockMethod's __call__.
Args:
# method name: the name of the method being called.
method_name: str
Returns:
A new MockMethod aware of MockAnything's state (record or replay).
"""
return self._CreateMockMethod(method_name) | [
"def",
"__getattr__",
"(",
"self",
",",
"method_name",
")",
":",
"return",
"self",
".",
"_CreateMockMethod",
"(",
"method_name",
")"
] | https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/mox.py#L278-L293 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | PhysicsTools/PatAlgos/python/tools/helpers.py | python | jetCollectionString | (prefix='', algo='', type='') | return jetCollectionString | ------------------------------------------------------------------
return the string of the jet collection module depending on the
input vaules. The default return value will be 'patAK5CaloJets'.
algo : indicating the algorithm type of the jet [expected are
'AK5', 'IC5', 'SC7', ...]
type : indicating the type of constituents of the jet [expec-
ted are 'Calo', 'PFlow', 'JPT', ...]
prefix : prefix indicating the type of pat collection module (ex-
pected are '', 'selected', 'clean').
------------------------------------------------------------------ | ------------------------------------------------------------------
return the string of the jet collection module depending on the
input vaules. The default return value will be 'patAK5CaloJets'. | [
"------------------------------------------------------------------",
"return",
"the",
"string",
"of",
"the",
"jet",
"collection",
"module",
"depending",
"on",
"the",
"input",
"vaules",
".",
"The",
"default",
"return",
"value",
"will",
"be",
"patAK5CaloJets",
"."
] | def jetCollectionString(prefix='', algo='', type=''):
"""
------------------------------------------------------------------
return the string of the jet collection module depending on the
input vaules. The default return value will be 'patAK5CaloJets'.
algo : indicating the algorithm type of the jet [expected are
'AK5', 'IC5', 'SC7', ...]
type : indicating the type of constituents of the jet [expec-
ted are 'Calo', 'PFlow', 'JPT', ...]
prefix : prefix indicating the type of pat collection module (ex-
pected are '', 'selected', 'clean').
------------------------------------------------------------------
"""
if(prefix==''):
jetCollectionString ='pat'
else:
jetCollectionString =prefix
jetCollectionString+='Pat'
jetCollectionString+='Jets'
jetCollectionString+=algo
jetCollectionString+=type
return jetCollectionString | [
"def",
"jetCollectionString",
"(",
"prefix",
"=",
"''",
",",
"algo",
"=",
"''",
",",
"type",
"=",
"''",
")",
":",
"if",
"(",
"prefix",
"==",
"''",
")",
":",
"jetCollectionString",
"=",
"'pat'",
"else",
":",
"jetCollectionString",
"=",
"prefix",
"jetColle... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/PatAlgos/python/tools/helpers.py#L217-L239 | |
wywu/LAB | 4b6debd302ae109fd104d4dd04dccc3418ae7471 | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | BatchLoader.load_next_image | (self) | return self.transformer.preprocess(im), multilabel | Load the next image in a batch. | Load the next image in a batch. | [
"Load",
"the",
"next",
"image",
"in",
"a",
"batch",
"."
] | def load_next_image(self):
"""
Load the next image in a batch.
"""
# Did we finish an epoch?
if self._cur == len(self.indexlist):
self._cur = 0
shuffle(self.indexlist)
# Load an image
index = self.indexlist[self._cur] # Get the image index
image_file_name = index + '.jpg'
im = np.asarray(Image.open(
osp.join(self.pascal_root, 'JPEGImages', image_file_name)))
im = scipy.misc.imresize(im, self.im_shape) # resize
# do a simple horizontal flip as data augmentation
flip = np.random.choice(2)*2-1
im = im[:, ::flip, :]
# Load and prepare ground truth
multilabel = np.zeros(20).astype(np.float32)
anns = load_pascal_annotation(index, self.pascal_root)
for label in anns['gt_classes']:
# in the multilabel problem we don't care how MANY instances
# there are of each class. Only if they are present.
# The "-1" is b/c we are not interested in the background
# class.
multilabel[label - 1] = 1
self._cur += 1
return self.transformer.preprocess(im), multilabel | [
"def",
"load_next_image",
"(",
"self",
")",
":",
"# Did we finish an epoch?",
"if",
"self",
".",
"_cur",
"==",
"len",
"(",
"self",
".",
"indexlist",
")",
":",
"self",
".",
"_cur",
"=",
"0",
"shuffle",
"(",
"self",
".",
"indexlist",
")",
"# Load an image",
... | https://github.com/wywu/LAB/blob/4b6debd302ae109fd104d4dd04dccc3418ae7471/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L106-L137 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/checkperms/checkperms.py | python | has_shebang_or_is_elf | (full_path) | Returns if the file starts with #!/ or is an ELF binary.
full_path is the absolute path to the file. | Returns if the file starts with #!/ or is an ELF binary. | [
"Returns",
"if",
"the",
"file",
"starts",
"with",
"#!",
"/",
"or",
"is",
"an",
"ELF",
"binary",
"."
] | def has_shebang_or_is_elf(full_path):
"""Returns if the file starts with #!/ or is an ELF binary.
full_path is the absolute path to the file.
"""
with open(full_path, 'rb') as f:
data = f.read(4)
return (data[:3] == '#!/', data == '\x7fELF') | [
"def",
"has_shebang_or_is_elf",
"(",
"full_path",
")",
":",
"with",
"open",
"(",
"full_path",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
"4",
")",
"return",
"(",
"data",
"[",
":",
"3",
"]",
"==",
"'#!/'",
",",
"data",
"... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/checkperms/checkperms.py#L291-L298 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/__init__.py | python | Distribution.get_entry_info | (self, group, name) | return self.get_entry_map(group).get(name) | Return the EntryPoint object for `group`+`name`, or ``None`` | Return the EntryPoint object for `group`+`name`, or ``None`` | [
"Return",
"the",
"EntryPoint",
"object",
"for",
"group",
"+",
"name",
"or",
"None"
] | def get_entry_info(self, group, name):
"""Return the EntryPoint object for `group`+`name`, or ``None``"""
return self.get_entry_map(group).get(name) | [
"def",
"get_entry_info",
"(",
"self",
",",
"group",
",",
"name",
")",
":",
"return",
"self",
".",
"get_entry_map",
"(",
"group",
")",
".",
"get",
"(",
"name",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/__init__.py#L2875-L2877 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStrUtil_GetStdName | (*args) | return _snap.TStrUtil_GetStdName(*args) | TStrUtil_GetStdName(TStr AuthorName) -> TStr
Parameters:
AuthorName: TStr | TStrUtil_GetStdName(TStr AuthorName) -> TStr | [
"TStrUtil_GetStdName",
"(",
"TStr",
"AuthorName",
")",
"-",
">",
"TStr"
] | def TStrUtil_GetStdName(*args):
"""
TStrUtil_GetStdName(TStr AuthorName) -> TStr
Parameters:
AuthorName: TStr
"""
return _snap.TStrUtil_GetStdName(*args) | [
"def",
"TStrUtil_GetStdName",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStrUtil_GetStdName",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L7502-L7510 | |
plumonito/dtslam | 5994bb9cf7a11981b830370db206bceb654c085d | 3rdparty/opencv-git/3rdparty/jinja2/parser.py | python | Parser.parse_assign_target | (self, with_tuple=True, name_only=False,
extra_end_rules=None) | return target | Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function. | Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function. | [
"Parse",
"an",
"assignment",
"target",
".",
"As",
"Jinja2",
"allows",
"assignments",
"to",
"tuples",
"this",
"function",
"can",
"parse",
"all",
"allowed",
"assignment",
"targets",
".",
"Per",
"default",
"assignments",
"to",
"tuples",
"are",
"parsed",
"that",
"... | def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None):
"""Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function.
"""
if name_only:
token = self.stream.expect('name')
target = nodes.Name(token.value, 'store', lineno=token.lineno)
else:
if with_tuple:
target = self.parse_tuple(simplified=True,
extra_end_rules=extra_end_rules)
else:
target = self.parse_primary()
target.set_ctx('store')
if not target.can_assign():
self.fail('can\'t assign to %r' % target.__class__.
__name__.lower(), target.lineno)
return target | [
"def",
"parse_assign_target",
"(",
"self",
",",
"with_tuple",
"=",
"True",
",",
"name_only",
"=",
"False",
",",
"extra_end_rules",
"=",
"None",
")",
":",
"if",
"name_only",
":",
"token",
"=",
"self",
".",
"stream",
".",
"expect",
"(",
"'name'",
")",
"tar... | https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/3rdparty/jinja2/parser.py#L356-L378 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | DC.GetCGContext | (*args, **kwargs) | return _gdi_.DC_GetCGContext(*args, **kwargs) | GetCGContext(self) -> void | GetCGContext(self) -> void | [
"GetCGContext",
"(",
"self",
")",
"-",
">",
"void"
] | def GetCGContext(*args, **kwargs):
"""GetCGContext(self) -> void"""
return _gdi_.DC_GetCGContext(*args, **kwargs) | [
"def",
"GetCGContext",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_GetCGContext",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L4640-L4642 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetRcflags | (self, config, gyp_to_ninja_path) | return rcflags | Returns the flags that need to be added to invocations of the resource
compiler. | Returns the flags that need to be added to invocations of the resource
compiler. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
"invocations",
"of",
"the",
"resource",
"compiler",
"."
] | def GetRcflags(self, config, gyp_to_ninja_path):
"""Returns the flags that need to be added to invocations of the resource
compiler."""
config = self._TargetConfig(config)
rcflags = []
rc = self._GetWrapper(
self, self.msvs_settings[config], "VCResourceCompilerTool", append=rcflags
)
rc("AdditionalIncludeDirectories", map=gyp_to_ninja_path, prefix="/I")
rcflags.append("/I" + gyp_to_ninja_path("."))
rc("PreprocessorDefinitions", prefix="/d")
# /l arg must be in hex without leading '0x'
rc("Culture", prefix="/l", map=lambda x: hex(int(x))[2:])
return rcflags | [
"def",
"GetRcflags",
"(",
"self",
",",
"config",
",",
"gyp_to_ninja_path",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"rcflags",
"=",
"[",
"]",
"rc",
"=",
"self",
".",
"_GetWrapper",
"(",
"self",
",",
"self",
".",
"msvs_... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/msvs_emulation.py#L907-L920 | |
logcabin/logcabin | ee6c55ae9744b82b451becd9707d26c7c1b6bbfb | scripts/cpplint.py | python | FileInfo.FullName | (self) | return os.path.abspath(self._filename).replace('\\', '/') | Make Windows paths like Unix. | Make Windows paths like Unix. | [
"Make",
"Windows",
"paths",
"like",
"Unix",
"."
] | def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/') | [
"def",
"FullName",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"_filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | https://github.com/logcabin/logcabin/blob/ee6c55ae9744b82b451becd9707d26c7c1b6bbfb/scripts/cpplint.py#L644-L646 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-thci/OpenThread.py | python | OpenThreadTHCI.__getMlIid | (self) | return mliid | get the Mesh Local IID. | get the Mesh Local IID. | [
"get",
"the",
"Mesh",
"Local",
"IID",
"."
] | def __getMlIid(self):
"""get the Mesh Local IID."""
print('%s call __getMlIid' % self.port)
# getULA64() would return the full string representation
mleid = ModuleHelper.GetFullIpv6Address(self.getULA64()).lower()
mliid = mleid[-19:].replace(':', '')
print('mliid: %s' % mliid)
return mliid | [
"def",
"__getMlIid",
"(",
"self",
")",
":",
"print",
"(",
"'%s call __getMlIid'",
"%",
"self",
".",
"port",
")",
"# getULA64() would return the full string representation",
"mleid",
"=",
"ModuleHelper",
".",
"GetFullIpv6Address",
"(",
"self",
".",
"getULA64",
"(",
"... | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread.py#L3291-L3298 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/control_flow_ops.py | python | vectorized_map | (fn, elems) | return pfor(loop_fn, batch_size) | Parallel map on the list of tensors unpacked from `elems` on dimension 0.
This method works similar to tf.map_fn but is optimized to run much faster,
possibly with a much larger memory footprint. The speedups are obtained by
vectorization (see https://arxiv.org/pdf/1903.04243.pdf). The idea behind
vectorization is to semantically launch all the invocations of `fn` in
parallel and fuse corresponding operations across all these invocations. This
fusion is done statically at graph generation time and the generated code is
often similar in performance to a manually fused version.
Because `tf.vectorized_map` fully parallelizes the batch, this method will
generally be significantly faster than using `tf.map_fn`, especially in eager
mode. However this is an experimental feature and currently has a lot of
limitations:
- There should be no data dependency between the different semantic
invocations of `fn`, i.e. it should be safe to map the elements of the
inputs in any order.
- Stateful kernels may mostly not be supported since these often imply a
data dependency. We do support a limited set of such stateful kernels
though (like RandomFoo, Variable operations like reads, etc).
- `fn` has limited support for control flow operations. `tf.cond` in
particular is not supported.
- `fn` should return nested structure of Tensors or Operations. However
if an Operation is returned, it should have zero outputs.
- The shape and dtype of any intermediate or output tensors in the
computation of `fn` should not depend on the input to `fn`.
Args:
fn: The callable to be performed. It accepts one argument, which will have
the same (possibly nested) structure as `elems`, and returns a possibly
nested structure of Tensors and Operations, which may be different than
the structure of `elems`.
elems: A tensor or (possibly nested) sequence of tensors, each of which will
be unpacked along their first dimension. The nested sequence of the
resulting slices will be mapped over by `fn`.
Returns:
A tensor or (possibly nested) sequence of tensors. Each tensor packs the
results of applying fn to tensors unpacked from elems along the first
dimension, from first to last.
Examples:
```python
def outer_product(a):
return tf.tensordot(a, a, 0)
batch_size = 100
a = tf.ones((batch_size, 32, 32))
c = tf.vectorized_map(outer_product, a)
assert c.shape == (batch_size, 32, 32, 32, 32)
```
```python
# Computing per-example gradients
batch_size = 10
num_features = 32
layer = tf.keras.layers.Dense(1)
def model_fn(arg):
with tf.GradientTape() as g:
inp, label = arg
inp = tf.expand_dims(inp, 0)
label = tf.expand_dims(label, 0)
prediction = layer(inp)
loss = tf.nn.l2_loss(label - prediction)
return g.gradient(loss, (layer.kernel, layer.bias))
inputs = tf.random_uniform([batch_size, num_features])
labels = tf.random_uniform([batch_size, 1])
per_example_gradients = tf.vectorized_map(model_fn, (inputs, labels))
assert per_example_gradients[0].shape == (batch_size, num_features, 1)
assert per_example_gradients[1].shape == (batch_size, 1)
``` | Parallel map on the list of tensors unpacked from `elems` on dimension 0. | [
"Parallel",
"map",
"on",
"the",
"list",
"of",
"tensors",
"unpacked",
"from",
"elems",
"on",
"dimension",
"0",
"."
] | def vectorized_map(fn, elems):
"""Parallel map on the list of tensors unpacked from `elems` on dimension 0.
This method works similar to tf.map_fn but is optimized to run much faster,
possibly with a much larger memory footprint. The speedups are obtained by
vectorization (see https://arxiv.org/pdf/1903.04243.pdf). The idea behind
vectorization is to semantically launch all the invocations of `fn` in
parallel and fuse corresponding operations across all these invocations. This
fusion is done statically at graph generation time and the generated code is
often similar in performance to a manually fused version.
Because `tf.vectorized_map` fully parallelizes the batch, this method will
generally be significantly faster than using `tf.map_fn`, especially in eager
mode. However this is an experimental feature and currently has a lot of
limitations:
- There should be no data dependency between the different semantic
invocations of `fn`, i.e. it should be safe to map the elements of the
inputs in any order.
- Stateful kernels may mostly not be supported since these often imply a
data dependency. We do support a limited set of such stateful kernels
though (like RandomFoo, Variable operations like reads, etc).
- `fn` has limited support for control flow operations. `tf.cond` in
particular is not supported.
- `fn` should return nested structure of Tensors or Operations. However
if an Operation is returned, it should have zero outputs.
- The shape and dtype of any intermediate or output tensors in the
computation of `fn` should not depend on the input to `fn`.
Args:
fn: The callable to be performed. It accepts one argument, which will have
the same (possibly nested) structure as `elems`, and returns a possibly
nested structure of Tensors and Operations, which may be different than
the structure of `elems`.
elems: A tensor or (possibly nested) sequence of tensors, each of which will
be unpacked along their first dimension. The nested sequence of the
resulting slices will be mapped over by `fn`.
Returns:
A tensor or (possibly nested) sequence of tensors. Each tensor packs the
results of applying fn to tensors unpacked from elems along the first
dimension, from first to last.
Examples:
```python
def outer_product(a):
return tf.tensordot(a, a, 0)
batch_size = 100
a = tf.ones((batch_size, 32, 32))
c = tf.vectorized_map(outer_product, a)
assert c.shape == (batch_size, 32, 32, 32, 32)
```
```python
# Computing per-example gradients
batch_size = 10
num_features = 32
layer = tf.keras.layers.Dense(1)
def model_fn(arg):
with tf.GradientTape() as g:
inp, label = arg
inp = tf.expand_dims(inp, 0)
label = tf.expand_dims(label, 0)
prediction = layer(inp)
loss = tf.nn.l2_loss(label - prediction)
return g.gradient(loss, (layer.kernel, layer.bias))
inputs = tf.random_uniform([batch_size, num_features])
labels = tf.random_uniform([batch_size, 1])
per_example_gradients = tf.vectorized_map(model_fn, (inputs, labels))
assert per_example_gradients[0].shape == (batch_size, num_features, 1)
assert per_example_gradients[1].shape == (batch_size, 1)
```
"""
def loop_fn(i):
gathered_elems = nest.map_structure(lambda x: array_ops.gather(x, i), elems)
return fn(gathered_elems)
batch_size = array_ops.shape(nest.flatten(elems)[0])[0]
return pfor(loop_fn, batch_size) | [
"def",
"vectorized_map",
"(",
"fn",
",",
"elems",
")",
":",
"def",
"loop_fn",
"(",
"i",
")",
":",
"gathered_elems",
"=",
"nest",
".",
"map_structure",
"(",
"lambda",
"x",
":",
"array_ops",
".",
"gather",
"(",
"x",
",",
"i",
")",
",",
"elems",
")",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/control_flow_ops.py#L309-L390 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/model_fitting/model_fitting_data_selector_view.py | python | ModelFittingDataSelectorView.add_results_table_name | (self, results_table_name: str) | Add a results table to the results table combo box. | Add a results table to the results table combo box. | [
"Add",
"a",
"results",
"table",
"to",
"the",
"results",
"table",
"combo",
"box",
"."
] | def add_results_table_name(self, results_table_name: str) -> None:
"""Add a results table to the results table combo box."""
self.result_table_selector.add_dataset_name(results_table_name)
self.result_table_selector.set_current_dataset_index(self.result_table_selector.number_of_datasets()-1) | [
"def",
"add_results_table_name",
"(",
"self",
",",
"results_table_name",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"result_table_selector",
".",
"add_dataset_name",
"(",
"results_table_name",
")",
"self",
".",
"result_table_selector",
".",
"set_current_dataset_... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/model_fitting/model_fitting_data_selector_view.py#L47-L50 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBListener.__init__ | (self, *args) | __init__(lldb::SBListener self) -> SBListener
__init__(lldb::SBListener self, char const * name) -> SBListener
__init__(lldb::SBListener self, SBListener rhs) -> SBListener | __init__(lldb::SBListener self) -> SBListener
__init__(lldb::SBListener self, char const * name) -> SBListener
__init__(lldb::SBListener self, SBListener rhs) -> SBListener | [
"__init__",
"(",
"lldb",
"::",
"SBListener",
"self",
")",
"-",
">",
"SBListener",
"__init__",
"(",
"lldb",
"::",
"SBListener",
"self",
"char",
"const",
"*",
"name",
")",
"-",
">",
"SBListener",
"__init__",
"(",
"lldb",
"::",
"SBListener",
"self",
"SBListen... | def __init__(self, *args):
"""
__init__(lldb::SBListener self) -> SBListener
__init__(lldb::SBListener self, char const * name) -> SBListener
__init__(lldb::SBListener self, SBListener rhs) -> SBListener
"""
this = _lldb.new_SBListener(*args)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"this",
"=",
"_lldb",
".",
"new_SBListener",
"(",
"*",
"args",
")",
"try",
":",
"self",
".",
"this",
".",
"append",
"(",
"this",
")",
"except",
"__builtin__",
".",
"Exception",
":",
"self",
... | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6800-L6810 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/headers.py | python | Headers._convert_string_type | (self, value) | Convert/check value type. | Convert/check value type. | [
"Convert",
"/",
"check",
"value",
"type",
"."
] | def _convert_string_type(self, value):
"""Convert/check value type."""
if type(value) is str:
return value
raise AssertionError("Header names/values must be"
" of type str (got {0})".format(repr(value))) | [
"def",
"_convert_string_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"str",
":",
"return",
"value",
"raise",
"AssertionError",
"(",
"\"Header names/values must be\"",
"\" of type str (got {0})\"",
".",
"format",
"(",
"repr",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/wsgiref/headers.py#L41-L46 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/framework/python/ops/sampling_ops.py | python | _verify_input | (tensor_list, labels, probs_list) | return tensor_list, labels, checked_probs_list | Verify that batched inputs are well-formed. | Verify that batched inputs are well-formed. | [
"Verify",
"that",
"batched",
"inputs",
"are",
"well",
"-",
"formed",
"."
] | def _verify_input(tensor_list, labels, probs_list):
"""Verify that batched inputs are well-formed."""
checked_probs_list = []
for probs in probs_list:
# Since number of classes shouldn't change at runtime, probalities shape
# should be fully defined.
probs.get_shape().assert_is_fully_defined()
# Probabilities must be 1D.
probs.get_shape().assert_has_rank(1)
# Probabilities must be nonnegative and sum to one.
tol = 1e-6
prob_sum = math_ops.reduce_sum(probs)
checked_probs = control_flow_ops.with_dependencies(
[check_ops.assert_non_negative(probs),
check_ops.assert_less(prob_sum, 1.0 + tol),
check_ops.assert_less(1.0 - tol, prob_sum)],
probs)
checked_probs_list.append(checked_probs)
# All probabilities should be the same length.
prob_length = checked_probs_list[0].get_shape().num_elements()
for checked_prob in checked_probs_list:
if checked_prob.get_shape().num_elements() != prob_length:
raise ValueError('Probability parameters must have the same length.')
# Labels tensor should only have batch dimension.
labels.get_shape().assert_has_rank(1)
for tensor in tensor_list:
# Data tensor should have a batch dimension.
tensor_shape = tensor.get_shape().with_rank_at_least(1)
# Data and label batch dimensions must be compatible.
tensor_shape[0].assert_is_compatible_with(labels.get_shape()[0])
# Data and labels must have the same, strictly positive batch size. Since we
# can't assume we know the batch size at graph creation, add runtime checks.
labels_batch_size = array_ops.shape(labels)[0]
lbl_assert = check_ops.assert_positive(labels_batch_size)
# Make each tensor depend on its own checks.
labels = control_flow_ops.with_dependencies([lbl_assert], labels)
tensor_list = [control_flow_ops.with_dependencies(
[lbl_assert,
check_ops.assert_equal(array_ops.shape(x)[0], labels_batch_size)],
x) for x in tensor_list]
# Label's classes must be integers 0 <= x < num_classes.
labels = control_flow_ops.with_dependencies(
[check_ops.assert_integer(labels),
check_ops.assert_non_negative(labels),
check_ops.assert_less(labels, math_ops.cast(prob_length, labels.dtype))],
labels)
return tensor_list, labels, checked_probs_list | [
"def",
"_verify_input",
"(",
"tensor_list",
",",
"labels",
",",
"probs_list",
")",
":",
"checked_probs_list",
"=",
"[",
"]",
"for",
"probs",
"in",
"probs_list",
":",
"# Since number of classes shouldn't change at runtime, probalities shape",
"# should be fully defined.",
"p... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/framework/python/ops/sampling_ops.py#L260-L316 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/idl_parser/idl_parser.py | python | IDLParser.p_Const | (self, p) | Const : CONST ConstType identifier '=' ConstValue '; | Const : CONST ConstType identifier '=' ConstValue '; | [
"Const",
":",
"CONST",
"ConstType",
"identifier",
"=",
"ConstValue",
";"
] | def p_Const(self, p):
"""Const : CONST ConstType identifier '=' ConstValue ';'"""
value = self.BuildProduction('Value', p, 5, p[5])
p[0] = self.BuildNamed('Const', p, 3, ListFromConcat(p[2], value)) | [
"def",
"p_Const",
"(",
"self",
",",
"p",
")",
":",
"value",
"=",
"self",
".",
"BuildProduction",
"(",
"'Value'",
",",
"p",
",",
"5",
",",
"p",
"[",
"5",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"BuildNamed",
"(",
"'Const'",
",",
"p",
"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_parser.py#L439-L442 | ||
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | docker/monitor.py | python | datetime_to_seconds_since_epoch | (dt) | return time.mktime(dt.timetuple()) | Converts a Python datetime to seconds since the epoch. | Converts a Python datetime to seconds since the epoch. | [
"Converts",
"a",
"Python",
"datetime",
"to",
"seconds",
"since",
"the",
"epoch",
"."
] | def datetime_to_seconds_since_epoch(dt):
"""Converts a Python datetime to seconds since the epoch."""
return time.mktime(dt.timetuple()) | [
"def",
"datetime_to_seconds_since_epoch",
"(",
"dt",
")",
":",
"return",
"time",
".",
"mktime",
"(",
"dt",
".",
"timetuple",
"(",
")",
")"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/docker/monitor.py#L85-L87 | |
pskun/finance_news_analysis | 6ac13e32deede37a4cf57bba8b2897941ae3d80d | preprocess/report_preprocess_handler.py | python | ReportPreprocessHandler.init_handler | (self) | 初始化handler的回调函数 | 初始化handler的回调函数 | [
"初始化handler的回调函数"
] | def init_handler(self):
''' 初始化handler的回调函数 '''
# 载入关键词
for keyword_type in GIVEN_KEYWORD_FILES:
kfile = os.path.join(
GIVEN_KEYWORD_DIR, GIVEN_KEYWORD_FILES[keyword_type])
self.keyword_extractor.initGivenKeywords(keyword_type, kfile)
# 从数据库中查询基本的新闻信息
self.process_basic_info()
pass | [
"def",
"init_handler",
"(",
"self",
")",
":",
"# 载入关键词",
"for",
"keyword_type",
"in",
"GIVEN_KEYWORD_FILES",
":",
"kfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"GIVEN_KEYWORD_DIR",
",",
"GIVEN_KEYWORD_FILES",
"[",
"keyword_type",
"]",
")",
"self",
".",
... | https://github.com/pskun/finance_news_analysis/blob/6ac13e32deede37a4cf57bba8b2897941ae3d80d/preprocess/report_preprocess_handler.py#L50-L59 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py | python | shared_embedding_columns_v2 | (categorical_columns,
dimension,
combiner='mean',
initializer=None,
shared_embedding_collection_name=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None,
max_norm=None,
trainable=True) | return result | List of dense columns that convert from sparse, categorical input.
This is similar to `embedding_column`, except that it produces a list of
embedding columns that share the same embedding weights.
Use this when your inputs are sparse and of the same type (e.g. watched and
impression video IDs that share the same vocabulary), and you want to convert
them to a dense representation (e.g., to feed to a DNN).
Inputs must be a list of categorical columns created by any of the
`categorical_column_*` function. They must all be of the same type and have
the same arguments except `key`. E.g. they can be
categorical_column_with_vocabulary_file with the same vocabulary_file. Some or
all columns could also be weighted_categorical_column.
Here is an example embedding of two features for a DNNClassifier model:
```python
watched_video_id = categorical_column_with_vocabulary_file(
'watched_video_id', video_vocabulary_file, video_vocabulary_size)
impression_video_id = categorical_column_with_vocabulary_file(
'impression_video_id', video_vocabulary_file, video_vocabulary_size)
columns = shared_embedding_columns(
[watched_video_id, impression_video_id], dimension=10)
estimator = tf.estimator.DNNClassifier(feature_columns=columns, ...)
label_column = ...
def input_fn():
features = tf.io.parse_example(
..., features=make_parse_example_spec(columns + [label_column]))
labels = features.pop(label_column.name)
return features, labels
estimator.train(input_fn=input_fn, steps=100)
```
Here is an example using `shared_embedding_columns` with model_fn:
```python
def model_fn(features, ...):
watched_video_id = categorical_column_with_vocabulary_file(
'watched_video_id', video_vocabulary_file, video_vocabulary_size)
impression_video_id = categorical_column_with_vocabulary_file(
'impression_video_id', video_vocabulary_file, video_vocabulary_size)
columns = shared_embedding_columns(
[watched_video_id, impression_video_id], dimension=10)
dense_tensor = input_layer(features, columns)
# Form DNN layers, calculate loss, and return EstimatorSpec.
...
```
Args:
categorical_columns: List of categorical columns created by a
`categorical_column_with_*` function. These columns produce the sparse IDs
that are inputs to the embedding lookup. All columns must be of the same
type and have the same arguments except `key`. E.g. they can be
categorical_column_with_vocabulary_file with the same vocabulary_file.
Some or all columns could also be weighted_categorical_column.
dimension: An integer specifying dimension of the embedding, must be > 0.
combiner: A string specifying how to reduce if there are multiple entries
in a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with
'mean' the default. 'sqrtn' often achieves good accuracy, in particular
with bag-of-words columns. Each of this can be thought as example level
normalizations on the column. For more information, see
`tf.embedding_lookup_sparse`.
initializer: A variable initializer function to be used in embedding
variable initialization. If not specified, defaults to
`truncated_normal_initializer` with mean `0.0` and standard
deviation `1/sqrt(dimension)`.
shared_embedding_collection_name: Optional collective name of these columns.
If not given, a reasonable name will be chosen based on the names of
`categorical_columns`.
ckpt_to_load_from: String representing checkpoint name/pattern from which to
restore column weights. Required if `tensor_name_in_ckpt` is not `None`.
tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from
which to restore the column weights. Required if `ckpt_to_load_from` is
not `None`.
max_norm: If not `None`, each embedding is clipped if its l2-norm is
larger than this value, before combining.
trainable: Whether or not the embedding is trainable. Default is True.
Returns:
A list of dense columns that converts from sparse input. The order of
results follows the ordering of `categorical_columns`.
Raises:
ValueError: if `dimension` not > 0.
ValueError: if any of the given `categorical_columns` is of different type
or has different arguments than the others.
ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt`
is specified.
ValueError: if `initializer` is specified and is not callable.
RuntimeError: if eager execution is enabled. | List of dense columns that convert from sparse, categorical input. | [
"List",
"of",
"dense",
"columns",
"that",
"convert",
"from",
"sparse",
"categorical",
"input",
"."
] | def shared_embedding_columns_v2(categorical_columns,
dimension,
combiner='mean',
initializer=None,
shared_embedding_collection_name=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None,
max_norm=None,
trainable=True):
"""List of dense columns that convert from sparse, categorical input.
This is similar to `embedding_column`, except that it produces a list of
embedding columns that share the same embedding weights.
Use this when your inputs are sparse and of the same type (e.g. watched and
impression video IDs that share the same vocabulary), and you want to convert
them to a dense representation (e.g., to feed to a DNN).
Inputs must be a list of categorical columns created by any of the
`categorical_column_*` function. They must all be of the same type and have
the same arguments except `key`. E.g. they can be
categorical_column_with_vocabulary_file with the same vocabulary_file. Some or
all columns could also be weighted_categorical_column.
Here is an example embedding of two features for a DNNClassifier model:
```python
watched_video_id = categorical_column_with_vocabulary_file(
'watched_video_id', video_vocabulary_file, video_vocabulary_size)
impression_video_id = categorical_column_with_vocabulary_file(
'impression_video_id', video_vocabulary_file, video_vocabulary_size)
columns = shared_embedding_columns(
[watched_video_id, impression_video_id], dimension=10)
estimator = tf.estimator.DNNClassifier(feature_columns=columns, ...)
label_column = ...
def input_fn():
features = tf.io.parse_example(
..., features=make_parse_example_spec(columns + [label_column]))
labels = features.pop(label_column.name)
return features, labels
estimator.train(input_fn=input_fn, steps=100)
```
Here is an example using `shared_embedding_columns` with model_fn:
```python
def model_fn(features, ...):
watched_video_id = categorical_column_with_vocabulary_file(
'watched_video_id', video_vocabulary_file, video_vocabulary_size)
impression_video_id = categorical_column_with_vocabulary_file(
'impression_video_id', video_vocabulary_file, video_vocabulary_size)
columns = shared_embedding_columns(
[watched_video_id, impression_video_id], dimension=10)
dense_tensor = input_layer(features, columns)
# Form DNN layers, calculate loss, and return EstimatorSpec.
...
```
Args:
categorical_columns: List of categorical columns created by a
`categorical_column_with_*` function. These columns produce the sparse IDs
that are inputs to the embedding lookup. All columns must be of the same
type and have the same arguments except `key`. E.g. they can be
categorical_column_with_vocabulary_file with the same vocabulary_file.
Some or all columns could also be weighted_categorical_column.
dimension: An integer specifying dimension of the embedding, must be > 0.
combiner: A string specifying how to reduce if there are multiple entries
in a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with
'mean' the default. 'sqrtn' often achieves good accuracy, in particular
with bag-of-words columns. Each of this can be thought as example level
normalizations on the column. For more information, see
`tf.embedding_lookup_sparse`.
initializer: A variable initializer function to be used in embedding
variable initialization. If not specified, defaults to
`truncated_normal_initializer` with mean `0.0` and standard
deviation `1/sqrt(dimension)`.
shared_embedding_collection_name: Optional collective name of these columns.
If not given, a reasonable name will be chosen based on the names of
`categorical_columns`.
ckpt_to_load_from: String representing checkpoint name/pattern from which to
restore column weights. Required if `tensor_name_in_ckpt` is not `None`.
tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from
which to restore the column weights. Required if `ckpt_to_load_from` is
not `None`.
max_norm: If not `None`, each embedding is clipped if its l2-norm is
larger than this value, before combining.
trainable: Whether or not the embedding is trainable. Default is True.
Returns:
A list of dense columns that converts from sparse input. The order of
results follows the ordering of `categorical_columns`.
Raises:
ValueError: if `dimension` not > 0.
ValueError: if any of the given `categorical_columns` is of different type
or has different arguments than the others.
ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt`
is specified.
ValueError: if `initializer` is specified and is not callable.
RuntimeError: if eager execution is enabled.
"""
if context.executing_eagerly():
raise RuntimeError('shared_embedding_columns are not supported when eager '
'execution is enabled.')
if (dimension is None) or (dimension < 1):
raise ValueError('Invalid dimension {}.'.format(dimension))
if (ckpt_to_load_from is None) != (tensor_name_in_ckpt is None):
raise ValueError('Must specify both `ckpt_to_load_from` and '
'`tensor_name_in_ckpt` or none of them.')
if (initializer is not None) and (not callable(initializer)):
raise ValueError('initializer must be callable if specified.')
if initializer is None:
initializer = init_ops.truncated_normal_initializer(
mean=0.0, stddev=1. / math.sqrt(dimension))
# Sort the columns so the default collection name is deterministic even if the
# user passes columns from an unsorted collection, such as dict.values().
sorted_columns = sorted(categorical_columns, key=lambda x: x.name)
c0 = sorted_columns[0]
num_buckets = c0.num_buckets
if not isinstance(c0, CategoricalColumn):
raise ValueError(
'All categorical_columns must be subclasses of CategoricalColumn. '
'Given: {}, of type: {}'.format(c0, type(c0)))
if isinstance(c0, WeightedCategoricalColumn):
c0 = c0.categorical_column
for c in sorted_columns[1:]:
if isinstance(c, WeightedCategoricalColumn):
c = c.categorical_column
if not isinstance(c, type(c0)):
raise ValueError(
'To use shared_embedding_column, all categorical_columns must have '
'the same type, or be weighted_categorical_column of the same type. '
'Given column: {} of type: {} does not match given column: {} of '
'type: {}'.format(c0, type(c0), c, type(c)))
if num_buckets != c.num_buckets:
raise ValueError(
'To use shared_embedding_column, all categorical_columns must have '
'the same number of buckets. Given column: {} with buckets: {} does '
'not match column: {} with buckets: {}'.format(
c0, num_buckets, c, c.num_buckets))
if not shared_embedding_collection_name:
shared_embedding_collection_name = '_'.join(c.name for c in sorted_columns)
shared_embedding_collection_name += '_shared_embedding'
column_creator = SharedEmbeddingColumnCreator(
dimension, initializer, ckpt_to_load_from, tensor_name_in_ckpt,
num_buckets, trainable, shared_embedding_collection_name)
result = []
for column in categorical_columns:
result.append(
column_creator(
categorical_column=column, combiner=combiner, max_norm=max_norm))
return result | [
"def",
"shared_embedding_columns_v2",
"(",
"categorical_columns",
",",
"dimension",
",",
"combiner",
"=",
"'mean'",
",",
"initializer",
"=",
"None",
",",
"shared_embedding_collection_name",
"=",
"None",
",",
"ckpt_to_load_from",
"=",
"None",
",",
"tensor_name_in_ckpt",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L1088-L1250 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/utils/lui/lldbutil.py | python | int_to_bytearray | (val, bytesize) | return bytearray(ord(x) for x in packed) | Utility function to convert an integer into a bytearray.
It returns the bytearray in the little endian format. It is easy to get the
big endian format, just do ba.reverse() on the returned object. | Utility function to convert an integer into a bytearray. | [
"Utility",
"function",
"to",
"convert",
"an",
"integer",
"into",
"a",
"bytearray",
"."
] | def int_to_bytearray(val, bytesize):
"""Utility function to convert an integer into a bytearray.
It returns the bytearray in the little endian format. It is easy to get the
big endian format, just do ba.reverse() on the returned object.
"""
import struct
if bytesize == 1:
return bytearray([val])
# Little endian followed by a format character.
template = "<%c"
if bytesize == 2:
fmt = template % 'h'
elif bytesize == 4:
fmt = template % 'i'
elif bytesize == 4:
fmt = template % 'q'
else:
return None
packed = struct.pack(fmt, val)
return bytearray(ord(x) for x in packed) | [
"def",
"int_to_bytearray",
"(",
"val",
",",
"bytesize",
")",
":",
"import",
"struct",
"if",
"bytesize",
"==",
"1",
":",
"return",
"bytearray",
"(",
"[",
"val",
"]",
")",
"# Little endian followed by a format character.",
"template",
"=",
"\"<%c\"",
"if",
"bytesi... | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/utils/lui/lldbutil.py#L66-L89 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py | python | adjust_jpeg_quality | (image, jpeg_quality, name=None) | Adjust jpeg encoding quality of an RGB image.
This is a convenience method that adjusts jpeg encoding quality of an
RGB image.
`image` is an RGB image. The image's encoding quality is adjusted
to `jpeg_quality`.
`jpeg_quality` must be in the interval `[0, 100]`.
Args:
image: RGB image or images. Size of the last dimension must be 3.
jpeg_quality: Python int or Tensor of type int32. jpeg encoding quality.
name: A name for this operation (optional).
Returns:
Adjusted image(s), same shape and DType as `image`.
Usage Example:
```python
>> import tensorflow as tf
>> x = tf.random.normal(shape=(256, 256, 3))
>> tf.image.adjust_jpeg_quality(x, 75)
```
Raises:
InvalidArgumentError: quality must be in [0,100]
InvalidArgumentError: image must have 1 or 3 channels | Adjust jpeg encoding quality of an RGB image. | [
"Adjust",
"jpeg",
"encoding",
"quality",
"of",
"an",
"RGB",
"image",
"."
] | def adjust_jpeg_quality(image, jpeg_quality, name=None):
"""Adjust jpeg encoding quality of an RGB image.
This is a convenience method that adjusts jpeg encoding quality of an
RGB image.
`image` is an RGB image. The image's encoding quality is adjusted
to `jpeg_quality`.
`jpeg_quality` must be in the interval `[0, 100]`.
Args:
image: RGB image or images. Size of the last dimension must be 3.
jpeg_quality: Python int or Tensor of type int32. jpeg encoding quality.
name: A name for this operation (optional).
Returns:
Adjusted image(s), same shape and DType as `image`.
Usage Example:
```python
>> import tensorflow as tf
>> x = tf.random.normal(shape=(256, 256, 3))
>> tf.image.adjust_jpeg_quality(x, 75)
```
Raises:
InvalidArgumentError: quality must be in [0,100]
InvalidArgumentError: image must have 1 or 3 channels
"""
with ops.name_scope(name, 'adjust_jpeg_quality', [image]) as name:
image = ops.convert_to_tensor(image, name='image')
# Remember original dtype to so we can convert back if needed
orig_dtype = image.dtype
# Convert to uint8
image = convert_image_dtype(image, dtypes.uint8)
# Encode image to jpeg with given jpeg quality
if compat.forward_compatible(2019, 4, 4):
if not _is_tensor(jpeg_quality):
# If jpeg_quality is a int (not tensor).
jpeg_quality = ops.convert_to_tensor(jpeg_quality, dtype=dtypes.int32)
image = gen_image_ops.encode_jpeg_variable_quality(image, jpeg_quality)
else:
image = gen_image_ops.encode_jpeg(image, quality=jpeg_quality)
# Decode jpeg image
image = gen_image_ops.decode_jpeg(image)
# Convert back to original dtype and return
return convert_image_dtype(image, orig_dtype) | [
"def",
"adjust_jpeg_quality",
"(",
"image",
",",
"jpeg_quality",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'adjust_jpeg_quality'",
",",
"[",
"image",
"]",
")",
"as",
"name",
":",
"image",
"=",
"ops",
".",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py#L2001-L2047 | ||
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | cpplint.py | python | ProcessFileData | (filename, file_extension, lines, error) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is termined with a newline.
error: A callable to which errors are reported, which takes 4 arguments: | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is termined with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
class_state = _ClassState()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, class_state, error)
class_state.CheckFinished(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForUnicodeReplacementCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error)
CheckForThrowNew(filename, lines, error)
CheckForCatchByNonRef(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// marker so line numbers end in a known way'",
"]",... | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/cpplint.py#L2904-L2942 | ||
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/serde.py | python | extract_elem | (serde, n, if_not_found=None) | return if_not_found | inner function | inner function | [
"inner",
"function"
] | def extract_elem(serde, n, if_not_found=None):
""" inner function"""
if isinstance(serde, Optional):
ret = extract_elem(serde._orig_serde, n, None)
if ret is None:
return if_not_found
if not isinstance(ret, Optional):
return Optional(ret)
else:
return ret
if isinstance(serde, TupleSerde):
return serde._args[n]
if isinstance(serde, ListSerde):
return extract_elem(serde._delegate, n, if_not_found)
if isinstance(serde, SameTypeListSerde):
return serde._value
if isinstance(serde, TupleLikeListSerde):
return serde._values[n]
#print serde, isinstance(serde, ListSerde), type(serde)
return if_not_found | [
"def",
"extract_elem",
"(",
"serde",
",",
"n",
",",
"if_not_found",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"serde",
",",
"Optional",
")",
":",
"ret",
"=",
"extract_elem",
"(",
"serde",
".",
"_orig_serde",
",",
"n",
",",
"None",
")",
"if",
"r... | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/serde.py#L768-L792 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py | python | copy | (a, order='K') | return array(a, order=order, copy=True) | Return an array copy of the given object.
Parameters
----------
a : array_like
Input data.
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a` as closely
as possible. (Note that this function and :meth:`ndarray.copy` are very
similar, but have different default values for their order=
arguments.)
Returns
-------
arr : ndarray
Array interpretation of `a`.
Notes
-----
This is equivalent to:
>>> np.array(a, copy=True) #doctest: +SKIP
Examples
--------
Create an array x, with a reference y and a copy z:
>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
Note that, when we modify x, y changes, but not z:
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False | Return an array copy of the given object. | [
"Return",
"an",
"array",
"copy",
"of",
"the",
"given",
"object",
"."
] | def copy(a, order='K'):
"""
Return an array copy of the given object.
Parameters
----------
a : array_like
Input data.
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a` as closely
as possible. (Note that this function and :meth:`ndarray.copy` are very
similar, but have different default values for their order=
arguments.)
Returns
-------
arr : ndarray
Array interpretation of `a`.
Notes
-----
This is equivalent to:
>>> np.array(a, copy=True) #doctest: +SKIP
Examples
--------
Create an array x, with a reference y and a copy z:
>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
Note that, when we modify x, y changes, but not z:
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
"""
return array(a, order=order, copy=True) | [
"def",
"copy",
"(",
"a",
",",
"order",
"=",
"'K'",
")",
":",
"return",
"array",
"(",
"a",
",",
"order",
"=",
"order",
",",
"copy",
"=",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py#L731-L775 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/tools/transformers/profiler.py | python | create_longformer_inputs | (onnx_model, batch_size, sequence_length, global_length, samples) | return all_inputs | Create dummy inputs for Longformer model.
Args:
onnx_model (OnnxModel): ONNX model
batch_size (int): batch size
sequence_length (int): sequence length
global_length (int): number of global tokens
samples (int): number of samples
Raises:
RuntimeError: symbolic is not supported. Use the tool convert_longformer_to_onnx.py to export ONNX model instead.
Returns:
List[Dict]: list of inputs | Create dummy inputs for Longformer model. | [
"Create",
"dummy",
"inputs",
"for",
"Longformer",
"model",
"."
] | def create_longformer_inputs(onnx_model, batch_size, sequence_length, global_length, samples):
"""Create dummy inputs for Longformer model.
Args:
onnx_model (OnnxModel): ONNX model
batch_size (int): batch size
sequence_length (int): sequence length
global_length (int): number of global tokens
samples (int): number of samples
Raises:
RuntimeError: symbolic is not supported. Use the tool convert_longformer_to_onnx.py to export ONNX model instead.
Returns:
List[Dict]: list of inputs
"""
symbols = {'batch_size': batch_size, 'sequence_length': sequence_length}
dummy_inputs = {}
for graph_input in onnx_model.get_graph_inputs_excluding_initializers():
shape = get_shape_from_type_proto(graph_input.type)
for i, dim in enumerate(shape):
if isinstance(dim, str):
if dim not in symbols.keys():
raise RuntimeError(f"symbol is not supported: {dim}")
else:
shape[i] = symbols[dim]
elem_type = graph_input.type.tensor_type.elem_type
assert elem_type in [TensorProto.FLOAT, TensorProto.INT32, TensorProto.INT64]
data_type = numpy.float32 if elem_type == TensorProto.FLOAT else (
numpy.int64 if elem_type == TensorProto.INT64 else numpy.int32)
if "global" in graph_input.name:
data = numpy.zeros(shape, dtype=data_type)
data[:, :global_length] = 1
else:
data = numpy.ones(shape, dtype=data_type)
dummy_inputs[graph_input.name] = data
all_inputs = [dummy_inputs for _ in range(samples)]
return all_inputs | [
"def",
"create_longformer_inputs",
"(",
"onnx_model",
",",
"batch_size",
",",
"sequence_length",
",",
"global_length",
",",
"samples",
")",
":",
"symbols",
"=",
"{",
"'batch_size'",
":",
"batch_size",
",",
"'sequence_length'",
":",
"sequence_length",
"}",
"dummy_inp... | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/transformers/profiler.py#L532-L573 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py | python | Mailbox.has_key | (self, key) | Return True if the keyed message exists, False otherwise. | Return True if the keyed message exists, False otherwise. | [
"Return",
"True",
"if",
"the",
"keyed",
"message",
"exists",
"False",
"otherwise",
"."
] | def has_key(self, key):
"""Return True if the keyed message exists, False otherwise."""
raise NotImplementedError('Method must be implemented by subclass') | [
"def",
"has_key",
"(",
"self",
",",
"key",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Method must be implemented by subclass'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L135-L137 | ||
VKCOM/YouTokenToMe | f4bc5f8c45487b31aa0f53419714f32229ca8854 | youtokentome/yttm_cli.py | python | vocab | (model, verbose) | Print list of learned subwords. | Print list of learned subwords. | [
"Print",
"list",
"of",
"learned",
"subwords",
"."
] | def vocab(model, verbose):
"""Print list of learned subwords."""
bpe = yttmc.BPE(model)
bpe.vocab_cli(verbose) | [
"def",
"vocab",
"(",
"model",
",",
"verbose",
")",
":",
"bpe",
"=",
"yttmc",
".",
"BPE",
"(",
"model",
")",
"bpe",
".",
"vocab_cli",
"(",
"verbose",
")"
] | https://github.com/VKCOM/YouTokenToMe/blob/f4bc5f8c45487b31aa0f53419714f32229ca8854/youtokentome/yttm_cli.py#L160-L163 | ||
OPAE/opae-sdk | 221124343c8275243a249eb72d69e0ea2d568d1b | python/opae.admin/opae/admin/tools/fpgaotsu.py | python | otsu_updater.verify | (self, obj, mtd_dev, infile, report_fail=True) | return False | Verify the flash range described in obj.
Args:
obj: an object for one of the parsed "flash" sections
from the manifest.
mtd_dev: an mtd object for the open flash device.
infile: an open file object to the source file content. | Verify the flash range described in obj. | [
"Verify",
"the",
"flash",
"range",
"described",
"in",
"obj",
"."
] | def verify(self, obj, mtd_dev, infile, report_fail=True):
"""Verify the flash range described in obj.
Args:
obj: an object for one of the parsed "flash" sections
from the manifest.
mtd_dev: an mtd object for the open flash device.
infile: an open file object to the source file content.
"""
seek = 0 if obj.get('seek') is None else to_int(obj['seek'])[1]
start = to_int(obj['start'])[1]
end = to_int(obj['end'])[1]
filename = os.path.join(self._fw_dir, obj['filename'])
infile.seek(seek)
if infile.tell() != seek:
raise IOError('failed to seek in input file %s: 0x%x' %
(filename, seek))
src_bits = tempfile.NamedTemporaryFile(mode='wb', delete=False)
src_bits.write(infile.read((end + 1) - start))
src_bits.close()
flash_bits = tempfile.NamedTemporaryFile(mode='wb', delete=False)
LOG.info('Reading %s@0x%x for %d bytes for verification',
obj['type'], start, (end + 1) - start)
if min([l.level for l in LOG.handlers]) < logging.INFO:
prog = LOG.debug
else:
prog = sys.stdout
mtd_dev.copy_to(flash_bits,
(end + 1) - start,
start,
progress=prog,
chunked=self._chunk_size)
flash_bits.close()
compare = filecmp.cmp(src_bits.name, flash_bits.name, shallow=False)
os.remove(src_bits.name)
os.remove(flash_bits.name)
if compare:
LOG.info('Verified %s@0x%x for %d bytes (%s)',
obj['type'], start, (end + 1) - start,
os.path.basename(filename))
return True
if report_fail:
msg = 'Verification of {} @0x{} failed'.format(
os.path.basename(filename), start)
self.error(msg)
return False | [
"def",
"verify",
"(",
"self",
",",
"obj",
",",
"mtd_dev",
",",
"infile",
",",
"report_fail",
"=",
"True",
")",
":",
"seek",
"=",
"0",
"if",
"obj",
".",
"get",
"(",
"'seek'",
")",
"is",
"None",
"else",
"to_int",
"(",
"obj",
"[",
"'seek'",
"]",
")"... | https://github.com/OPAE/opae-sdk/blob/221124343c8275243a249eb72d69e0ea2d568d1b/python/opae.admin/opae/admin/tools/fpgaotsu.py#L405-L460 | |
TheLegendAli/DeepLab-Context | fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c | scripts/cpp_lint.py | python | _CppLintState.ResetErrorCounts | (self) | Sets the module's error statistic back to zero. | Sets the module's error statistic back to zero. | [
"Sets",
"the",
"module",
"s",
"error",
"statistic",
"back",
"to",
"zero",
"."
] | def ResetErrorCounts(self):
"""Sets the module's error statistic back to zero."""
self.error_count = 0
self.errors_by_category = {} | [
"def",
"ResetErrorCounts",
"(",
"self",
")",
":",
"self",
".",
"error_count",
"=",
"0",
"self",
".",
"errors_by_category",
"=",
"{",
"}"
] | https://github.com/TheLegendAli/DeepLab-Context/blob/fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c/scripts/cpp_lint.py#L742-L745 | ||
oneapi-src/oneDNN | 653d270544c0ceb29bb6f4fb6aeb6fc9928011b1 | scripts/verbose_converter/src/dnnl_parser.py | python | LogParser.process | (self) | Adds data from the last log file.
Parameters:
-----------
None
Returns:
--------
None | Adds data from the last log file. | [
"Adds",
"data",
"from",
"the",
"last",
"log",
"file",
"."
] | def process(self):
"""
Adds data from the last log file.
Parameters:
-----------
None
Returns:
--------
None
"""
def convert_primitive(log_entry, template):
"""
Converts oneDNN verbose primitive entry into the internal
representation.
"""
def convert_mds(log_mds):
mds = []
for md in log_mds.split(' '):
# arg_dt:padding:format_kind:tag:flags
fields = md.split(':')
arg_dt = fields[0]
padding = fields[1]
format_kind = fields[2]
tag = fields[3]
flags = {}
flags['value'] = fields[4]
if len(fields) > 5:
flag_fields = fields[5:]
for f in flag_fields:
if f[:3] == 's8m':
flags['s8_comp_mask'] = f[3:]
if f[:3] == 'zpm':
flags['zp_comp_mask'] = f[3:]
data_type = arg_dt.split('_')[-1]
arg = arg_dt[:-len(data_type) - 1]
mds.append({
'arg': arg,
'data_type': data_type,
'padding': padding,
'format_kind': format_kind,
'tag': tag,
'flags': flags
})
return mds
def convert_alg(alg):
found_alg = alg.find('alg')
if found_alg != -1:
alg = alg[len('alg') + 1:]
return alg
def convert_prim_kind(prim_kind):
if prim_kind == 'pooling_v2':
prim_kind = 'pooling'
if prim_kind == 'softmax_v2':
prim_kind = 'softmax'
return prim_kind
def convert_exts(exts):
def extract_attr(attrs, type):
start_idx = attrs.find(type)
if start_idx == -1:
return ''
start_idx += len(type) + 1
end_symbol = ' '
end_idx = attrs.find(end_symbol, start_idx)
return attrs[start_idx:end_idx]
def convert_structure_to_ir_seq(ir, value):
params = value.split(':')
fields = list(ir.keys())
ir.update(
(fields[i], params[i])
for i in range(0, min(len(params), len(fields))))
return ir
def convert_post_ops(value):
def convert_binary_post_op(value):
p_op = {
'alg': '',
'dt': 'f32',
'mask': '0',
'tag': None
}
p_op = convert_structure_to_ir_seq(p_op, value)
p_op['prim_kind'] = 'binary'
return p_op
def convert_dw_post_op(value):
p_op = {
'alg': '',
'dst_dt': 'f32',
'wei_dt': 'f32',
'scales': {
'mask': '0',
'value': None
}
}
params = value.split(':')
len_params = len(params)
p_op['alg'] = params[0]
if len_params > 1:
p_op['dst_dt'] = params[1]
if len_params > 2:
p_op['wei_dt'] = 's8'
p_op['scales']['mask'] = params[2]
if len_params > 3:
p_op['scales']['value'] = params[3]
return p_op
def convert_eltwise_post_op(value):
p_op = {
'alg': '',
'alpha': '1.0',
'beta': '0.0',
'scale': '1.0'
}
return convert_structure_to_ir_seq(p_op, value)
def convert_sum_post_op(value):
p_op = {'alg': '', 'scale': '1.0', 'zp': '0', 'dt': ''}
return convert_structure_to_ir_seq(p_op, value)
def convert_prelu_post_op(value):
p_op = {'alg': '', 'mask': '0'}
return convert_structure_to_ir_seq(p_op, value)
convert = {
'binary': convert_binary_post_op,
'dw': convert_dw_post_op,
'eltwise': convert_eltwise_post_op,
'sum': convert_sum_post_op,
'prelu': convert_prelu_post_op,
}
entries = value.split('+')
postops = []
for e in entries:
for k in convert.keys():
if k in e:
cvt = convert.get(k)
postops.append(cvt(e))
break
return postops
def convert_oscale(value):
oscale = {'mask': '0', 'value': None}
return convert_structure_to_ir_seq(oscale, value)
def convert_scales(value):
res = {}
scales = value.split('+')
for s in scales:
scale = {'mask': '0', 'value': None}
arg = s[:s.find(':')]
s_wo_arg = s[s.find(':')+1:]
res[arg] = convert_structure_to_ir_seq(scale, s_wo_arg)
return res
def convert_zero_points(value):
res = {}
zp_value = value.split('+')
for zp in zp_value:
arg = zp[:zp.find(':')]
zp_value_wo_arg = zp[zp.find(':')+1:]
zp_dict = {'mask': '0', 'value': None}
res[arg] = convert_structure_to_ir_seq(zp_dict, zp_value_wo_arg)
return res
def convert_scratchpad_mode(value):
return value
converters = {
'attr-post-ops': convert_post_ops,
'attr-oscale': convert_oscale,
'attr-scales': convert_scales,
'attr-zero-points': convert_zero_points,
'attr-scratchpad': convert_scratchpad_mode
}
attrs = {}
for e in converters.keys():
attr = extract_attr(exts, e)
if attr != '':
attrs[e] = converters[e](attr)
return attrs
def convert_pass(v):
return v
convert = {
'prim_kind': convert_prim_kind,
'mds': convert_mds,
'alg_kind': convert_alg,
'exts': convert_exts
}
dnnl_to_ir = {
'engine': 'engine',
'prim_kind': 'primitive',
'impl': 'implementation',
'prop_kind': 'prop_kind',
'mds': 'memory_descriptors',
'exts': 'attributes',
'alg_kind': 'auxiliary',
'shapes': 'problem_desc',
'time': 'exec_time',
'timestamp': 'timestamp'
}
ir_req = [ 'engine', 'prim_kind', 'impl', 'prop_kind', 'mds',
'exts', 'alg_kind', 'shapes']
entry = {}
t = template.split(',')
for key, value in dnnl_to_ir.items():
notification_level = "WARN" if key in ir_req else "INFO"
try:
idx = t.index(value)
if idx != -1:
cvt = convert.get(key)
if cvt is None:
cvt = convert_pass
field = log_entry[idx]
try:
entry[key] = cvt(field)
except:
self.__writer.print(
f"Parser: parsing entry error: {field}: {value}",
notification_level)
else:
self.__writer.print(f"Parser: Unknown entry: {value}",
notification_level)
except:
self.__writer.print(f"Parser: skipping empty entry: {key}",
notification_level)
return entry
verbose_template = "onednn_verbose,operation,engine,primitive," + \
"implementation,prop_kind,memory_descriptors,attributes," + \
"auxiliary,problem_desc"
i = len(self.__data)
for line in self.__input:
self.__raw_data.append(line.rstrip())
l_raw = line.split(",")
marker = l_raw[0]
if marker == "onednn_verbose":
event = l_raw[1]
if event == "info":
opt = l_raw[2]
if opt == "prim_template":
verbose_template = "onednn_verbose," + line.split(':')[1]
if event == "exec":
l_converted = convert_primitive(l_raw, verbose_template)
if l_converted:
self.__data[i] = l_converted
i = i + 1 | [
"def",
"process",
"(",
"self",
")",
":",
"def",
"convert_primitive",
"(",
"log_entry",
",",
"template",
")",
":",
"\"\"\"\n Converts oneDNN verbose primitive entry into the internal\n representation.\n \"\"\"",
"def",
"convert_mds",
"(",
"log_mds"... | https://github.com/oneapi-src/oneDNN/blob/653d270544c0ceb29bb6f4fb6aeb6fc9928011b1/scripts/verbose_converter/src/dnnl_parser.py#L39-L300 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBType.get_bases_array | (self) | return bases | An accessor function that returns a list() that contains all direct base classes in a lldb.SBType object. | An accessor function that returns a list() that contains all direct base classes in a lldb.SBType object. | [
"An",
"accessor",
"function",
"that",
"returns",
"a",
"list",
"()",
"that",
"contains",
"all",
"direct",
"base",
"classes",
"in",
"a",
"lldb",
".",
"SBType",
"object",
"."
] | def get_bases_array(self):
'''An accessor function that returns a list() that contains all direct base classes in a lldb.SBType object.'''
bases = []
for idx in range(self.GetNumberOfDirectBaseClasses()):
bases.append(self.GetDirectBaseClassAtIndex(idx))
return bases | [
"def",
"get_bases_array",
"(",
"self",
")",
":",
"bases",
"=",
"[",
"]",
"for",
"idx",
"in",
"range",
"(",
"self",
".",
"GetNumberOfDirectBaseClasses",
"(",
")",
")",
":",
"bases",
".",
"append",
"(",
"self",
".",
"GetDirectBaseClassAtIndex",
"(",
"idx",
... | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12852-L12857 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/utils.py | python | consume | (iterable) | Consumes an iterable without doing anything with it. | Consumes an iterable without doing anything with it. | [
"Consumes",
"an",
"iterable",
"without",
"doing",
"anything",
"with",
"it",
"."
] | def consume(iterable):
"""Consumes an iterable without doing anything with it."""
for event in iterable:
pass | [
"def",
"consume",
"(",
"iterable",
")",
":",
"for",
"event",
"in",
"iterable",
":",
"pass"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/utils.py#L105-L108 | ||
ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | LeetCode/python3/15.py | python | Solution.threeSum | (self, nums) | return res | :type nums: List[int]
:rtype: List[List[int]] | :type nums: List[int]
:rtype: List[List[int]] | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] | def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
print(nums)
i = 0
while i < len(nums):
target = -nums[i]
x, y = i + 1, len(nums) - 1
while x < y:
if nums[x] + nums[y] < target:
x += 1
elif nums[x] + nums[y] > target:
y -= 1
else:
X = nums[x]
Y = nums[y]
res.append([nums[i], X, Y])
while x < y and nums[x] == X:
x += 1
while x < y and nums[y] == Y:
y -= 1
while i + 1 < len(nums) and nums[i + 1] == nums[i]:
i += 1
i += 1
return res | [
"def",
"threeSum",
"(",
"self",
",",
"nums",
")",
":",
"res",
"=",
"[",
"]",
"nums",
".",
"sort",
"(",
")",
"print",
"(",
"nums",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"nums",
")",
":",
"target",
"=",
"-",
"nums",
"[",
"i",
"]"... | https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python3/15.py#L2-L31 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/tools/batch_env.py | python | BatchEnv.__init__ | (self, envs, blocking) | Combine multiple environments to step them in batch.
To step environments in parallel, environments must support a
`blocking=False` argument to their step and reset functions that makes them
return callables instead to receive the result at a later time.
Args:
envs: List of environments.
blocking: Step environments after another rather than in parallel.
Raises:
ValueError: Environments have different observation or action spaces. | Combine multiple environments to step them in batch. | [
"Combine",
"multiple",
"environments",
"to",
"step",
"them",
"in",
"batch",
"."
] | def __init__(self, envs, blocking):
"""Combine multiple environments to step them in batch.
To step environments in parallel, environments must support a
`blocking=False` argument to their step and reset functions that makes them
return callables instead to receive the result at a later time.
Args:
envs: List of environments.
blocking: Step environments after another rather than in parallel.
Raises:
ValueError: Environments have different observation or action spaces.
"""
self._envs = envs
self._blocking = blocking
observ_space = self._envs[0].observation_space
if not all(env.observation_space == observ_space for env in self._envs):
raise ValueError('All environments must use the same observation space.')
action_space = self._envs[0].action_space
if not all(env.action_space == action_space for env in self._envs):
raise ValueError('All environments must use the same observation space.') | [
"def",
"__init__",
"(",
"self",
",",
"envs",
",",
"blocking",
")",
":",
"self",
".",
"_envs",
"=",
"envs",
"self",
".",
"_blocking",
"=",
"blocking",
"observ_space",
"=",
"self",
".",
"_envs",
"[",
"0",
"]",
".",
"observation_space",
"if",
"not",
"all"... | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/tools/batch_env.py#L26-L47 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntV.SwapI | (*args) | return _snap.TIntV_SwapI(*args) | SwapI(TInt LVal, TInt RVal)
Parameters:
LVal: TVec< TInt,int >::TIter
RVal: TVec< TInt,int >::TIter | SwapI(TInt LVal, TInt RVal) | [
"SwapI",
"(",
"TInt",
"LVal",
"TInt",
"RVal",
")"
] | def SwapI(*args):
"""
SwapI(TInt LVal, TInt RVal)
Parameters:
LVal: TVec< TInt,int >::TIter
RVal: TVec< TInt,int >::TIter
"""
return _snap.TIntV_SwapI(*args) | [
"def",
"SwapI",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TIntV_SwapI",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L15857-L15866 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/shutil.py | python | copyfile | (src, dst, *, follow_symlinks=True) | return dst | Copy data from src to dst in the most efficient way possible.
If follow_symlinks is not set and src is a symbolic link, a new
symlink will be created instead of copying the file it points to. | Copy data from src to dst in the most efficient way possible. | [
"Copy",
"data",
"from",
"src",
"to",
"dst",
"in",
"the",
"most",
"efficient",
"way",
"possible",
"."
] | def copyfile(src, dst, *, follow_symlinks=True):
"""Copy data from src to dst in the most efficient way possible.
If follow_symlinks is not set and src is a symbolic link, a new
symlink will be created instead of copying the file it points to.
"""
sys.audit("shutil.copyfile", src, dst)
if _samefile(src, dst):
raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
file_size = 0
for i, fn in enumerate([src, dst]):
try:
st = _stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
fn = fn.path if isinstance(fn, os.DirEntry) else fn
raise SpecialFileError("`%s` is a named pipe" % fn)
if _WINDOWS and i == 0:
file_size = st.st_size
if not follow_symlinks and _islink(src):
os.symlink(os.readlink(src), dst)
else:
with open(src, 'rb') as fsrc:
try:
with open(dst, 'wb') as fdst:
# macOS
if _HAS_FCOPYFILE:
try:
_fastcopy_fcopyfile(fsrc, fdst, posix._COPYFILE_DATA)
return dst
except _GiveupOnFastCopy:
pass
# Linux
elif _USE_CP_SENDFILE:
try:
_fastcopy_sendfile(fsrc, fdst)
return dst
except _GiveupOnFastCopy:
pass
# Windows, see:
# https://github.com/python/cpython/pull/7160#discussion_r195405230
elif _WINDOWS and file_size > 0:
_copyfileobj_readinto(fsrc, fdst, min(file_size, COPY_BUFSIZE))
return dst
copyfileobj(fsrc, fdst)
# Issue 43219, raise a less confusing exception
except IsADirectoryError as e:
if not os.path.exists(dst):
raise FileNotFoundError(f'Directory does not exist: {dst}') from e
else:
raise
return dst | [
"def",
"copyfile",
"(",
"src",
",",
"dst",
",",
"*",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"sys",
".",
"audit",
"(",
"\"shutil.copyfile\"",
",",
"src",
",",
"dst",
")",
"if",
"_samefile",
"(",
"src",
",",
"dst",
")",
":",
"raise",
"SameFileE... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/shutil.py#L234-L296 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/common/position.py | python | Position.Get | (self, string) | return string[self.start:self.start + self.length] | Returns this range of the given string.
Args:
string: The string to slice.
Returns:
The string within the range specified by this object. | Returns this range of the given string. | [
"Returns",
"this",
"range",
"of",
"the",
"given",
"string",
"."
] | def Get(self, string):
"""Returns this range of the given string.
Args:
string: The string to slice.
Returns:
The string within the range specified by this object.
"""
return string[self.start:self.start + self.length] | [
"def",
"Get",
"(",
"self",
",",
"string",
")",
":",
"return",
"string",
"[",
"self",
".",
"start",
":",
"self",
".",
"start",
"+",
"self",
".",
"length",
"]"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/common/position.py#L41-L50 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/credentials.py | python | ConfigProvider.__init__ | (self, config_filename, profile_name, config_parser=None) | :param config_filename: The session configuration scoped to the current
profile. This is available via ``session.config``.
:param profile_name: The name of the current profile.
:param config_parser: A config parser callable. | [] | def __init__(self, config_filename, profile_name, config_parser=None):
"""
:param config_filename: The session configuration scoped to the current
profile. This is available via ``session.config``.
:param profile_name: The name of the current profile.
:param config_parser: A config parser callable.
"""
self._config_filename = config_filename
self._profile_name = profile_name
if config_parser is None:
config_parser = botocore.configloader.load_config
self._config_parser = config_parser | [
"def",
"__init__",
"(",
"self",
",",
"config_filename",
",",
"profile_name",
",",
"config_parser",
"=",
"None",
")",
":",
"self",
".",
"_config_filename",
"=",
"config_filename",
"self",
".",
"_profile_name",
"=",
"profile_name",
"if",
"config_parser",
"is",
"No... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/credentials.py#L1221-L1234 | |||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/smtplib.py | python | SMTP.set_debuglevel | (self, debuglevel) | Set the debug output level.
A non-false value results in debug messages for connection and for all
messages sent to and received from the server. | Set the debug output level. | [
"Set",
"the",
"debug",
"output",
"level",
"."
] | def set_debuglevel(self, debuglevel):
"""Set the debug output level.
A non-false value results in debug messages for connection and for all
messages sent to and received from the server.
"""
self.debuglevel = debuglevel | [
"def",
"set_debuglevel",
"(",
"self",
",",
"debuglevel",
")",
":",
"self",
".",
"debuglevel",
"=",
"debuglevel"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/smtplib.py#L271-L278 | ||
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/descriptor.py | python | FieldDescriptor.ProtoTypeToCppProtoType | (proto_type) | Converts from a Python proto type to a C++ Proto Type.
The Python ProtocolBuffer classes specify both the 'Python' datatype and the
'C++' datatype - and they're not the same. This helper method should
translate from one to another.
Args:
proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
Returns:
descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
Raises:
TypeTransformationError: when the Python proto type isn't known. | Converts from a Python proto type to a C++ Proto Type. | [
"Converts",
"from",
"a",
"Python",
"proto",
"type",
"to",
"a",
"C",
"++",
"Proto",
"Type",
"."
] | def ProtoTypeToCppProtoType(proto_type):
"""Converts from a Python proto type to a C++ Proto Type.
The Python ProtocolBuffer classes specify both the 'Python' datatype and the
'C++' datatype - and they're not the same. This helper method should
translate from one to another.
Args:
proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
Returns:
descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
Raises:
TypeTransformationError: when the Python proto type isn't known.
"""
try:
return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
except KeyError:
raise TypeTransformationError('Unknown proto_type: %s' % proto_type) | [
"def",
"ProtoTypeToCppProtoType",
"(",
"proto_type",
")",
":",
"try",
":",
"return",
"FieldDescriptor",
".",
"_PYTHON_TO_CPP_PROTO_TYPE_MAP",
"[",
"proto_type",
"]",
"except",
"KeyError",
":",
"raise",
"TypeTransformationError",
"(",
"'Unknown proto_type: %s'",
"%",
"pr... | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/descriptor.py#L550-L567 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py | python | SimpleXMLRPCDispatcher._marshaled_dispatch | (self, data, dispatch_method = None, path = None) | return response.encode(self.encoding, 'xmlcharrefreplace') | Dispatches an XML-RPC method from marshalled (XML) data.
XML-RPC methods are dispatched from the marshalled (XML) data
using the _dispatch method and the result is returned as
marshalled data. For backwards compatibility, a dispatch
function can be provided as an argument (see comment in
SimpleXMLRPCRequestHandler.do_POST) but overriding the
existing method through subclassing is the preferred means
of changing method dispatch behavior. | Dispatches an XML-RPC method from marshalled (XML) data. | [
"Dispatches",
"an",
"XML",
"-",
"RPC",
"method",
"from",
"marshalled",
"(",
"XML",
")",
"data",
"."
] | def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
"""Dispatches an XML-RPC method from marshalled (XML) data.
XML-RPC methods are dispatched from the marshalled (XML) data
using the _dispatch method and the result is returned as
marshalled data. For backwards compatibility, a dispatch
function can be provided as an argument (see comment in
SimpleXMLRPCRequestHandler.do_POST) but overriding the
existing method through subclassing is the preferred means
of changing method dispatch behavior.
"""
try:
params, method = loads(data, use_builtin_types=self.use_builtin_types)
# generate response
if dispatch_method is not None:
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params)
# wrap response in a singleton tuple
response = (response,)
response = dumps(response, methodresponse=1,
allow_none=self.allow_none, encoding=self.encoding)
except Fault as fault:
response = dumps(fault, allow_none=self.allow_none,
encoding=self.encoding)
except:
# report exception back to server
exc_type, exc_value, exc_tb = sys.exc_info()
try:
response = dumps(
Fault(1, "%s:%s" % (exc_type, exc_value)),
encoding=self.encoding, allow_none=self.allow_none,
)
finally:
# Break reference cycle
exc_type = exc_value = exc_tb = None
return response.encode(self.encoding, 'xmlcharrefreplace') | [
"def",
"_marshaled_dispatch",
"(",
"self",
",",
"data",
",",
"dispatch_method",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"try",
":",
"params",
",",
"method",
"=",
"loads",
"(",
"data",
",",
"use_builtin_types",
"=",
"self",
".",
"use_builtin_types"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/xmlrpc/server.py#L244-L283 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html.py | python | HtmlHelpFrame.SetTitleFormat | (*args, **kwargs) | return _html.HtmlHelpFrame_SetTitleFormat(*args, **kwargs) | SetTitleFormat(self, String format) | SetTitleFormat(self, String format) | [
"SetTitleFormat",
"(",
"self",
"String",
"format",
")"
] | def SetTitleFormat(*args, **kwargs):
"""SetTitleFormat(self, String format)"""
return _html.HtmlHelpFrame_SetTitleFormat(*args, **kwargs) | [
"def",
"SetTitleFormat",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlHelpFrame_SetTitleFormat",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1754-L1756 | |
facebookincubator/Polygames | eb5390e57cc38e5287bf6dcfb420308a5995d194 | pypolygames/utils/listings.py | python | games | (olympiads: bool = False) | return list(
x.group("name") for x in iterator if not x.group().strip().startswith("//")
) | List games using pattern in core/game.h
Parameters
----------
olympiads: bool
only list olympiad games | List games using pattern in core/game.h | [
"List",
"games",
"using",
"pattern",
"in",
"core",
"/",
"game",
".",
"h"
] | def games(olympiads: bool = False) -> tp.List[str]:
"""List games using pattern in core/game.h
Parameters
----------
olympiads: bool
only list olympiad games
"""
if olympiads:
pies = {"Hex11pie", "Hex13pie", "Hex19pie", "Havannah5pie", "Havannah8pie"} & set(
games()
) # to ready yet
return [
"BlockGo",
"Einstein",
"Othello8",
"Othello10",
"Othello16",
"Minishogi",
"DiceShogi",
"Surakarta",
"Breakthrough",
"Tristannogo",
"GameOfTheAmazons",
] + list(pies)
filepath = Path(__file__).parents[2] / "core" / "game.h"
assert filepath.exists()
pattern = r".*if\s*?\(\s*?isGameNameMatched\s*?\(\s*?\{\s*?\"(?P<name>\w+)\"[^}]*\}\s*?\)\s*?\)\s*?\{.*"
iterator = re.finditer(pattern, filepath.read_text())
return list(
x.group("name") for x in iterator if not x.group().strip().startswith("//")
) | [
"def",
"games",
"(",
"olympiads",
":",
"bool",
"=",
"False",
")",
"->",
"tp",
".",
"List",
"[",
"str",
"]",
":",
"if",
"olympiads",
":",
"pies",
"=",
"{",
"\"Hex11pie\"",
",",
"\"Hex13pie\"",
",",
"\"Hex19pie\"",
",",
"\"Havannah5pie\"",
",",
"\"Havannah... | https://github.com/facebookincubator/Polygames/blob/eb5390e57cc38e5287bf6dcfb420308a5995d194/pypolygames/utils/listings.py#L11-L42 | |
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/mac/Build/cpplint.py | python | IsCppString | (line) | return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant. | Does line terminate so, that the next symbol is in string constant. | [
"Does",
"line",
"terminate",
"so",
"that",
"the",
"next",
"symbol",
"is",
"in",
"string",
"constant",
"."
] | def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant.
"""
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | [
"def",
"IsCppString",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"r'\\\\'",
",",
"'XX'",
")",
"# after this, \\\\\" does not match to \\\"",
"return",
"(",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
... | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/mac/Build/cpplint.py#L674-L688 | |
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | tools/clang/utils/analyzer/CmpRuns.py | python | compareResults | (A, B, opts) | return res | compareResults - Generate a relation from diagnostics in run A to
diagnostics in run B.
The result is the relation as a list of triples (a, b) where
each element {a,b} is None or a matching element from the respective run | compareResults - Generate a relation from diagnostics in run A to
diagnostics in run B. | [
"compareResults",
"-",
"Generate",
"a",
"relation",
"from",
"diagnostics",
"in",
"run",
"A",
"to",
"diagnostics",
"in",
"run",
"B",
"."
] | def compareResults(A, B, opts):
"""
compareResults - Generate a relation from diagnostics in run A to
diagnostics in run B.
The result is the relation as a list of triples (a, b) where
each element {a,b} is None or a matching element from the respective run
"""
res = []
# Map size_before -> size_after
path_difference_data = []
# Quickly eliminate equal elements.
neqA = []
neqB = []
eltsA = list(A.diagnostics)
eltsB = list(B.diagnostics)
eltsA.sort(key=cmpAnalysisDiagnostic)
eltsB.sort(key=cmpAnalysisDiagnostic)
while eltsA and eltsB:
a = eltsA.pop()
b = eltsB.pop()
if (a.getIssueIdentifier() == b.getIssueIdentifier()):
if a.getPathLength() != b.getPathLength():
if opts.relative_path_histogram:
path_difference_data.append(
float(a.getPathLength()) / b.getPathLength())
elif opts.relative_log_path_histogram:
path_difference_data.append(
log(float(a.getPathLength()) / b.getPathLength()))
elif opts.absolute_path_histogram:
path_difference_data.append(
a.getPathLength() - b.getPathLength())
res.append((a, b))
elif a.getIssueIdentifier() > b.getIssueIdentifier():
eltsB.append(b)
neqA.append(a)
else:
eltsA.append(a)
neqB.append(b)
neqA.extend(eltsA)
neqB.extend(eltsB)
# FIXME: Add fuzzy matching. One simple and possible effective idea would
# be to bin the diagnostics, print them in a normalized form (based solely
# on the structure of the diagnostic), compute the diff, then use that as
# the basis for matching. This has the nice property that we don't depend
# in any way on the diagnostic format.
for a in neqA:
res.append((a, None))
for b in neqB:
res.append((None, b))
if opts.relative_log_path_histogram or opts.relative_path_histogram or \
opts.absolute_path_histogram:
from matplotlib import pyplot
pyplot.hist(path_difference_data, bins=100)
pyplot.show()
return res | [
"def",
"compareResults",
"(",
"A",
",",
"B",
",",
"opts",
")",
":",
"res",
"=",
"[",
"]",
"# Map size_before -> size_after",
"path_difference_data",
"=",
"[",
"]",
"# Quickly eliminate equal elements.",
"neqA",
"=",
"[",
"]",
"neqB",
"=",
"[",
"]",
"eltsA",
... | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/utils/analyzer/CmpRuns.py#L202-L265 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py | python | cudnn_lstm | (inputs,
input_h,
input_c,
params,
is_training,
sequence_lengths=None,
time_major=True,
input_mode=CUDNN_INPUT_LINEAR_MODE,
direction=CUDNN_RNN_UNIDIRECTION,
dropout=0.,
seed=0,
num_proj=None,
name=None) | return _cudnn_rnn(inputs, input_h, input_c, params, is_training, CUDNN_LSTM,
sequence_lengths, time_major, input_mode, direction,
dropout, seed, num_proj, name) | Cudnn LSTM.
Args:
inputs: the input sequence to the RNN model. If `time_major` is True
(default), the Tensor shape is [max_time, batch_size, input_size]. If
`time_major` is False, the shape is [batch_size, max_time, input_size].
input_h: the initial hidden state for h. If `time_major` is True (default),
the Tensor shape is [num_layers, batch_size, num_units]. If `time_major`
is False, the shape is [batch_size, num_layers, num_units].
input_c: the initial hidden state for c. This is only relevant for LSTM. A
Tensor of the same shape as input_h.
params: the parameter buffer created for this model.
is_training: whether this operation will be used in training or inference
sequence_lengths: an int32 array representing the variable sequence lengths
in a batch. The size of the array has to equal the batch_size. Default to
None, in which case sequences in the batch are assumed to have the same
length, which is inferred from inputs.
time_major: The shape format of the `inputs` and `outputs` Tensors. If true,
these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If
false, these Tensors must be shaped ['batch_size', 'max_time', 'depth'].
By default this function accepts input and emits output in time-major
form. This param is only effective when 'sequence_lengths' is used.
input_mode: indicate whether there is a linear projection between the input
and the actual computation before the first layer. It could be
'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default)
always applies a linear projection of input onto RNN hidden state.
(standard RNN behavior). 'skip_input' is only allowed when input_size ==
num_units; 'auto_select' implies 'skip_input' when input_size ==
num_units; otherwise, it implies 'linear_input'.
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
seed: the op seed used for initializing dropout. See
`tf.compat.v1.set_random_seed` for behavior.
num_proj: The output dimensionality for the projection matrices.
If None or 0, no projection is performed.
name: name of the operation.
Returns:
outputs, output_h, output_c | Cudnn LSTM. | [
"Cudnn",
"LSTM",
"."
] | def cudnn_lstm(inputs,
input_h,
input_c,
params,
is_training,
sequence_lengths=None,
time_major=True,
input_mode=CUDNN_INPUT_LINEAR_MODE,
direction=CUDNN_RNN_UNIDIRECTION,
dropout=0.,
seed=0,
num_proj=None,
name=None):
"""Cudnn LSTM.
Args:
inputs: the input sequence to the RNN model. If `time_major` is True
(default), the Tensor shape is [max_time, batch_size, input_size]. If
`time_major` is False, the shape is [batch_size, max_time, input_size].
input_h: the initial hidden state for h. If `time_major` is True (default),
the Tensor shape is [num_layers, batch_size, num_units]. If `time_major`
is False, the shape is [batch_size, num_layers, num_units].
input_c: the initial hidden state for c. This is only relevant for LSTM. A
Tensor of the same shape as input_h.
params: the parameter buffer created for this model.
is_training: whether this operation will be used in training or inference
sequence_lengths: an int32 array representing the variable sequence lengths
in a batch. The size of the array has to equal the batch_size. Default to
None, in which case sequences in the batch are assumed to have the same
length, which is inferred from inputs.
time_major: The shape format of the `inputs` and `outputs` Tensors. If true,
these Tensors must be shaped ['max_time', 'batch_size', 'depth']. If
false, these Tensors must be shaped ['batch_size', 'max_time', 'depth'].
By default this function accepts input and emits output in time-major
form. This param is only effective when 'sequence_lengths' is used.
input_mode: indicate whether there is a linear projection between the input
and the actual computation before the first layer. It could be
'linear_input', 'skip_input' or 'auto_select'. 'linear_input' (default)
always applies a linear projection of input onto RNN hidden state.
(standard RNN behavior). 'skip_input' is only allowed when input_size ==
num_units; 'auto_select' implies 'skip_input' when input_size ==
num_units; otherwise, it implies 'linear_input'.
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
seed: the op seed used for initializing dropout. See
`tf.compat.v1.set_random_seed` for behavior.
num_proj: The output dimensionality for the projection matrices.
If None or 0, no projection is performed.
name: name of the operation.
Returns:
outputs, output_h, output_c
"""
return _cudnn_rnn(inputs, input_h, input_c, params, is_training, CUDNN_LSTM,
sequence_lengths, time_major, input_mode, direction,
dropout, seed, num_proj, name) | [
"def",
"cudnn_lstm",
"(",
"inputs",
",",
"input_h",
",",
"input_c",
",",
"params",
",",
"is_training",
",",
"sequence_lengths",
"=",
"None",
",",
"time_major",
"=",
"True",
",",
"input_mode",
"=",
"CUDNN_INPUT_LINEAR_MODE",
",",
"direction",
"=",
"CUDNN_RNN_UNID... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py#L1149-L1205 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py | python | radial_gradient | (mode) | return Image()._new(core.radial_gradient(mode)) | Generate 256x256 radial gradient from black to white, centre to edge.
:param mode: Input mode. | Generate 256x256 radial gradient from black to white, centre to edge. | [
"Generate",
"256x256",
"radial",
"gradient",
"from",
"black",
"to",
"white",
"centre",
"to",
"edge",
"."
] | def radial_gradient(mode):
"""
Generate 256x256 radial gradient from black to white, centre to edge.
:param mode: Input mode.
"""
return Image()._new(core.radial_gradient(mode)) | [
"def",
"radial_gradient",
"(",
"mode",
")",
":",
"return",
"Image",
"(",
")",
".",
"_new",
"(",
"core",
".",
"radial_gradient",
"(",
"mode",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py#L3165-L3171 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/parso/py2/parso/tree.py | python | Leaf.__init__ | (self, value, start_pos, prefix='') | :py:func:`str` The value of the current token. | :py:func:`str` The value of the current token. | [
":",
"py",
":",
"func",
":",
"str",
"The",
"value",
"of",
"the",
"current",
"token",
"."
] | def __init__(self, value, start_pos, prefix=''):
self.value = value
'''
:py:func:`str` The value of the current token.
'''
self.start_pos = start_pos
self.prefix = prefix
'''
:py:func:`str` Typically a mixture of whitespace and comments. Stuff
that is syntactically irrelevant for the syntax tree.
'''
self.parent = None
'''
The parent :class:`BaseNode` of this leaf.
''' | [
"def",
"__init__",
"(",
"self",
",",
"value",
",",
"start_pos",
",",
"prefix",
"=",
"''",
")",
":",
"self",
".",
"value",
"=",
"value",
"self",
".",
"start_pos",
"=",
"start_pos",
"self",
".",
"prefix",
"=",
"prefix",
"'''\n :py:func:`str` Typically a... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/parso/py2/parso/tree.py#L185-L199 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiToolBarItem.HasDropDown | (*args, **kwargs) | return _aui.AuiToolBarItem_HasDropDown(*args, **kwargs) | HasDropDown(self) -> bool | HasDropDown(self) -> bool | [
"HasDropDown",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasDropDown(*args, **kwargs):
"""HasDropDown(self) -> bool"""
return _aui.AuiToolBarItem_HasDropDown(*args, **kwargs) | [
"def",
"HasDropDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBarItem_HasDropDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1853-L1855 | |
0ad/0ad | f58db82e0e925016d83f4e3fa7ca599e3866e2af | source/tools/lobbybots/xpartamupp/lobby_ranking.py | python | parse_args | (args) | return parser.parse_args(args) | Parse command line arguments.
Arguments:
args (dict): Raw command line arguments given to the script
Returns:
Parsed command line arguments | Parse command line arguments. | [
"Parse",
"command",
"line",
"arguments",
"."
] | def parse_args(args):
"""Parse command line arguments.
Arguments:
args (dict): Raw command line arguments given to the script
Returns:
Parsed command line arguments
"""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="Helper command for database creation")
parser.add_argument('action', help='Action to apply to the database',
choices=['create'])
parser.add_argument('--database-url', help='URL for the leaderboard database',
default='sqlite:///lobby_rankings.sqlite3')
return parser.parse_args(args) | [
"def",
"parse_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
",",
"description",
"=",
"\"Helper command for database creation\"",
")",
"parser",
".",
"add_a... | https://github.com/0ad/0ad/blob/f58db82e0e925016d83f4e3fa7ca599e3866e2af/source/tools/lobbybots/xpartamupp/lobby_ranking.py#L147-L163 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py | python | get_target_platform_detail | (ctx, platform_name) | Get a PlatformDetail object based on a platform name
:param ctx: Context
:param platform_name: Name of the platform to look up
:exception Errors.WafError | Get a PlatformDetail object based on a platform name
:param ctx: Context
:param platform_name: Name of the platform to look up
:exception Errors.WafError | [
"Get",
"a",
"PlatformDetail",
"object",
"based",
"on",
"a",
"platform",
"name",
":",
"param",
"ctx",
":",
"Context",
":",
"param",
"platform_name",
":",
"Name",
"of",
"the",
"platform",
"to",
"look",
"up",
":",
"exception",
"Errors",
".",
"WafError"
] | def get_target_platform_detail(ctx, platform_name):
"""
Get a PlatformDetail object based on a platform name
:param ctx: Context
:param platform_name: Name of the platform to look up
:exception Errors.WafError
"""
try:
return PLATFORM_MAP[platform_name]
except KeyError:
raise Exception("Invalid platform name '{}'. Make sure it is defined in the platform configuration file.".format(platform_name)) | [
"def",
"get_target_platform_detail",
"(",
"ctx",
",",
"platform_name",
")",
":",
"try",
":",
"return",
"PLATFORM_MAP",
"[",
"platform_name",
"]",
"except",
"KeyError",
":",
"raise",
"Exception",
"(",
"\"Invalid platform name '{}'. Make sure it is defined in the platform con... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py#L629-L639 | ||
qt-creator/qt-creator | c9cd00f2ce590e9b272ad69214dc910e92bf62eb | share/qtcreator/debugger/dumper.py | python | DumperBase.handleInterpreterMessage | (self) | return resdict.get('event') == 'break' | Return True if inferior stopped | Return True if inferior stopped | [
"Return",
"True",
"if",
"inferior",
"stopped"
] | def handleInterpreterMessage(self):
""" Return True if inferior stopped """
resdict = self.fetchInterpreterResult()
return resdict.get('event') == 'break' | [
"def",
"handleInterpreterMessage",
"(",
"self",
")",
":",
"resdict",
"=",
"self",
".",
"fetchInterpreterResult",
"(",
")",
"return",
"resdict",
".",
"get",
"(",
"'event'",
")",
"==",
"'break'"
] | https://github.com/qt-creator/qt-creator/blob/c9cd00f2ce590e9b272ad69214dc910e92bf62eb/share/qtcreator/debugger/dumper.py#L2595-L2598 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | ChildFocusEvent.__init__ | (self, *args, **kwargs) | __init__(self, Window win=None) -> ChildFocusEvent
Constructor | __init__(self, Window win=None) -> ChildFocusEvent | [
"__init__",
"(",
"self",
"Window",
"win",
"=",
"None",
")",
"-",
">",
"ChildFocusEvent"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window win=None) -> ChildFocusEvent
Constructor
"""
_core_.ChildFocusEvent_swiginit(self,_core_.new_ChildFocusEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_core_",
".",
"ChildFocusEvent_swiginit",
"(",
"self",
",",
"_core_",
".",
"new_ChildFocusEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L6342-L6348 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/rospkg/rospack.py | python | list_by_path | (manifest_name, path, cache) | return resources | List ROS stacks or packages within the specified path.
The cache will be updated with the resource->path
mappings. list_by_path() does NOT returned cached results
-- it only updates the cache.
:param manifest_name: MANIFEST_FILE or STACK_FILE, ``str``
:param path: path to list resources in, ``str``
:param cache: path cache to update. Maps resource name to directory path, ``{str: str}``
:returns: complete list of resources in ROS environment, ``[str]`` | List ROS stacks or packages within the specified path. | [
"List",
"ROS",
"stacks",
"or",
"packages",
"within",
"the",
"specified",
"path",
"."
] | def list_by_path(manifest_name, path, cache):
"""
List ROS stacks or packages within the specified path.
The cache will be updated with the resource->path
mappings. list_by_path() does NOT returned cached results
-- it only updates the cache.
:param manifest_name: MANIFEST_FILE or STACK_FILE, ``str``
:param path: path to list resources in, ``str``
:param cache: path cache to update. Maps resource name to directory path, ``{str: str}``
:returns: complete list of resources in ROS environment, ``[str]``
"""
resources = []
path = os.path.abspath(path)
basename = os.path.basename
for d, dirs, files in os.walk(path, topdown=True, followlinks=True):
if 'CATKIN_IGNORE' in files:
del dirs[:]
continue #leaf
if PACKAGE_FILE in files:
# parse package.xml and decide if it matches the search criteria
root = ElementTree(None, os.path.join(d, PACKAGE_FILE))
is_metapackage = root.find('./export/metapackage') is not None
if ((manifest_name == STACK_FILE and is_metapackage) or
(manifest_name == MANIFEST_FILE and not is_metapackage) or
manifest_name == PACKAGE_FILE):
resource_name = root.findtext('name').strip(' \n\r\t')
if resource_name not in resources:
resources.append(resource_name)
if cache is not None:
cache[resource_name] = d
del dirs[:]
continue #leaf
if manifest_name in files:
resource_name = basename(d)
if resource_name not in resources:
resources.append(resource_name)
if cache is not None:
cache[resource_name] = d
del dirs[:]
continue #leaf
elif MANIFEST_FILE in files or PACKAGE_FILE in files:
# noop if manifest_name==MANIFEST_FILE, but a good
# optimization for stacks.
del dirs[:]
continue #leaf
elif 'rospack_nosubdirs' in files:
del dirs[:]
continue #leaf
# remove hidden dirs (esp. .svn/.git)
[dirs.remove(di) for di in dirs if di[0] == '.']
return resources | [
"def",
"list_by_path",
"(",
"manifest_name",
",",
"path",
",",
"cache",
")",
":",
"resources",
"=",
"[",
"]",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"for",
"d",
",",
"d... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/rospkg/rospack.py#L45-L97 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/devtools_monitor.py | python | Listener.__init__ | (self, connection) | Initializes a Listener instance.
Args:
connection: (DevToolsConnection). | Initializes a Listener instance. | [
"Initializes",
"a",
"Listener",
"instance",
"."
] | def __init__(self, connection):
"""Initializes a Listener instance.
Args:
connection: (DevToolsConnection).
"""
pass | [
"def",
"__init__",
"(",
"self",
",",
"connection",
")",
":",
"pass"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/devtools_monitor.py#L439-L445 | ||
wisdompeak/LeetCode | ef729c1249ead3ead47f1a94b5eeb5958a69e152 | Greedy/435.Non-overlapping-Intervals/435.Non-overlapping-Intervals.py | python | Solution.eraseOverlapIntervals | (self, intervals) | return count | :type intervals: List[Interval]
:rtype: int | :type intervals: List[Interval]
:rtype: int | [
":",
"type",
"intervals",
":",
"List",
"[",
"Interval",
"]",
":",
"rtype",
":",
"int"
] | def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
intervals = sorted(intervals,key=lambda x:x.end)
count,j = 0,0
while j<len(intervals):
right = intervals[j].end
j+=1
while j<len(intervals) and intervals[j].start<right:
j+=1
count+=1
return count | [
"def",
"eraseOverlapIntervals",
"(",
"self",
",",
"intervals",
")",
":",
"intervals",
"=",
"sorted",
"(",
"intervals",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"end",
")",
"count",
",",
"j",
"=",
"0",
",",
"0",
"while",
"j",
"<",
"len",
"(",
... | https://github.com/wisdompeak/LeetCode/blob/ef729c1249ead3ead47f1a94b5eeb5958a69e152/Greedy/435.Non-overlapping-Intervals/435.Non-overlapping-Intervals.py#L8-L21 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/multitype_ops/_compile_utils.py | python | _transform_indexing_tensor | (broadcast_shape, final_shape, new_shape, item) | return _broadcast(final_shape, F.reshape(item, new_shape)) | Transform indexing tensor to the required. | Transform indexing tensor to the required. | [
"Transform",
"indexing",
"tensor",
"to",
"the",
"required",
"."
] | def _transform_indexing_tensor(broadcast_shape, final_shape, new_shape, item):
"""Transform indexing tensor to the required."""
item = _broadcast(broadcast_shape, item)
return _broadcast(final_shape, F.reshape(item, new_shape)) | [
"def",
"_transform_indexing_tensor",
"(",
"broadcast_shape",
",",
"final_shape",
",",
"new_shape",
",",
"item",
")",
":",
"item",
"=",
"_broadcast",
"(",
"broadcast_shape",
",",
"item",
")",
"return",
"_broadcast",
"(",
"final_shape",
",",
"F",
".",
"reshape",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/_compile_utils.py#L228-L231 | |
ufal/udpipe | e51f02d2744cdfd4a29efc1320644ea04d535f0b | doc/t2t_docsys/txt2tags.py | python | CommandLine._compose_long_opts | (self) | return ret | Returns a list with all the valid long options/flags | Returns a list with all the valid long options/flags | [
"Returns",
"a",
"list",
"with",
"all",
"the",
"valid",
"long",
"options",
"/",
"flags"
] | def _compose_long_opts(self):
"Returns a list with all the valid long options/flags"
ret = [x+'=' for x in self.all_options] # add =
ret.extend(self.all_flags) # flag ON
ret.extend(self.all_actions) # actions
ret.extend(['no-'+x for x in self.all_flags]) # add no-*
ret.extend(['no-style','no-encoding']) # turn OFF
ret.extend(['no-outfile','no-infile']) # turn OFF
ret.extend(['no-dump-config', 'no-dump-source']) # turn OFF
ret.extend(['no-targets']) # turn OFF
#Debug('Valid LONG options: %s'%ret)
return ret | [
"def",
"_compose_long_opts",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"x",
"+",
"'='",
"for",
"x",
"in",
"self",
".",
"all_options",
"]",
"# add =",
"ret",
".",
"extend",
"(",
"self",
".",
"all_flags",
")",
"# flag ON",
"ret",
".",
"extend",
"(",
"sel... | https://github.com/ufal/udpipe/blob/e51f02d2744cdfd4a29efc1320644ea04d535f0b/doc/t2t_docsys/txt2tags.py#L2375-L2386 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.