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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
glotzerlab/hoomd-blue
|
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
|
hoomd/communicator.py
|
python
|
Communicator.barrier
|
(self)
|
Perform a barrier synchronization across all ranks in the partition.
Note:
Does nothing in builds with ENABLE_MPI=off.
|
Perform a barrier synchronization across all ranks in the partition.
|
[
"Perform",
"a",
"barrier",
"synchronization",
"across",
"all",
"ranks",
"in",
"the",
"partition",
"."
] |
def barrier(self):
"""Perform a barrier synchronization across all ranks in the partition.
Note:
Does nothing in builds with ENABLE_MPI=off.
"""
if hoomd.version.mpi_enabled:
self.cpp_mpi_conf.barrier()
|
[
"def",
"barrier",
"(",
"self",
")",
":",
"if",
"hoomd",
".",
"version",
".",
"mpi_enabled",
":",
"self",
".",
"cpp_mpi_conf",
".",
"barrier",
"(",
")"
] |
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/communicator.py#L154-L161
|
||
tensorflow/tensorflow
|
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
|
tensorflow/python/distribute/values_util.py
|
python
|
is_saving_non_distributed
|
()
|
return (options.experimental_variable_policy !=
save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES)
|
Returns whether we're saving a non-distributed version of the model.
It returns True iff we are in saving context and are saving a non-distributed
version of the model. That is, SaveOptions.experimental_variable_policy is
NONE.
Returns:
A boolean.
|
Returns whether we're saving a non-distributed version of the model.
|
[
"Returns",
"whether",
"we",
"re",
"saving",
"a",
"non",
"-",
"distributed",
"version",
"of",
"the",
"model",
"."
] |
def is_saving_non_distributed():
"""Returns whether we're saving a non-distributed version of the model.
It returns True iff we are in saving context and are saving a non-distributed
version of the model. That is, SaveOptions.experimental_variable_policy is
NONE.
Returns:
A boolean.
"""
if not save_context.in_save_context():
return False
options = save_context.get_save_options()
return (options.experimental_variable_policy !=
save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES)
|
[
"def",
"is_saving_non_distributed",
"(",
")",
":",
"if",
"not",
"save_context",
".",
"in_save_context",
"(",
")",
":",
"return",
"False",
"options",
"=",
"save_context",
".",
"get_save_options",
"(",
")",
"return",
"(",
"options",
".",
"experimental_variable_policy",
"!=",
"save_options",
".",
"VariablePolicy",
".",
"EXPAND_DISTRIBUTED_VARIABLES",
")"
] |
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/values_util.py#L355-L369
|
|
OpenChemistry/tomviz
|
0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a
|
acquisition/tomviz/acquisition/__init__.py
|
python
|
AbstractSource.disconnect
|
(self, **params)
|
Disconnect from the source.
:param params: The disconnect parameters.
:type params: dict
|
Disconnect from the source.
|
[
"Disconnect",
"from",
"the",
"source",
"."
] |
def disconnect(self, **params):
"""
Disconnect from the source.
:param params: The disconnect parameters.
:type params: dict
"""
|
[
"def",
"disconnect",
"(",
"self",
",",
"*",
"*",
"params",
")",
":"
] |
https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/acquisition/tomviz/acquisition/__init__.py#L25-L31
|
||
simsong/bulk_extractor
|
738911df22b7066ca9e1662f4131fb44090a4196
|
python/dfxml.py
|
python
|
safe_b64decode
|
(b64data)
|
This function takes care of the logistics of base64 decoding XML data in Python 2 and 3.
Recall that Python3 requires b64decode operate on bytes, not a string.
Ref: <http://bugs.python.org/issue4769#msg115690>
A forum post that noted several encoding differences between Python 2 and 3:
<http://stackoverflow.com/questions/9327993/python3-unicode-escape-doesnt-work-with-non-ascii-bytes>
|
This function takes care of the logistics of base64 decoding XML data in Python 2 and 3.
Recall that Python3 requires b64decode operate on bytes, not a string.
Ref: <http://bugs.python.org/issue4769#msg115690>
A forum post that noted several encoding differences between Python 2 and 3:
<http://stackoverflow.com/questions/9327993/python3-unicode-escape-doesnt-work-with-non-ascii-bytes>
|
[
"This",
"function",
"takes",
"care",
"of",
"the",
"logistics",
"of",
"base64",
"decoding",
"XML",
"data",
"in",
"Python",
"2",
"and",
"3",
".",
"Recall",
"that",
"Python3",
"requires",
"b64decode",
"operate",
"on",
"bytes",
"not",
"a",
"string",
".",
"Ref",
":",
"<http",
":",
"//",
"bugs",
".",
"python",
".",
"org",
"/",
"issue4769#msg115690",
">",
"A",
"forum",
"post",
"that",
"noted",
"several",
"encoding",
"differences",
"between",
"Python",
"2",
"and",
"3",
":",
"<http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"9327993",
"/",
"python3",
"-",
"unicode",
"-",
"escape",
"-",
"doesnt",
"-",
"work",
"-",
"with",
"-",
"non",
"-",
"ascii",
"-",
"bytes",
">"
] |
def safe_b64decode(b64data):
"""
This function takes care of the logistics of base64 decoding XML data in Python 2 and 3.
Recall that Python3 requires b64decode operate on bytes, not a string.
Ref: <http://bugs.python.org/issue4769#msg115690>
A forum post that noted several encoding differences between Python 2 and 3:
<http://stackoverflow.com/questions/9327993/python3-unicode-escape-doesnt-work-with-non-ascii-bytes>
"""
if sys.version_info.major == 2:
return base64.b64decode(b64data).decode("unicode_escape")
elif sys.version_info.major == 3:
dtype = str(type(b64data))
to_decode = None
if dtype == "<class 'str'>":
to_decode = b64data.encode("ascii")
elif dtype == "<class 'bytes'>":
to_decode = b64data
return base64.b64decode(to_decode).decode("unicode_escape")
else:
raise Exception("Not sure how to parse base64 data outside Python versions 2 or 3.")
|
[
"def",
"safe_b64decode",
"(",
"b64data",
")",
":",
"if",
"sys",
".",
"version_info",
".",
"major",
"==",
"2",
":",
"return",
"base64",
".",
"b64decode",
"(",
"b64data",
")",
".",
"decode",
"(",
"\"unicode_escape\"",
")",
"elif",
"sys",
".",
"version_info",
".",
"major",
"==",
"3",
":",
"dtype",
"=",
"str",
"(",
"type",
"(",
"b64data",
")",
")",
"to_decode",
"=",
"None",
"if",
"dtype",
"==",
"\"<class 'str'>\"",
":",
"to_decode",
"=",
"b64data",
".",
"encode",
"(",
"\"ascii\"",
")",
"elif",
"dtype",
"==",
"\"<class 'bytes'>\"",
":",
"to_decode",
"=",
"b64data",
"return",
"base64",
".",
"b64decode",
"(",
"to_decode",
")",
".",
"decode",
"(",
"\"unicode_escape\"",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Not sure how to parse base64 data outside Python versions 2 or 3.\"",
")"
] |
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L1005-L1024
|
||
PaddlePaddle/Paddle
|
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
|
python/paddle/nn/functional/pooling.py
|
python
|
adaptive_avg_pool2d
|
(x, output_size, data_format='NCHW', name=None)
|
return pool_out
|
This API implements adaptive average pooling 2d operation.
See more details in :ref:`api_nn_pooling_AdaptiveAvgPool2d` .
Args:
x (Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor.
The data type can be float32 or float64.
output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
it must contain two element, (H, W). H and W can be either a int, or None which means
the size will be the same as that of the input.
data_format (str): The data format of the input and output data. An optional string
from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in
the order of: [batch_size, input_channels, input_height, input_width].
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tensor: The output tensor of avg adaptive pool2d result. The data type is same as input tensor.
Raises:
ValueError: If `data_format` is not "NCHW" or "NHWC".
Examples:
.. code-block:: python
# adaptive avg pool2d
# suppose input data in shape of [N, C, H, W], `output_size` is [m, n],
# output shape is [N, C, m, n], adaptive pool divide H and W dimensions
# of input data into m * n grids averagely and performs poolings in each
# grid to get output.
# adaptive avg pool performs calculations as follow:
#
# for i in range(m):
# for j in range(n):
# hstart = floor(i * H / m)
# hend = ceil((i + 1) * H / m)
# wstart = floor(i * W / n)
# wend = ceil((i + 1) * W / n)
# output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend])
#
import paddle
import numpy as np
input_data = np.random.rand(2, 3, 32, 32)
x = paddle.to_tensor(input_data)
# x.shape is [2, 3, 32, 32]
out = paddle.nn.functional.adaptive_avg_pool2d(
x = x,
output_size=[3, 3])
# out.shape is [2, 3, 3, 3]
|
This API implements adaptive average pooling 2d operation.
See more details in :ref:`api_nn_pooling_AdaptiveAvgPool2d` .
|
[
"This",
"API",
"implements",
"adaptive",
"average",
"pooling",
"2d",
"operation",
".",
"See",
"more",
"details",
"in",
":",
"ref",
":",
"api_nn_pooling_AdaptiveAvgPool2d",
"."
] |
def adaptive_avg_pool2d(x, output_size, data_format='NCHW', name=None):
"""
This API implements adaptive average pooling 2d operation.
See more details in :ref:`api_nn_pooling_AdaptiveAvgPool2d` .
Args:
x (Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor.
The data type can be float32 or float64.
output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
it must contain two element, (H, W). H and W can be either a int, or None which means
the size will be the same as that of the input.
data_format (str): The data format of the input and output data. An optional string
from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in
the order of: [batch_size, input_channels, input_height, input_width].
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tensor: The output tensor of avg adaptive pool2d result. The data type is same as input tensor.
Raises:
ValueError: If `data_format` is not "NCHW" or "NHWC".
Examples:
.. code-block:: python
# adaptive avg pool2d
# suppose input data in shape of [N, C, H, W], `output_size` is [m, n],
# output shape is [N, C, m, n], adaptive pool divide H and W dimensions
# of input data into m * n grids averagely and performs poolings in each
# grid to get output.
# adaptive avg pool performs calculations as follow:
#
# for i in range(m):
# for j in range(n):
# hstart = floor(i * H / m)
# hend = ceil((i + 1) * H / m)
# wstart = floor(i * W / n)
# wend = ceil((i + 1) * W / n)
# output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend])
#
import paddle
import numpy as np
input_data = np.random.rand(2, 3, 32, 32)
x = paddle.to_tensor(input_data)
# x.shape is [2, 3, 32, 32]
out = paddle.nn.functional.adaptive_avg_pool2d(
x = x,
output_size=[3, 3])
# out.shape is [2, 3, 3, 3]
"""
if not in_dygraph_mode():
check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'],
'adaptive_avg_pool2d')
check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d')
if data_format not in ["NCHW", "NHWC"]:
raise ValueError(
"Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
"Attr(data_format): %s." % str(data_format))
if data_format == "NCHW":
in_h, in_w = x.shape[2:4]
else:
in_h, in_w = x.shape[1:3]
if isinstance(output_size, int):
output_size = utils.convert_to_list(output_size, 2, 'output_size')
else:
output_size = list(output_size)
if output_size[0] == None:
output_size[0] = in_h
if output_size[1] == None:
output_size[1] = in_w
if in_dygraph_mode():
output = _C_ops.pool2d(x, 'pooling_type', 'avg', 'ksize', output_size,
'global_pooling', False, 'adaptive', True,
'data_format', data_format)
return output
l_type = 'pool2d'
helper = LayerHelper(l_type, **locals())
dtype = helper.input_dtype(input_param_name='x')
pool_out = helper.create_variable_for_type_inference(dtype)
outputs = {"Out": pool_out}
helper.append_op(
type=l_type,
inputs={"X": x},
outputs=outputs,
attrs={
"pooling_type": "avg",
"ksize": output_size,
"adaptive": True,
"data_format": data_format,
})
return pool_out
|
[
"def",
"adaptive_avg_pool2d",
"(",
"x",
",",
"output_size",
",",
"data_format",
"=",
"'NCHW'",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"in_dygraph_mode",
"(",
")",
":",
"check_variable_and_dtype",
"(",
"x",
",",
"'x'",
",",
"[",
"'float16'",
",",
"'float32'",
",",
"'float64'",
"]",
",",
"'adaptive_avg_pool2d'",
")",
"check_type",
"(",
"data_format",
",",
"'data_format'",
",",
"str",
",",
"'adaptive_avg_pool2d'",
")",
"if",
"data_format",
"not",
"in",
"[",
"\"NCHW\"",
",",
"\"NHWC\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"Attr(data_format) should be 'NCHW' or 'NHWC'. Received \"",
"\"Attr(data_format): %s.\"",
"%",
"str",
"(",
"data_format",
")",
")",
"if",
"data_format",
"==",
"\"NCHW\"",
":",
"in_h",
",",
"in_w",
"=",
"x",
".",
"shape",
"[",
"2",
":",
"4",
"]",
"else",
":",
"in_h",
",",
"in_w",
"=",
"x",
".",
"shape",
"[",
"1",
":",
"3",
"]",
"if",
"isinstance",
"(",
"output_size",
",",
"int",
")",
":",
"output_size",
"=",
"utils",
".",
"convert_to_list",
"(",
"output_size",
",",
"2",
",",
"'output_size'",
")",
"else",
":",
"output_size",
"=",
"list",
"(",
"output_size",
")",
"if",
"output_size",
"[",
"0",
"]",
"==",
"None",
":",
"output_size",
"[",
"0",
"]",
"=",
"in_h",
"if",
"output_size",
"[",
"1",
"]",
"==",
"None",
":",
"output_size",
"[",
"1",
"]",
"=",
"in_w",
"if",
"in_dygraph_mode",
"(",
")",
":",
"output",
"=",
"_C_ops",
".",
"pool2d",
"(",
"x",
",",
"'pooling_type'",
",",
"'avg'",
",",
"'ksize'",
",",
"output_size",
",",
"'global_pooling'",
",",
"False",
",",
"'adaptive'",
",",
"True",
",",
"'data_format'",
",",
"data_format",
")",
"return",
"output",
"l_type",
"=",
"'pool2d'",
"helper",
"=",
"LayerHelper",
"(",
"l_type",
",",
"*",
"*",
"locals",
"(",
")",
")",
"dtype",
"=",
"helper",
".",
"input_dtype",
"(",
"input_param_name",
"=",
"'x'",
")",
"pool_out",
"=",
"helper",
".",
"create_variable_for_type_inference",
"(",
"dtype",
")",
"outputs",
"=",
"{",
"\"Out\"",
":",
"pool_out",
"}",
"helper",
".",
"append_op",
"(",
"type",
"=",
"l_type",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"x",
"}",
",",
"outputs",
"=",
"outputs",
",",
"attrs",
"=",
"{",
"\"pooling_type\"",
":",
"\"avg\"",
",",
"\"ksize\"",
":",
"output_size",
",",
"\"adaptive\"",
":",
"True",
",",
"\"data_format\"",
":",
"data_format",
",",
"}",
")",
"return",
"pool_out"
] |
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/functional/pooling.py#L1286-L1385
|
|
OSGeo/gdal
|
3748fc4ba4fba727492774b2b908a2130c864a83
|
swig/python/osgeo/ogr.py
|
python
|
FeatureDefn.GetGeomFieldIndex
|
(self, *args)
|
return _ogr.FeatureDefn_GetGeomFieldIndex(self, *args)
|
r"""
GetGeomFieldIndex(FeatureDefn self, char const * field_name) -> int
int
OGR_FD_GetGeomFieldIndex(OGRFeatureDefnH hDefn, const char
*pszGeomFieldName)
Find geometry field by name.
The geometry field index of the first geometry field matching the
passed field name (case insensitively) is returned.
This function is the same as the C++ method
OGRFeatureDefn::GetGeomFieldIndex.
Parameters:
-----------
hDefn: handle to the feature definition to get field index from.
pszGeomFieldName: the geometry field name to search for.
the geometry field index, or -1 if no match found.
|
r"""
GetGeomFieldIndex(FeatureDefn self, char const * field_name) -> int
int
OGR_FD_GetGeomFieldIndex(OGRFeatureDefnH hDefn, const char
*pszGeomFieldName)
|
[
"r",
"GetGeomFieldIndex",
"(",
"FeatureDefn",
"self",
"char",
"const",
"*",
"field_name",
")",
"-",
">",
"int",
"int",
"OGR_FD_GetGeomFieldIndex",
"(",
"OGRFeatureDefnH",
"hDefn",
"const",
"char",
"*",
"pszGeomFieldName",
")"
] |
def GetGeomFieldIndex(self, *args):
r"""
GetGeomFieldIndex(FeatureDefn self, char const * field_name) -> int
int
OGR_FD_GetGeomFieldIndex(OGRFeatureDefnH hDefn, const char
*pszGeomFieldName)
Find geometry field by name.
The geometry field index of the first geometry field matching the
passed field name (case insensitively) is returned.
This function is the same as the C++ method
OGRFeatureDefn::GetGeomFieldIndex.
Parameters:
-----------
hDefn: handle to the feature definition to get field index from.
pszGeomFieldName: the geometry field name to search for.
the geometry field index, or -1 if no match found.
"""
return _ogr.FeatureDefn_GetGeomFieldIndex(self, *args)
|
[
"def",
"GetGeomFieldIndex",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"FeatureDefn_GetGeomFieldIndex",
"(",
"self",
",",
"*",
"args",
")"
] |
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L4658-L4682
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_core.py
|
python
|
BookCtrlBase.ChangeSelection
|
(*args, **kwargs)
|
return _core_.BookCtrlBase_ChangeSelection(*args, **kwargs)
|
ChangeSelection(self, size_t n) -> int
|
ChangeSelection(self, size_t n) -> int
|
[
"ChangeSelection",
"(",
"self",
"size_t",
"n",
")",
"-",
">",
"int"
] |
def ChangeSelection(*args, **kwargs):
"""ChangeSelection(self, size_t n) -> int"""
return _core_.BookCtrlBase_ChangeSelection(*args, **kwargs)
|
[
"def",
"ChangeSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"BookCtrlBase_ChangeSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13637-L13639
|
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py
|
python
|
StreamWriter.writelines
|
(self, list)
|
Writes the concatenated list of strings to the stream
using .write().
|
Writes the concatenated list of strings to the stream
using .write().
|
[
"Writes",
"the",
"concatenated",
"list",
"of",
"strings",
"to",
"the",
"stream",
"using",
".",
"write",
"()",
"."
] |
def writelines(self, list):
""" Writes the concatenated list of strings to the stream
using .write().
"""
self.write(''.join(list))
|
[
"def",
"writelines",
"(",
"self",
",",
"list",
")",
":",
"self",
".",
"write",
"(",
"''",
".",
"join",
"(",
"list",
")",
")"
] |
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py#L354-L359
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scipy/py3/scipy/sparse/base.py
|
python
|
spmatrix.setdiag
|
(self, values, k=0)
|
Set diagonal or off-diagonal elements of the array.
Parameters
----------
values : array_like
New values of the diagonal elements.
Values may have any length. If the diagonal is longer than values,
then the remaining diagonal entries will not be set. If values if
longer than the diagonal, then the remaining values are ignored.
If a scalar value is given, all of the diagonal is set to it.
k : int, optional
Which off-diagonal to set, corresponding to elements a[i,i+k].
Default: 0 (the main diagonal).
|
Set diagonal or off-diagonal elements of the array.
|
[
"Set",
"diagonal",
"or",
"off",
"-",
"diagonal",
"elements",
"of",
"the",
"array",
"."
] |
def setdiag(self, values, k=0):
"""
Set diagonal or off-diagonal elements of the array.
Parameters
----------
values : array_like
New values of the diagonal elements.
Values may have any length. If the diagonal is longer than values,
then the remaining diagonal entries will not be set. If values if
longer than the diagonal, then the remaining values are ignored.
If a scalar value is given, all of the diagonal is set to it.
k : int, optional
Which off-diagonal to set, corresponding to elements a[i,i+k].
Default: 0 (the main diagonal).
"""
M, N = self.shape
if (k > 0 and k >= N) or (k < 0 and -k >= M):
raise ValueError("k exceeds matrix dimensions")
self._setdiag(np.asarray(values), k)
|
[
"def",
"setdiag",
"(",
"self",
",",
"values",
",",
"k",
"=",
"0",
")",
":",
"M",
",",
"N",
"=",
"self",
".",
"shape",
"if",
"(",
"k",
">",
"0",
"and",
"k",
">=",
"N",
")",
"or",
"(",
"k",
"<",
"0",
"and",
"-",
"k",
">=",
"M",
")",
":",
"raise",
"ValueError",
"(",
"\"k exceeds matrix dimensions\"",
")",
"self",
".",
"_setdiag",
"(",
"np",
".",
"asarray",
"(",
"values",
")",
",",
"k",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/base.py#L1122-L1145
|
||
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem.py
|
python
|
FakeOsModule.lstat
|
(self, entry_path)
|
Returns the os.stat-like tuple for entry_path, not following symlinks.
Args:
entry_path: path to filesystem object to retrieve
Returns:
the os.stat_result object corresponding to entry_path
Raises:
OSError: if the filesystem object doesn't exist.
|
Returns the os.stat-like tuple for entry_path, not following symlinks.
|
[
"Returns",
"the",
"os",
".",
"stat",
"-",
"like",
"tuple",
"for",
"entry_path",
"not",
"following",
"symlinks",
"."
] |
def lstat(self, entry_path):
"""Returns the os.stat-like tuple for entry_path, not following symlinks.
Args:
entry_path: path to filesystem object to retrieve
Returns:
the os.stat_result object corresponding to entry_path
Raises:
OSError: if the filesystem object doesn't exist.
"""
# stat should return the tuple representing return value of os.stat
try:
stats = self.filesystem.LResolveObject(entry_path)
st_obj = os.stat_result((stats.st_mode, stats.st_ino, stats.st_dev,
stats.st_nlink, stats.st_uid, stats.st_gid,
stats.st_size, stats.st_atime,
stats.st_mtime, stats.st_ctime))
return st_obj
except IOError as io_error:
raise OSError(io_error.errno, io_error.strerror, entry_path)
|
[
"def",
"lstat",
"(",
"self",
",",
"entry_path",
")",
":",
"# stat should return the tuple representing return value of os.stat",
"try",
":",
"stats",
"=",
"self",
".",
"filesystem",
".",
"LResolveObject",
"(",
"entry_path",
")",
"st_obj",
"=",
"os",
".",
"stat_result",
"(",
"(",
"stats",
".",
"st_mode",
",",
"stats",
".",
"st_ino",
",",
"stats",
".",
"st_dev",
",",
"stats",
".",
"st_nlink",
",",
"stats",
".",
"st_uid",
",",
"stats",
".",
"st_gid",
",",
"stats",
".",
"st_size",
",",
"stats",
".",
"st_atime",
",",
"stats",
".",
"st_mtime",
",",
"stats",
".",
"st_ctime",
")",
")",
"return",
"st_obj",
"except",
"IOError",
"as",
"io_error",
":",
"raise",
"OSError",
"(",
"io_error",
".",
"errno",
",",
"io_error",
".",
"strerror",
",",
"entry_path",
")"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L1505-L1526
|
||
miyosuda/TensorFlowAndroidDemo
|
35903e0221aa5f109ea2dbef27f20b52e317f42d
|
jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py
|
python
|
_MergeShape
|
(op)
|
Shape function for the Merge op.
The Merge op takes many inputs of arbitrary shapes, and produces a
first output that is one of those inputs, and a second scalar
output.
If all input shapes are known and have the same rank, the output
shape must have that rank, otherwise the output shape is unknown.
Each output dimension is specified only if that dimension in all
inputs are the same.
Args:
op: A Merge Operation.
Returns:
A single-element list containing the Shape of the Merge op.
|
Shape function for the Merge op.
|
[
"Shape",
"function",
"for",
"the",
"Merge",
"op",
"."
] |
def _MergeShape(op):
"""Shape function for the Merge op.
The Merge op takes many inputs of arbitrary shapes, and produces a
first output that is one of those inputs, and a second scalar
output.
If all input shapes are known and have the same rank, the output
shape must have that rank, otherwise the output shape is unknown.
Each output dimension is specified only if that dimension in all
inputs are the same.
Args:
op: A Merge Operation.
Returns:
A single-element list containing the Shape of the Merge op.
"""
output_shape = op.inputs[0].get_shape()
if output_shape.dims is None:
return [tensor_shape.unknown_shape(), tensor_shape.scalar()]
else:
for input_ in op.inputs[1:]:
input_shape = input_.get_shape()
if input_shape.dims is None or input_shape.ndims != output_shape.ndims:
return [tensor_shape.unknown_shape(), tensor_shape.scalar()]
else:
output_shape = tensor_shape.TensorShape(
[input_dim.value if input_dim.value == output_dim.value else None
for input_dim, output_dim in zip(input_shape.dims,
output_shape.dims)])
return [output_shape, tensor_shape.scalar()]
|
[
"def",
"_MergeShape",
"(",
"op",
")",
":",
"output_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
"if",
"output_shape",
".",
"dims",
"is",
"None",
":",
"return",
"[",
"tensor_shape",
".",
"unknown_shape",
"(",
")",
",",
"tensor_shape",
".",
"scalar",
"(",
")",
"]",
"else",
":",
"for",
"input_",
"in",
"op",
".",
"inputs",
"[",
"1",
":",
"]",
":",
"input_shape",
"=",
"input_",
".",
"get_shape",
"(",
")",
"if",
"input_shape",
".",
"dims",
"is",
"None",
"or",
"input_shape",
".",
"ndims",
"!=",
"output_shape",
".",
"ndims",
":",
"return",
"[",
"tensor_shape",
".",
"unknown_shape",
"(",
")",
",",
"tensor_shape",
".",
"scalar",
"(",
")",
"]",
"else",
":",
"output_shape",
"=",
"tensor_shape",
".",
"TensorShape",
"(",
"[",
"input_dim",
".",
"value",
"if",
"input_dim",
".",
"value",
"==",
"output_dim",
".",
"value",
"else",
"None",
"for",
"input_dim",
",",
"output_dim",
"in",
"zip",
"(",
"input_shape",
".",
"dims",
",",
"output_shape",
".",
"dims",
")",
"]",
")",
"return",
"[",
"output_shape",
",",
"tensor_shape",
".",
"scalar",
"(",
")",
"]"
] |
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L2395-L2427
|
||
hfinkel/llvm-project-cxxjit
|
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
|
llvm/utils/benchmark/mingw.py
|
python
|
main
|
()
|
Invoked when the script is run directly by the python interpreter
|
Invoked when the script is run directly by the python interpreter
|
[
"Invoked",
"when",
"the",
"script",
"is",
"run",
"directly",
"by",
"the",
"python",
"interpreter"
] |
def main():
'''
Invoked when the script is run directly by the python interpreter
'''
parser = argparse.ArgumentParser(
description = 'Downloads a specific version of MinGW',
formatter_class = argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('--location',
help = 'the location to download the compiler to',
default = os.path.join(tempfile.gettempdir(), 'mingw-builds'))
parser.add_argument('--arch', required = True, choices = ['i686', 'x86_64'],
help = 'the target MinGW architecture string')
parser.add_argument('--version', type = str2ver,
help = 'the version of GCC to download')
parser.add_argument('--threading', choices = ['posix', 'win32'],
help = 'the threading type of the compiler')
parser.add_argument('--exceptions', choices = ['sjlj', 'seh', 'dwarf'],
help = 'the method to throw exceptions')
parser.add_argument('--revision', type=int,
help = 'the revision of the MinGW release')
group = parser.add_mutually_exclusive_group()
group.add_argument('-v', '--verbose', action='store_true',
help='increase the script output verbosity')
group.add_argument('-q', '--quiet', action='store_true',
help='only print errors and warning')
args = parser.parse_args()
# Create the logger
logger = logging.getLogger('mingw')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
if args.quiet:
logger.setLevel(logging.WARN)
if args.verbose:
logger.setLevel(logging.DEBUG)
# Get MinGW
root_dir = root(location = args.location, arch = args.arch,
version = args.version, threading = args.threading,
exceptions = args.exceptions, revision = args.revision,
log = logger)
sys.stdout.write('%s\n' % os.path.join(root_dir, 'bin'))
|
[
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Downloads a specific version of MinGW'",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'--location'",
",",
"help",
"=",
"'the location to download the compiler to'",
",",
"default",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'mingw-builds'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'--arch'",
",",
"required",
"=",
"True",
",",
"choices",
"=",
"[",
"'i686'",
",",
"'x86_64'",
"]",
",",
"help",
"=",
"'the target MinGW architecture string'",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"type",
"=",
"str2ver",
",",
"help",
"=",
"'the version of GCC to download'",
")",
"parser",
".",
"add_argument",
"(",
"'--threading'",
",",
"choices",
"=",
"[",
"'posix'",
",",
"'win32'",
"]",
",",
"help",
"=",
"'the threading type of the compiler'",
")",
"parser",
".",
"add_argument",
"(",
"'--exceptions'",
",",
"choices",
"=",
"[",
"'sjlj'",
",",
"'seh'",
",",
"'dwarf'",
"]",
",",
"help",
"=",
"'the method to throw exceptions'",
")",
"parser",
".",
"add_argument",
"(",
"'--revision'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'the revision of the MinGW release'",
")",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"group",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'increase the script output verbosity'",
")",
"group",
".",
"add_argument",
"(",
"'-q'",
",",
"'--quiet'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'only print errors and warning'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# Create the logger",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'mingw'",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(message)s'",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"if",
"args",
".",
"quiet",
":",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"WARN",
")",
"if",
"args",
".",
"verbose",
":",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"# Get MinGW",
"root_dir",
"=",
"root",
"(",
"location",
"=",
"args",
".",
"location",
",",
"arch",
"=",
"args",
".",
"arch",
",",
"version",
"=",
"args",
".",
"version",
",",
"threading",
"=",
"args",
".",
"threading",
",",
"exceptions",
"=",
"args",
".",
"exceptions",
",",
"revision",
"=",
"args",
".",
"revision",
",",
"log",
"=",
"logger",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'%s\\n'",
"%",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'bin'",
")",
")"
] |
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/utils/benchmark/mingw.py#L261-L307
|
||
adobe/chromium
|
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
|
third_party/closure_linter/closure_linter/statetracker.py
|
python
|
StateTracker.InBlock
|
(self)
|
return bool(self._block_depth)
|
Returns true if the current token is within a block.
Returns:
True if the current token is within a block.
|
Returns true if the current token is within a block.
|
[
"Returns",
"true",
"if",
"the",
"current",
"token",
"is",
"within",
"a",
"block",
"."
] |
def InBlock(self):
"""Returns true if the current token is within a block.
Returns:
True if the current token is within a block.
"""
return bool(self._block_depth)
|
[
"def",
"InBlock",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"_block_depth",
")"
] |
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/statetracker.py#L661-L667
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/tornado/tornado-6/tornado/queues.py
|
python
|
Queue.qsize
|
(self)
|
return len(self._queue)
|
Number of items in the queue.
|
Number of items in the queue.
|
[
"Number",
"of",
"items",
"in",
"the",
"queue",
"."
] |
def qsize(self) -> int:
"""Number of items in the queue."""
return len(self._queue)
|
[
"def",
"qsize",
"(",
"self",
")",
"->",
"int",
":",
"return",
"len",
"(",
"self",
".",
"_queue",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/queues.py#L173-L175
|
|
thalium/icebox
|
99d147d5b9269222225443ce171b4fd46d8985d4
|
src/icebox/icebox_py/__init__.py
|
python
|
Vm.break_on_physical_process
|
(self, dtb, where, callback, name="")
|
return BreakpointId(bp, callback)
|
Return breakpoint on physical address filtered by DTB.
|
Return breakpoint on physical address filtered by DTB.
|
[
"Return",
"breakpoint",
"on",
"physical",
"address",
"filtered",
"by",
"DTB",
"."
] |
def break_on_physical_process(self, dtb, where, callback, name=""):
"""Return breakpoint on physical address filtered by DTB."""
where = self._to_physical(where, self.processes.current())
bp = libicebox.break_on_physical_process(name, dtb, where, callback)
return BreakpointId(bp, callback)
|
[
"def",
"break_on_physical_process",
"(",
"self",
",",
"dtb",
",",
"where",
",",
"callback",
",",
"name",
"=",
"\"\"",
")",
":",
"where",
"=",
"self",
".",
"_to_physical",
"(",
"where",
",",
"self",
".",
"processes",
".",
"current",
"(",
")",
")",
"bp",
"=",
"libicebox",
".",
"break_on_physical_process",
"(",
"name",
",",
"dtb",
",",
"where",
",",
"callback",
")",
"return",
"BreakpointId",
"(",
"bp",
",",
"callback",
")"
] |
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/src/icebox/icebox_py/__init__.py#L713-L717
|
|
SFTtech/openage
|
d6a08c53c48dc1e157807471df92197f6ca9e04d
|
openage/convert/processor/conversion/aoc/effect_subprocessor.py
|
python
|
AoCEffectSubprocessor.get_construct_effects
|
(line, location_ref)
|
return effects
|
Creates effects that are used for construction (unit command: 101)
:param line: Unit/Building line that gets the ability.
:type line: ...dataformat.converter_object.ConverterObjectGroup
:param location_ref: Reference to API object the effects are added to.
:type location_ref: str
:returns: The forward references for the effects.
:rtype: list
|
Creates effects that are used for construction (unit command: 101)
|
[
"Creates",
"effects",
"that",
"are",
"used",
"for",
"construction",
"(",
"unit",
"command",
":",
"101",
")"
] |
def get_construct_effects(line, location_ref):
"""
Creates effects that are used for construction (unit command: 101)
:param line: Unit/Building line that gets the ability.
:type line: ...dataformat.converter_object.ConverterObjectGroup
:param location_ref: Reference to API object the effects are added to.
:type location_ref: str
:returns: The forward references for the effects.
:rtype: list
"""
dataset = line.data
name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version)
effects = []
progress_effect_parent = "engine.effect.continuous.time_relative_progress.TimeRelativeProgressChange"
progress_construct_parent = "engine.effect.continuous.time_relative_progress.type.TimeRelativeProgressIncrease"
attr_effect_parent = "engine.effect.continuous.time_relative_attribute.TimeRelativeAttributeChange"
attr_construct_parent = "engine.effect.continuous.time_relative_attribute.type.TimeRelativeAttributeIncrease"
constructable_lines = []
constructable_lines.extend(dataset.building_lines.values())
for constructable_line in constructable_lines:
game_entity_name = name_lookup_dict[constructable_line.get_head_unit_id()][0]
# Construction progress
contruct_progress_name = f"{game_entity_name}ConstructProgressEffect"
contruct_progress_ref = f"{location_ref}.{contruct_progress_name}"
contruct_progress_raw_api_object = RawAPIObject(contruct_progress_ref,
contruct_progress_name,
dataset.nyan_api_objects)
contruct_progress_raw_api_object.add_raw_parent(progress_construct_parent)
contruct_progress_location = ForwardRef(line, location_ref)
contruct_progress_raw_api_object.set_location(contruct_progress_location)
# Type
type_ref = f"util.construct_type.types.{game_entity_name}Construct"
change_type = dataset.pregen_nyan_objects[type_ref].get_nyan_object()
contruct_progress_raw_api_object.add_raw_member("type",
change_type,
progress_effect_parent)
# Total change time
change_time = constructable_line.get_head_unit()["creation_time"].get_value()
contruct_progress_raw_api_object.add_raw_member("total_change_time",
change_time,
progress_effect_parent)
line.add_raw_api_object(contruct_progress_raw_api_object)
contruct_progress_forward_ref = ForwardRef(line, contruct_progress_ref)
effects.append(contruct_progress_forward_ref)
# HP increase during construction
contruct_hp_name = f"{game_entity_name}ConstructHPEffect"
contruct_hp_ref = f"{location_ref}.{contruct_hp_name}"
contruct_hp_raw_api_object = RawAPIObject(contruct_hp_ref,
contruct_hp_name,
dataset.nyan_api_objects)
contruct_hp_raw_api_object.add_raw_parent(attr_construct_parent)
contruct_hp_location = ForwardRef(line, location_ref)
contruct_hp_raw_api_object.set_location(contruct_hp_location)
# Type
type_ref = f"util.attribute_change_type.types.{game_entity_name}Construct"
change_type = dataset.pregen_nyan_objects[type_ref].get_nyan_object()
contruct_hp_raw_api_object.add_raw_member("type",
change_type,
attr_effect_parent)
# Total change time
change_time = constructable_line.get_head_unit()["creation_time"].get_value()
contruct_hp_raw_api_object.add_raw_member("total_change_time",
change_time,
attr_effect_parent)
# Ignore protection
contruct_hp_raw_api_object.add_raw_member("ignore_protection",
[],
attr_effect_parent)
line.add_raw_api_object(contruct_hp_raw_api_object)
contruct_hp_forward_ref = ForwardRef(line, contruct_hp_ref)
effects.append(contruct_hp_forward_ref)
return effects
|
[
"def",
"get_construct_effects",
"(",
"line",
",",
"location_ref",
")",
":",
"dataset",
"=",
"line",
".",
"data",
"name_lookup_dict",
"=",
"internal_name_lookups",
".",
"get_entity_lookups",
"(",
"dataset",
".",
"game_version",
")",
"effects",
"=",
"[",
"]",
"progress_effect_parent",
"=",
"\"engine.effect.continuous.time_relative_progress.TimeRelativeProgressChange\"",
"progress_construct_parent",
"=",
"\"engine.effect.continuous.time_relative_progress.type.TimeRelativeProgressIncrease\"",
"attr_effect_parent",
"=",
"\"engine.effect.continuous.time_relative_attribute.TimeRelativeAttributeChange\"",
"attr_construct_parent",
"=",
"\"engine.effect.continuous.time_relative_attribute.type.TimeRelativeAttributeIncrease\"",
"constructable_lines",
"=",
"[",
"]",
"constructable_lines",
".",
"extend",
"(",
"dataset",
".",
"building_lines",
".",
"values",
"(",
")",
")",
"for",
"constructable_line",
"in",
"constructable_lines",
":",
"game_entity_name",
"=",
"name_lookup_dict",
"[",
"constructable_line",
".",
"get_head_unit_id",
"(",
")",
"]",
"[",
"0",
"]",
"# Construction progress",
"contruct_progress_name",
"=",
"f\"{game_entity_name}ConstructProgressEffect\"",
"contruct_progress_ref",
"=",
"f\"{location_ref}.{contruct_progress_name}\"",
"contruct_progress_raw_api_object",
"=",
"RawAPIObject",
"(",
"contruct_progress_ref",
",",
"contruct_progress_name",
",",
"dataset",
".",
"nyan_api_objects",
")",
"contruct_progress_raw_api_object",
".",
"add_raw_parent",
"(",
"progress_construct_parent",
")",
"contruct_progress_location",
"=",
"ForwardRef",
"(",
"line",
",",
"location_ref",
")",
"contruct_progress_raw_api_object",
".",
"set_location",
"(",
"contruct_progress_location",
")",
"# Type",
"type_ref",
"=",
"f\"util.construct_type.types.{game_entity_name}Construct\"",
"change_type",
"=",
"dataset",
".",
"pregen_nyan_objects",
"[",
"type_ref",
"]",
".",
"get_nyan_object",
"(",
")",
"contruct_progress_raw_api_object",
".",
"add_raw_member",
"(",
"\"type\"",
",",
"change_type",
",",
"progress_effect_parent",
")",
"# Total change time",
"change_time",
"=",
"constructable_line",
".",
"get_head_unit",
"(",
")",
"[",
"\"creation_time\"",
"]",
".",
"get_value",
"(",
")",
"contruct_progress_raw_api_object",
".",
"add_raw_member",
"(",
"\"total_change_time\"",
",",
"change_time",
",",
"progress_effect_parent",
")",
"line",
".",
"add_raw_api_object",
"(",
"contruct_progress_raw_api_object",
")",
"contruct_progress_forward_ref",
"=",
"ForwardRef",
"(",
"line",
",",
"contruct_progress_ref",
")",
"effects",
".",
"append",
"(",
"contruct_progress_forward_ref",
")",
"# HP increase during construction",
"contruct_hp_name",
"=",
"f\"{game_entity_name}ConstructHPEffect\"",
"contruct_hp_ref",
"=",
"f\"{location_ref}.{contruct_hp_name}\"",
"contruct_hp_raw_api_object",
"=",
"RawAPIObject",
"(",
"contruct_hp_ref",
",",
"contruct_hp_name",
",",
"dataset",
".",
"nyan_api_objects",
")",
"contruct_hp_raw_api_object",
".",
"add_raw_parent",
"(",
"attr_construct_parent",
")",
"contruct_hp_location",
"=",
"ForwardRef",
"(",
"line",
",",
"location_ref",
")",
"contruct_hp_raw_api_object",
".",
"set_location",
"(",
"contruct_hp_location",
")",
"# Type",
"type_ref",
"=",
"f\"util.attribute_change_type.types.{game_entity_name}Construct\"",
"change_type",
"=",
"dataset",
".",
"pregen_nyan_objects",
"[",
"type_ref",
"]",
".",
"get_nyan_object",
"(",
")",
"contruct_hp_raw_api_object",
".",
"add_raw_member",
"(",
"\"type\"",
",",
"change_type",
",",
"attr_effect_parent",
")",
"# Total change time",
"change_time",
"=",
"constructable_line",
".",
"get_head_unit",
"(",
")",
"[",
"\"creation_time\"",
"]",
".",
"get_value",
"(",
")",
"contruct_hp_raw_api_object",
".",
"add_raw_member",
"(",
"\"total_change_time\"",
",",
"change_time",
",",
"attr_effect_parent",
")",
"# Ignore protection",
"contruct_hp_raw_api_object",
".",
"add_raw_member",
"(",
"\"ignore_protection\"",
",",
"[",
"]",
",",
"attr_effect_parent",
")",
"line",
".",
"add_raw_api_object",
"(",
"contruct_hp_raw_api_object",
")",
"contruct_hp_forward_ref",
"=",
"ForwardRef",
"(",
"line",
",",
"contruct_hp_ref",
")",
"effects",
".",
"append",
"(",
"contruct_hp_forward_ref",
")",
"return",
"effects"
] |
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/aoc/effect_subprocessor.py#L459-L546
|
|
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/macosxSupport.py
|
python
|
isCarbonAquaTk
|
(root)
|
return _carbonaquatk
|
Returns True if IDLE is using a Carbon Aqua Tk (instead of the
newer Cocoa Aqua Tk).
|
Returns True if IDLE is using a Carbon Aqua Tk (instead of the
newer Cocoa Aqua Tk).
|
[
"Returns",
"True",
"if",
"IDLE",
"is",
"using",
"a",
"Carbon",
"Aqua",
"Tk",
"(",
"instead",
"of",
"the",
"newer",
"Cocoa",
"Aqua",
"Tk",
")",
"."
] |
def isCarbonAquaTk(root):
"""
Returns True if IDLE is using a Carbon Aqua Tk (instead of the
newer Cocoa Aqua Tk).
"""
global _carbonaquatk
if _carbonaquatk is None:
_carbonaquatk = (runningAsOSXApp() and
'aqua' in root.tk.call('tk', 'windowingsystem') and
'AppKit' not in root.tk.call('winfo', 'server', '.'))
return _carbonaquatk
|
[
"def",
"isCarbonAquaTk",
"(",
"root",
")",
":",
"global",
"_carbonaquatk",
"if",
"_carbonaquatk",
"is",
"None",
":",
"_carbonaquatk",
"=",
"(",
"runningAsOSXApp",
"(",
")",
"and",
"'aqua'",
"in",
"root",
".",
"tk",
".",
"call",
"(",
"'tk'",
",",
"'windowingsystem'",
")",
"and",
"'AppKit'",
"not",
"in",
"root",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'server'",
",",
"'.'",
")",
")",
"return",
"_carbonaquatk"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/macosxSupport.py#L25-L35
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/_misc.py
|
python
|
Log_SetRepetitionCounting
|
(*args, **kwargs)
|
return _misc_.Log_SetRepetitionCounting(*args, **kwargs)
|
Log_SetRepetitionCounting(bool bRepetCounting=True)
|
Log_SetRepetitionCounting(bool bRepetCounting=True)
|
[
"Log_SetRepetitionCounting",
"(",
"bool",
"bRepetCounting",
"=",
"True",
")"
] |
def Log_SetRepetitionCounting(*args, **kwargs):
"""Log_SetRepetitionCounting(bool bRepetCounting=True)"""
return _misc_.Log_SetRepetitionCounting(*args, **kwargs)
|
[
"def",
"Log_SetRepetitionCounting",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Log_SetRepetitionCounting",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1688-L1690
|
|
OSGeo/gdal
|
3748fc4ba4fba727492774b2b908a2130c864a83
|
swig/python/osgeo/ogr.py
|
python
|
Feature.GetFieldCount
|
(self, *args)
|
return _ogr.Feature_GetFieldCount(self, *args)
|
r"""
GetFieldCount(Feature self) -> int
int
OGR_F_GetFieldCount(OGRFeatureH hFeat)
Fetch number of fields on this feature This will always be the same as
the field count for the OGRFeatureDefn.
This function is the same as the C++ method
OGRFeature::GetFieldCount().
Parameters:
-----------
hFeat: handle to the feature to get the fields count from.
count of fields.
|
r"""
GetFieldCount(Feature self) -> int
int
OGR_F_GetFieldCount(OGRFeatureH hFeat)
|
[
"r",
"GetFieldCount",
"(",
"Feature",
"self",
")",
"-",
">",
"int",
"int",
"OGR_F_GetFieldCount",
"(",
"OGRFeatureH",
"hFeat",
")"
] |
def GetFieldCount(self, *args):
r"""
GetFieldCount(Feature self) -> int
int
OGR_F_GetFieldCount(OGRFeatureH hFeat)
Fetch number of fields on this feature This will always be the same as
the field count for the OGRFeatureDefn.
This function is the same as the C++ method
OGRFeature::GetFieldCount().
Parameters:
-----------
hFeat: handle to the feature to get the fields count from.
count of fields.
"""
return _ogr.Feature_GetFieldCount(self, *args)
|
[
"def",
"GetFieldCount",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"Feature_GetFieldCount",
"(",
"self",
",",
"*",
"args",
")"
] |
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L3034-L3053
|
|
borglab/gtsam
|
a5bee157efce6a0563704bce6a5d188c29817f39
|
python/gtsam/__init__.py
|
python
|
_init
|
()
|
This function is to add shims for the long-gone Point2 and Point3 types
|
This function is to add shims for the long-gone Point2 and Point3 types
|
[
"This",
"function",
"is",
"to",
"add",
"shims",
"for",
"the",
"long",
"-",
"gone",
"Point2",
"and",
"Point3",
"types"
] |
def _init():
"""This function is to add shims for the long-gone Point2 and Point3 types"""
import numpy as np
global Point2 # export function
def Point2(x=np.nan, y=np.nan):
"""Shim for the deleted Point2 type."""
if isinstance(x, np.ndarray):
assert x.shape == (2, ), "Point2 takes 2-vector"
return x # "copy constructor"
return np.array([x, y], dtype=float)
global Point3 # export function
def Point3(x=np.nan, y=np.nan, z=np.nan):
"""Shim for the deleted Point3 type."""
if isinstance(x, np.ndarray):
assert x.shape == (3, ), "Point3 takes 3-vector"
return x # "copy constructor"
return np.array([x, y, z], dtype=float)
# for interactive debugging
if __name__ == "__main__":
# we want all definitions accessible
globals().update(locals())
|
[
"def",
"_init",
"(",
")",
":",
"import",
"numpy",
"as",
"np",
"global",
"Point2",
"# export function",
"def",
"Point2",
"(",
"x",
"=",
"np",
".",
"nan",
",",
"y",
"=",
"np",
".",
"nan",
")",
":",
"\"\"\"Shim for the deleted Point2 type.\"\"\"",
"if",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"assert",
"x",
".",
"shape",
"==",
"(",
"2",
",",
")",
",",
"\"Point2 takes 2-vector\"",
"return",
"x",
"# \"copy constructor\"",
"return",
"np",
".",
"array",
"(",
"[",
"x",
",",
"y",
"]",
",",
"dtype",
"=",
"float",
")",
"global",
"Point3",
"# export function",
"def",
"Point3",
"(",
"x",
"=",
"np",
".",
"nan",
",",
"y",
"=",
"np",
".",
"nan",
",",
"z",
"=",
"np",
".",
"nan",
")",
":",
"\"\"\"Shim for the deleted Point3 type.\"\"\"",
"if",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"assert",
"x",
".",
"shape",
"==",
"(",
"3",
",",
")",
",",
"\"Point3 takes 3-vector\"",
"return",
"x",
"# \"copy constructor\"",
"return",
"np",
".",
"array",
"(",
"[",
"x",
",",
"y",
",",
"z",
"]",
",",
"dtype",
"=",
"float",
")",
"# for interactive debugging",
"if",
"__name__",
"==",
"\"__main__\"",
":",
"# we want all definitions accessible",
"globals",
"(",
")",
".",
"update",
"(",
"locals",
"(",
")",
")"
] |
https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/python/gtsam/__init__.py#L12-L38
|
||
benoitsteiner/tensorflow-opencl
|
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
|
tensorflow/python/client/timeline.py
|
python
|
_ChromeTraceFormatter.emit_flow_start
|
(self, name, timestamp, pid, tid, flow_id)
|
Adds a flow start event to the trace.
When matched with a flow end event (with the same 'flow_id') this will
cause the trace viewer to draw an arrow between the start and end events.
Args:
name: The event name as a string.
timestamp: The timestamp of this event as a long integer.
pid: Identifier of the process generating this event as an integer.
tid: Identifier of the thread generating this event as an integer.
flow_id: Identifier of the flow as an integer.
|
Adds a flow start event to the trace.
|
[
"Adds",
"a",
"flow",
"start",
"event",
"to",
"the",
"trace",
"."
] |
def emit_flow_start(self, name, timestamp, pid, tid, flow_id):
"""Adds a flow start event to the trace.
When matched with a flow end event (with the same 'flow_id') this will
cause the trace viewer to draw an arrow between the start and end events.
Args:
name: The event name as a string.
timestamp: The timestamp of this event as a long integer.
pid: Identifier of the process generating this event as an integer.
tid: Identifier of the thread generating this event as an integer.
flow_id: Identifier of the flow as an integer.
"""
event = self._create_event('s', 'DataFlow', name, pid, tid, timestamp)
event['id'] = flow_id
self._events.append(event)
|
[
"def",
"emit_flow_start",
"(",
"self",
",",
"name",
",",
"timestamp",
",",
"pid",
",",
"tid",
",",
"flow_id",
")",
":",
"event",
"=",
"self",
".",
"_create_event",
"(",
"'s'",
",",
"'DataFlow'",
",",
"name",
",",
"pid",
",",
"tid",
",",
"timestamp",
")",
"event",
"[",
"'id'",
"]",
"=",
"flow_id",
"self",
".",
"_events",
".",
"append",
"(",
"event",
")"
] |
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/client/timeline.py#L185-L200
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hlc/common.py
|
python
|
rename_label
|
(llvmir)
|
return _re_labelname.sub(repl, llvmir)
|
HLC does not like a label with '.' prefix.
|
HLC does not like a label with '.' prefix.
|
[
"HLC",
"does",
"not",
"like",
"a",
"label",
"with",
".",
"prefix",
"."
] |
def rename_label(llvmir):
"""
HLC does not like a label with '.' prefix.
"""
def repl(mat):
return '_dot_.{0}:'.format(mat.group(1))
return _re_labelname.sub(repl, llvmir)
|
[
"def",
"rename_label",
"(",
"llvmir",
")",
":",
"def",
"repl",
"(",
"mat",
")",
":",
"return",
"'_dot_.{0}:'",
".",
"format",
"(",
"mat",
".",
"group",
"(",
"1",
")",
")",
"return",
"_re_labelname",
".",
"sub",
"(",
"repl",
",",
"llvmir",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hlc/common.py#L55-L62
|
|
krishauser/Klampt
|
972cc83ea5befac3f653c1ba20f80155768ad519
|
Python/klampt/src/robotsim.py
|
python
|
RobotModelDriver.getLimits
|
(self)
|
return _robotsim.RobotModelDriver_getLimits(self)
|
r"""
getLimits(RobotModelDriver self)
Returns value limits [xmin,xmax].
|
r"""
getLimits(RobotModelDriver self)
|
[
"r",
"getLimits",
"(",
"RobotModelDriver",
"self",
")"
] |
def getLimits(self) -> "void":
r"""
getLimits(RobotModelDriver self)
Returns value limits [xmin,xmax].
"""
return _robotsim.RobotModelDriver_getLimits(self)
|
[
"def",
"getLimits",
"(",
"self",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"RobotModelDriver_getLimits",
"(",
"self",
")"
] |
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L4707-L4715
|
|
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/rfc822.py
|
python
|
AddrlistClass.gotonext
|
(self)
|
Parse up to the start of the next address.
|
Parse up to the start of the next address.
|
[
"Parse",
"up",
"to",
"the",
"start",
"of",
"the",
"next",
"address",
"."
] |
def gotonext(self):
"""Parse up to the start of the next address."""
while self.pos < len(self.field):
if self.field[self.pos] in self.LWS + '\n\r':
self.pos = self.pos + 1
elif self.field[self.pos] == '(':
self.commentlist.append(self.getcomment())
else: break
|
[
"def",
"gotonext",
"(",
"self",
")",
":",
"while",
"self",
".",
"pos",
"<",
"len",
"(",
"self",
".",
"field",
")",
":",
"if",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"in",
"self",
".",
"LWS",
"+",
"'\\n\\r'",
":",
"self",
".",
"pos",
"=",
"self",
".",
"pos",
"+",
"1",
"elif",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"==",
"'('",
":",
"self",
".",
"commentlist",
".",
"append",
"(",
"self",
".",
"getcomment",
"(",
")",
")",
"else",
":",
"break"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/rfc822.py#L526-L533
|
||
qgis/QGIS
|
15a77662d4bb712184f6aa60d0bd663010a76a75
|
python/plugins/db_manager/db_plugins/oracle/connector.py
|
python
|
OracleDBConnector.createTableIndex
|
(self, table, name, column)
|
Creates index on one column using default options.
|
Creates index on one column using default options.
|
[
"Creates",
"index",
"on",
"one",
"column",
"using",
"default",
"options",
"."
] |
def createTableIndex(self, table, name, column):
"""Creates index on one column using default options."""
sql = u"CREATE INDEX {0} ON {1} ({2})".format(
self.quoteId(name), self.quoteId(table),
self.quoteId(column))
self._execute_and_commit(sql)
|
[
"def",
"createTableIndex",
"(",
"self",
",",
"table",
",",
"name",
",",
"column",
")",
":",
"sql",
"=",
"u\"CREATE INDEX {0} ON {1} ({2})\"",
".",
"format",
"(",
"self",
".",
"quoteId",
"(",
"name",
")",
",",
"self",
".",
"quoteId",
"(",
"table",
")",
",",
"self",
".",
"quoteId",
"(",
"column",
")",
")",
"self",
".",
"_execute_and_commit",
"(",
"sql",
")"
] |
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/oracle/connector.py#L1590-L1595
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scikit-learn/py3/sklearn/feature_selection/_base.py
|
python
|
SelectorMixin.get_support
|
(self, indices=False)
|
return mask if not indices else np.where(mask)[0]
|
Get a mask, or integer index, of the features selected
Parameters
----------
indices : boolean (default False)
If True, the return value will be an array of integers, rather
than a boolean mask.
Returns
-------
support : array
An index that selects the retained features from a feature vector.
If `indices` is False, this is a boolean array of shape
[# input features], in which an element is True iff its
corresponding feature is selected for retention. If `indices` is
True, this is an integer array of shape [# output features] whose
values are indices into the input feature vector.
|
Get a mask, or integer index, of the features selected
|
[
"Get",
"a",
"mask",
"or",
"integer",
"index",
"of",
"the",
"features",
"selected"
] |
def get_support(self, indices=False):
"""
Get a mask, or integer index, of the features selected
Parameters
----------
indices : boolean (default False)
If True, the return value will be an array of integers, rather
than a boolean mask.
Returns
-------
support : array
An index that selects the retained features from a feature vector.
If `indices` is False, this is a boolean array of shape
[# input features], in which an element is True iff its
corresponding feature is selected for retention. If `indices` is
True, this is an integer array of shape [# output features] whose
values are indices into the input feature vector.
"""
mask = self._get_support_mask()
return mask if not indices else np.where(mask)[0]
|
[
"def",
"get_support",
"(",
"self",
",",
"indices",
"=",
"False",
")",
":",
"mask",
"=",
"self",
".",
"_get_support_mask",
"(",
")",
"return",
"mask",
"if",
"not",
"indices",
"else",
"np",
".",
"where",
"(",
"mask",
")",
"[",
"0",
"]"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_selection/_base.py#L26-L47
|
|
runtimejs/runtime
|
0a6e84c30823d35a4548d6634166784260ae7b74
|
deps/v8/tools/stats-viewer.py
|
python
|
UiCounter.__init__
|
(self, var, format)
|
Creates a new ui counter.
Args:
var: the Tkinter string variable for updating the ui
format: the format string used to format this counter
|
Creates a new ui counter.
|
[
"Creates",
"a",
"new",
"ui",
"counter",
"."
] |
def __init__(self, var, format):
"""Creates a new ui counter.
Args:
var: the Tkinter string variable for updating the ui
format: the format string used to format this counter
"""
self.var = var
self.format = format
self.last_value = None
|
[
"def",
"__init__",
"(",
"self",
",",
"var",
",",
"format",
")",
":",
"self",
".",
"var",
"=",
"var",
"self",
".",
"format",
"=",
"format",
"self",
".",
"last_value",
"=",
"None"
] |
https://github.com/runtimejs/runtime/blob/0a6e84c30823d35a4548d6634166784260ae7b74/deps/v8/tools/stats-viewer.py#L271-L280
|
||
tensorflow/tensorflow
|
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
|
tensorflow/python/ops/distributions/transformed_distribution.py
|
python
|
_ones_like
|
(x)
|
return array_ops.ones_like(x)
|
Convenience function attempts to statically construct `ones_like`.
|
Convenience function attempts to statically construct `ones_like`.
|
[
"Convenience",
"function",
"attempts",
"to",
"statically",
"construct",
"ones_like",
"."
] |
def _ones_like(x):
"""Convenience function attempts to statically construct `ones_like`."""
# Should only be used for small vectors.
if x.get_shape().is_fully_defined():
return array_ops.ones(x.get_shape().as_list(), dtype=x.dtype)
return array_ops.ones_like(x)
|
[
"def",
"_ones_like",
"(",
"x",
")",
":",
"# Should only be used for small vectors.",
"if",
"x",
".",
"get_shape",
"(",
")",
".",
"is_fully_defined",
"(",
")",
":",
"return",
"array_ops",
".",
"ones",
"(",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
"return",
"array_ops",
".",
"ones_like",
"(",
"x",
")"
] |
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/transformed_distribution.py#L94-L99
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_dummy_thread.py
|
python
|
exit
|
()
|
Dummy implementation of _thread.exit().
|
Dummy implementation of _thread.exit().
|
[
"Dummy",
"implementation",
"of",
"_thread",
".",
"exit",
"()",
"."
] |
def exit():
"""Dummy implementation of _thread.exit()."""
raise SystemExit
|
[
"def",
"exit",
"(",
")",
":",
"raise",
"SystemExit"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_dummy_thread.py#L61-L63
|
||
facebookresearch/ELF
|
1f790173095cd910976d9f651b80beb872ec5d12
|
vendor/pybind11/tools/clang/cindex.py
|
python
|
Cursor.hash
|
(self)
|
return self._hash
|
Returns a hash of the cursor as an int.
|
Returns a hash of the cursor as an int.
|
[
"Returns",
"a",
"hash",
"of",
"the",
"cursor",
"as",
"an",
"int",
"."
] |
def hash(self):
"""Returns a hash of the cursor as an int."""
if not hasattr(self, '_hash'):
self._hash = conf.lib.clang_hashCursor(self)
return self._hash
|
[
"def",
"hash",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_hash'",
")",
":",
"self",
".",
"_hash",
"=",
"conf",
".",
"lib",
".",
"clang_hashCursor",
"(",
"self",
")",
"return",
"self",
".",
"_hash"
] |
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L1565-L1570
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
wx/lib/agw/cubecolourdialog.py
|
python
|
HSVWheel.OnLeftUp
|
(self, event)
|
Handles the ``wx.EVT_LEFT_UP`` for :class:`HSVWheel`.
:param `event`: a :class:`MouseEvent` event to be processed.
|
Handles the ``wx.EVT_LEFT_UP`` for :class:`HSVWheel`.
|
[
"Handles",
"the",
"wx",
".",
"EVT_LEFT_UP",
"for",
":",
"class",
":",
"HSVWheel",
"."
] |
def OnLeftUp(self, event):
"""
Handles the ``wx.EVT_LEFT_UP`` for :class:`HSVWheel`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
if self.GetCapture():
self.ReleaseMouse()
self._mouseIn = False
|
[
"def",
"OnLeftUp",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"GetCapture",
"(",
")",
":",
"self",
".",
"ReleaseMouse",
"(",
")",
"self",
".",
"_mouseIn",
"=",
"False"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/cubecolourdialog.py#L2056-L2065
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/ipython/py3/IPython/lib/backgroundjobs.py
|
python
|
BackgroundJobManager.flush
|
(self)
|
Flush all finished jobs (completed and dead) from lists.
Running jobs are never flushed.
It first calls _status_new(), to update info. If any jobs have
completed since the last _status_new() call, the flush operation
aborts.
|
Flush all finished jobs (completed and dead) from lists.
|
[
"Flush",
"all",
"finished",
"jobs",
"(",
"completed",
"and",
"dead",
")",
"from",
"lists",
"."
] |
def flush(self):
"""Flush all finished jobs (completed and dead) from lists.
Running jobs are never flushed.
It first calls _status_new(), to update info. If any jobs have
completed since the last _status_new() call, the flush operation
aborts."""
# Remove the finished jobs from the master dict
alljobs = self.all
for job in self.completed+self.dead:
del(alljobs[job.num])
# Now flush these lists completely
fl_comp = self._group_flush(self.completed, 'Completed')
fl_dead = self._group_flush(self.dead, 'Dead')
if not (fl_comp or fl_dead):
print('No jobs to flush.')
|
[
"def",
"flush",
"(",
"self",
")",
":",
"# Remove the finished jobs from the master dict",
"alljobs",
"=",
"self",
".",
"all",
"for",
"job",
"in",
"self",
".",
"completed",
"+",
"self",
".",
"dead",
":",
"del",
"(",
"alljobs",
"[",
"job",
".",
"num",
"]",
")",
"# Now flush these lists completely",
"fl_comp",
"=",
"self",
".",
"_group_flush",
"(",
"self",
".",
"completed",
",",
"'Completed'",
")",
"fl_dead",
"=",
"self",
".",
"_group_flush",
"(",
"self",
".",
"dead",
",",
"'Dead'",
")",
"if",
"not",
"(",
"fl_comp",
"or",
"fl_dead",
")",
":",
"print",
"(",
"'No jobs to flush.'",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/lib/backgroundjobs.py#L312-L330
|
||
klzgrad/naiveproxy
|
ed2c513637c77b18721fe428d7ed395b4d284c83
|
src/third_party/depot_tools/cpplint.py
|
python
|
IsBlockInNameSpace
|
(nesting_state, is_forward_declaration)
|
return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.stack[-2], _NamespaceInfo))
|
Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace.
|
Checks that the new block is directly in a namespace.
|
[
"Checks",
"that",
"the",
"new",
"block",
"is",
"directly",
"in",
"a",
"namespace",
"."
] |
def IsBlockInNameSpace(nesting_state, is_forward_declaration):
"""Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace.
"""
if is_forward_declaration:
if len(nesting_state.stack) >= 1 and (
isinstance(nesting_state.stack[-1], _NamespaceInfo)):
return True
else:
return False
return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.stack[-2], _NamespaceInfo))
|
[
"def",
"IsBlockInNameSpace",
"(",
"nesting_state",
",",
"is_forward_declaration",
")",
":",
"if",
"is_forward_declaration",
":",
"if",
"len",
"(",
"nesting_state",
".",
"stack",
")",
">=",
"1",
"and",
"(",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_NamespaceInfo",
")",
")",
":",
"return",
"True",
"else",
":",
"return",
"False",
"return",
"(",
"len",
"(",
"nesting_state",
".",
"stack",
")",
">",
"1",
"and",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"check_namespace_indentation",
"and",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"2",
"]",
",",
"_NamespaceInfo",
")",
")"
] |
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L5585-L5603
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scipy/py2/scipy/signal/ltisys.py
|
python
|
StateSpace.__truediv__
|
(self, other)
|
return self.__mul__(1/other)
|
Divide by a scalar
|
Divide by a scalar
|
[
"Divide",
"by",
"a",
"scalar"
] |
def __truediv__(self, other):
"""
Divide by a scalar
"""
# Division by non-StateSpace scalars
if not self._check_binop_other(other) or isinstance(other, StateSpace):
return NotImplemented
if isinstance(other, np.ndarray) and other.ndim > 0:
# It's ambiguous what this means, so disallow it
raise ValueError("Cannot divide StateSpace by non-scalar numpy arrays")
return self.__mul__(1/other)
|
[
"def",
"__truediv__",
"(",
"self",
",",
"other",
")",
":",
"# Division by non-StateSpace scalars",
"if",
"not",
"self",
".",
"_check_binop_other",
"(",
"other",
")",
"or",
"isinstance",
"(",
"other",
",",
"StateSpace",
")",
":",
"return",
"NotImplemented",
"if",
"isinstance",
"(",
"other",
",",
"np",
".",
"ndarray",
")",
"and",
"other",
".",
"ndim",
">",
"0",
":",
"# It's ambiguous what this means, so disallow it",
"raise",
"ValueError",
"(",
"\"Cannot divide StateSpace by non-scalar numpy arrays\"",
")",
"return",
"self",
".",
"__mul__",
"(",
"1",
"/",
"other",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L1496-L1508
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/AWSPythonSDK/1.5.8/concurrent/futures/_base.py
|
python
|
Future.running
|
(self)
|
Return True if the future is currently executing.
|
Return True if the future is currently executing.
|
[
"Return",
"True",
"if",
"the",
"future",
"is",
"currently",
"executing",
"."
] |
def running(self):
"""Return True if the future is currently executing."""
with self._condition:
return self._state == RUNNING
|
[
"def",
"running",
"(",
"self",
")",
":",
"with",
"self",
".",
"_condition",
":",
"return",
"self",
".",
"_state",
"==",
"RUNNING"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/concurrent/futures/_base.py#L362-L365
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_core.py
|
python
|
ThreadEvent.__init__
|
(self, *args, **kwargs)
|
__init__(self, EventType eventType=wxEVT_THREAD, int id=ID_ANY) -> ThreadEvent
|
__init__(self, EventType eventType=wxEVT_THREAD, int id=ID_ANY) -> ThreadEvent
|
[
"__init__",
"(",
"self",
"EventType",
"eventType",
"=",
"wxEVT_THREAD",
"int",
"id",
"=",
"ID_ANY",
")",
"-",
">",
"ThreadEvent"
] |
def __init__(self, *args, **kwargs):
"""__init__(self, EventType eventType=wxEVT_THREAD, int id=ID_ANY) -> ThreadEvent"""
_core_.ThreadEvent_swiginit(self,_core_.new_ThreadEvent(*args, **kwargs))
|
[
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_core_",
".",
"ThreadEvent_swiginit",
"(",
"self",
",",
"_core_",
".",
"new_ThreadEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L5379-L5381
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py
|
python
|
is_HDN
|
(text)
|
return True
|
Return True if text is a host domain name.
|
Return True if text is a host domain name.
|
[
"Return",
"True",
"if",
"text",
"is",
"a",
"host",
"domain",
"name",
"."
] |
def is_HDN(text):
"""Return True if text is a host domain name."""
# XXX
# This may well be wrong. Which RFC is HDN defined in, if any (for
# the purposes of RFC 2965)?
# For the current implementation, what about IPv6? Remember to look
# at other uses of IPV4_RE also, if change this.
if IPV4_RE.search(text):
return False
if text == "":
return False
if text[0] == "." or text[-1] == ".":
return False
return True
|
[
"def",
"is_HDN",
"(",
"text",
")",
":",
"# XXX",
"# This may well be wrong. Which RFC is HDN defined in, if any (for",
"# the purposes of RFC 2965)?",
"# For the current implementation, what about IPv6? Remember to look",
"# at other uses of IPV4_RE also, if change this.",
"if",
"IPV4_RE",
".",
"search",
"(",
"text",
")",
":",
"return",
"False",
"if",
"text",
"==",
"\"\"",
":",
"return",
"False",
"if",
"text",
"[",
"0",
"]",
"==",
"\".\"",
"or",
"text",
"[",
"-",
"1",
"]",
"==",
"\".\"",
":",
"return",
"False",
"return",
"True"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py#L527-L540
|
|
deepmind/open_spiel
|
4ca53bea32bb2875c7385d215424048ae92f78c8
|
open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/ate.py
|
python
|
Solver.mirror_descent_step
|
(self, params, grads, t)
|
return (new_dist, new_y)
|
Entropic mirror descent on exploitability.
Args:
params: tuple of variables to be updated (dist, y)
grads: tuple of variable gradients (grad_dist, grad_y)
t: int, solver iteration (unused)
Returns:
new_params: tuple of update params (new_dist, new_y)
|
Entropic mirror descent on exploitability.
|
[
"Entropic",
"mirror",
"descent",
"on",
"exploitability",
"."
] |
def mirror_descent_step(self, params, grads, t):
"""Entropic mirror descent on exploitability.
Args:
params: tuple of variables to be updated (dist, y)
grads: tuple of variable gradients (grad_dist, grad_y)
t: int, solver iteration (unused)
Returns:
new_params: tuple of update params (new_dist, new_y)
"""
lr_dist, lr_y = self.lrs
new_dist = []
for dist_i, dist_grad_i in zip(params[0], grads[0]):
new_dist_i = np.log(np.clip(dist_i, 0., np.inf)) - lr_dist * dist_grad_i
new_dist_i = special.softmax(new_dist_i)
new_dist.append(new_dist_i)
lr_y = np.clip(1 / float(t + 1), lr_y, np.inf)
new_y = []
for y_i, y_grad_i in zip(params[1], grads[1]):
new_y_i = y_i - lr_y * y_grad_i
new_y_i = np.clip(new_y_i, 0., np.inf)
new_y.append(new_y_i)
return (new_dist, new_y)
|
[
"def",
"mirror_descent_step",
"(",
"self",
",",
"params",
",",
"grads",
",",
"t",
")",
":",
"lr_dist",
",",
"lr_y",
"=",
"self",
".",
"lrs",
"new_dist",
"=",
"[",
"]",
"for",
"dist_i",
",",
"dist_grad_i",
"in",
"zip",
"(",
"params",
"[",
"0",
"]",
",",
"grads",
"[",
"0",
"]",
")",
":",
"new_dist_i",
"=",
"np",
".",
"log",
"(",
"np",
".",
"clip",
"(",
"dist_i",
",",
"0.",
",",
"np",
".",
"inf",
")",
")",
"-",
"lr_dist",
"*",
"dist_grad_i",
"new_dist_i",
"=",
"special",
".",
"softmax",
"(",
"new_dist_i",
")",
"new_dist",
".",
"append",
"(",
"new_dist_i",
")",
"lr_y",
"=",
"np",
".",
"clip",
"(",
"1",
"/",
"float",
"(",
"t",
"+",
"1",
")",
",",
"lr_y",
",",
"np",
".",
"inf",
")",
"new_y",
"=",
"[",
"]",
"for",
"y_i",
",",
"y_grad_i",
"in",
"zip",
"(",
"params",
"[",
"1",
"]",
",",
"grads",
"[",
"1",
"]",
")",
":",
"new_y_i",
"=",
"y_i",
"-",
"lr_y",
"*",
"y_grad_i",
"new_y_i",
"=",
"np",
".",
"clip",
"(",
"new_y_i",
",",
"0.",
",",
"np",
".",
"inf",
")",
"new_y",
".",
"append",
"(",
"new_y_i",
")",
"return",
"(",
"new_dist",
",",
"new_y",
")"
] |
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/ate.py#L131-L153
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/ipython/py3/IPython/utils/ipstruct.py
|
python
|
Struct.__init__
|
(self, *args, **kw)
|
Initialize with a dictionary, another Struct, or data.
Parameters
----------
args : dict, Struct
Initialize with one dict or Struct
kw : dict
Initialize with key, value pairs.
Examples
--------
>>> s = Struct(a=10,b=30)
>>> s.a
10
>>> s.b
30
>>> s2 = Struct(s,c=30)
>>> sorted(s2.keys())
['a', 'b', 'c']
|
Initialize with a dictionary, another Struct, or data.
|
[
"Initialize",
"with",
"a",
"dictionary",
"another",
"Struct",
"or",
"data",
"."
] |
def __init__(self, *args, **kw):
"""Initialize with a dictionary, another Struct, or data.
Parameters
----------
args : dict, Struct
Initialize with one dict or Struct
kw : dict
Initialize with key, value pairs.
Examples
--------
>>> s = Struct(a=10,b=30)
>>> s.a
10
>>> s.b
30
>>> s2 = Struct(s,c=30)
>>> sorted(s2.keys())
['a', 'b', 'c']
"""
object.__setattr__(self, '_allownew', True)
dict.__init__(self, *args, **kw)
|
[
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"object",
".",
"__setattr__",
"(",
"self",
",",
"'_allownew'",
",",
"True",
")",
"dict",
".",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/utils/ipstruct.py#L41-L64
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py
|
python
|
Path.iterdir
|
(self)
|
Iterate over the files in this directory. Does not yield any
result for the special paths '.' and '..'.
|
Iterate over the files in this directory. Does not yield any
result for the special paths '.' and '..'.
|
[
"Iterate",
"over",
"the",
"files",
"in",
"this",
"directory",
".",
"Does",
"not",
"yield",
"any",
"result",
"for",
"the",
"special",
"paths",
".",
"and",
"..",
"."
] |
def iterdir(self):
"""Iterate over the files in this directory. Does not yield any
result for the special paths '.' and '..'.
"""
if self._closed:
self._raise_closed()
for name in self._accessor.listdir(self):
if name in {'.', '..'}:
# Yielding a path object for these makes little sense
continue
yield self._make_child_relpath(name)
if self._closed:
self._raise_closed()
|
[
"def",
"iterdir",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"for",
"name",
"in",
"self",
".",
"_accessor",
".",
"listdir",
"(",
"self",
")",
":",
"if",
"name",
"in",
"{",
"'.'",
",",
"'..'",
"}",
":",
"# Yielding a path object for these makes little sense",
"continue",
"yield",
"self",
".",
"_make_child_relpath",
"(",
"name",
")",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py#L1101-L1113
|
||
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
net/data/ssl/scripts/crlsetutil.py
|
python
|
ASN1Iterator.step_into
|
(self)
|
Begins processing the inner contents of the next ASN.1 element
|
Begins processing the inner contents of the next ASN.1 element
|
[
"Begins",
"processing",
"the",
"inner",
"contents",
"of",
"the",
"next",
"ASN",
".",
"1",
"element"
] |
def step_into(self):
"""Begins processing the inner contents of the next ASN.1 element"""
(self._tag, self._header_length, self._contents, self._rest) = (
_parse_asn1_element(self._contents[self._header_length:]))
|
[
"def",
"step_into",
"(",
"self",
")",
":",
"(",
"self",
".",
"_tag",
",",
"self",
".",
"_header_length",
",",
"self",
".",
"_contents",
",",
"self",
".",
"_rest",
")",
"=",
"(",
"_parse_asn1_element",
"(",
"self",
".",
"_contents",
"[",
"self",
".",
"_header_length",
":",
"]",
")",
")"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/net/data/ssl/scripts/crlsetutil.py#L101-L104
|
||
tensorflow/tensorflow
|
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
|
tensorflow/python/tools/saved_model_cli.py
|
python
|
_print_tensor_info
|
(tensor_info, indent=0)
|
Prints details of the given tensor_info.
Args:
tensor_info: TensorInfo object to be printed.
indent: How far (in increments of 2 spaces) to indent each line output
|
Prints details of the given tensor_info.
|
[
"Prints",
"details",
"of",
"the",
"given",
"tensor_info",
"."
] |
def _print_tensor_info(tensor_info, indent=0):
"""Prints details of the given tensor_info.
Args:
tensor_info: TensorInfo object to be printed.
indent: How far (in increments of 2 spaces) to indent each line output
"""
indent_str = ' ' * indent
def in_print(s):
print(indent_str + s)
in_print(' dtype: ' +
{value: key
for (key, value) in types_pb2.DataType.items()}[tensor_info.dtype])
# Display shape as tuple.
if tensor_info.tensor_shape.unknown_rank:
shape = 'unknown_rank'
else:
dims = [str(dim.size) for dim in tensor_info.tensor_shape.dim]
shape = ', '.join(dims)
shape = '(' + shape + ')'
in_print(' shape: ' + shape)
in_print(' name: ' + tensor_info.name)
|
[
"def",
"_print_tensor_info",
"(",
"tensor_info",
",",
"indent",
"=",
"0",
")",
":",
"indent_str",
"=",
"' '",
"*",
"indent",
"def",
"in_print",
"(",
"s",
")",
":",
"print",
"(",
"indent_str",
"+",
"s",
")",
"in_print",
"(",
"' dtype: '",
"+",
"{",
"value",
":",
"key",
"for",
"(",
"key",
",",
"value",
")",
"in",
"types_pb2",
".",
"DataType",
".",
"items",
"(",
")",
"}",
"[",
"tensor_info",
".",
"dtype",
"]",
")",
"# Display shape as tuple.",
"if",
"tensor_info",
".",
"tensor_shape",
".",
"unknown_rank",
":",
"shape",
"=",
"'unknown_rank'",
"else",
":",
"dims",
"=",
"[",
"str",
"(",
"dim",
".",
"size",
")",
"for",
"dim",
"in",
"tensor_info",
".",
"tensor_shape",
".",
"dim",
"]",
"shape",
"=",
"', '",
".",
"join",
"(",
"dims",
")",
"shape",
"=",
"'('",
"+",
"shape",
"+",
"')'",
"in_print",
"(",
"' shape: '",
"+",
"shape",
")",
"in_print",
"(",
"' name: '",
"+",
"tensor_info",
".",
"name",
")"
] |
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tools/saved_model_cli.py#L268-L290
|
||
Genius-x/genius-x
|
9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0
|
cocos2d/tools/bindings-generator/clang/cindex.py
|
python
|
Type.is_volatile_qualified
|
(self)
|
return conf.lib.clang_isVolatileQualifiedType(self)
|
Determine whether a Type has the "volatile" qualifier set.
This does not look through typedefs that may have added "volatile"
at a different level.
|
Determine whether a Type has the "volatile" qualifier set.
|
[
"Determine",
"whether",
"a",
"Type",
"has",
"the",
"volatile",
"qualifier",
"set",
"."
] |
def is_volatile_qualified(self):
"""Determine whether a Type has the "volatile" qualifier set.
This does not look through typedefs that may have added "volatile"
at a different level.
"""
return conf.lib.clang_isVolatileQualifiedType(self)
|
[
"def",
"is_volatile_qualified",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isVolatileQualifiedType",
"(",
"self",
")"
] |
https://github.com/Genius-x/genius-x/blob/9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0/cocos2d/tools/bindings-generator/clang/cindex.py#L1744-L1750
|
|
RapidsAtHKUST/CommunityDetectionCodes
|
23dbafd2e57ab0f5f0528b1322c4a409f21e5892
|
Prensentation/algorithms/link_partition/visualization/dendrogram/radial_support.py
|
python
|
from_polar
|
(p)
|
return _a(cos(p[0])* p[1], sin(p[0])* p[1])
|
(theta, radius) to (x, y).
|
(theta, radius) to (x, y).
|
[
"(",
"theta",
"radius",
")",
"to",
"(",
"x",
"y",
")",
"."
] |
def from_polar(p):
"""(theta, radius) to (x, y)."""
return _a(cos(p[0])* p[1], sin(p[0])* p[1])
|
[
"def",
"from_polar",
"(",
"p",
")",
":",
"return",
"_a",
"(",
"cos",
"(",
"p",
"[",
"0",
"]",
")",
"*",
"p",
"[",
"1",
"]",
",",
"sin",
"(",
"p",
"[",
"0",
"]",
")",
"*",
"p",
"[",
"1",
"]",
")"
] |
https://github.com/RapidsAtHKUST/CommunityDetectionCodes/blob/23dbafd2e57ab0f5f0528b1322c4a409f21e5892/Prensentation/algorithms/link_partition/visualization/dendrogram/radial_support.py#L9-L11
|
|
hughperkins/tf-coriander
|
970d3df6c11400ad68405f22b0c42a52374e94ca
|
tensorflow/python/ops/gradients.py
|
python
|
_GetGrads
|
(grads, op)
|
Gets all gradients for op.
|
Gets all gradients for op.
|
[
"Gets",
"all",
"gradients",
"for",
"op",
"."
] |
def _GetGrads(grads, op):
"""Gets all gradients for op."""
if op in grads:
return grads[op]
else:
return [[] for _ in xrange(len(op.outputs))]
|
[
"def",
"_GetGrads",
"(",
"grads",
",",
"op",
")",
":",
"if",
"op",
"in",
"grads",
":",
"return",
"grads",
"[",
"op",
"]",
"else",
":",
"return",
"[",
"[",
"]",
"for",
"_",
"in",
"xrange",
"(",
"len",
"(",
"op",
".",
"outputs",
")",
")",
"]"
] |
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/gradients.py#L583-L588
|
||
google/certificate-transparency
|
2588562fd306a447958471b6f06c1069619c1641
|
python/ct/client/monitor.py
|
python
|
Monitor._set_pending_sth
|
(self, new_sth)
|
return True
|
Set pending_sth from new_sth, or just verified_sth if not bigger.
|
Set pending_sth from new_sth, or just verified_sth if not bigger.
|
[
"Set",
"pending_sth",
"from",
"new_sth",
"or",
"just",
"verified_sth",
"if",
"not",
"bigger",
"."
] |
def _set_pending_sth(self, new_sth):
"""Set pending_sth from new_sth, or just verified_sth if not bigger."""
logging.info("STH verified, updating state.")
if new_sth.tree_size < self.__state.verified_sth.tree_size:
raise ValueError("pending size must be >= verified size")
if new_sth.timestamp <= self.__state.verified_sth.timestamp:
raise ValueError("pending time must be > verified time")
new_state = client_pb2.MonitorState()
new_state.CopyFrom(self.__state)
if new_sth.tree_size > self.__state.verified_sth.tree_size:
new_state.pending_sth.CopyFrom(new_sth)
else:
new_state.verified_sth.CopyFrom(new_sth)
self.__update_state(new_state)
return True
|
[
"def",
"_set_pending_sth",
"(",
"self",
",",
"new_sth",
")",
":",
"logging",
".",
"info",
"(",
"\"STH verified, updating state.\"",
")",
"if",
"new_sth",
".",
"tree_size",
"<",
"self",
".",
"__state",
".",
"verified_sth",
".",
"tree_size",
":",
"raise",
"ValueError",
"(",
"\"pending size must be >= verified size\"",
")",
"if",
"new_sth",
".",
"timestamp",
"<=",
"self",
".",
"__state",
".",
"verified_sth",
".",
"timestamp",
":",
"raise",
"ValueError",
"(",
"\"pending time must be > verified time\"",
")",
"new_state",
"=",
"client_pb2",
".",
"MonitorState",
"(",
")",
"new_state",
".",
"CopyFrom",
"(",
"self",
".",
"__state",
")",
"if",
"new_sth",
".",
"tree_size",
">",
"self",
".",
"__state",
".",
"verified_sth",
".",
"tree_size",
":",
"new_state",
".",
"pending_sth",
".",
"CopyFrom",
"(",
"new_sth",
")",
"else",
":",
"new_state",
".",
"verified_sth",
".",
"CopyFrom",
"(",
"new_sth",
")",
"self",
".",
"__update_state",
"(",
"new_state",
")",
"return",
"True"
] |
https://github.com/google/certificate-transparency/blob/2588562fd306a447958471b6f06c1069619c1641/python/ct/client/monitor.py#L87-L101
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py
|
python
|
RefreshTokenGrant.create_token_response
|
(self, request, token_handler)
|
return headers, json.dumps(token), 200
|
Create a new access token from a refresh_token.
If valid and authorized, the authorization server issues an access
token as described in `Section 5.1`_. If the request failed
verification or is invalid, the authorization server returns an error
response as described in `Section 5.2`_.
The authorization server MAY issue a new refresh token, in which case
the client MUST discard the old refresh token and replace it with the
new refresh token. The authorization server MAY revoke the old
refresh token after issuing a new refresh token to the client. If a
new refresh token is issued, the refresh token scope MUST be
identical to that of the refresh token included by the client in the
request.
.. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1
.. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2
|
Create a new access token from a refresh_token.
|
[
"Create",
"a",
"new",
"access",
"token",
"from",
"a",
"refresh_token",
"."
] |
def create_token_response(self, request, token_handler):
"""Create a new access token from a refresh_token.
If valid and authorized, the authorization server issues an access
token as described in `Section 5.1`_. If the request failed
verification or is invalid, the authorization server returns an error
response as described in `Section 5.2`_.
The authorization server MAY issue a new refresh token, in which case
the client MUST discard the old refresh token and replace it with the
new refresh token. The authorization server MAY revoke the old
refresh token after issuing a new refresh token to the client. If a
new refresh token is issued, the refresh token scope MUST be
identical to that of the refresh token included by the client in the
request.
.. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1
.. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2
"""
headers = {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'Pragma': 'no-cache',
}
try:
log.debug('Validating refresh token request, %r.', request)
self.validate_token_request(request)
except errors.OAuth2Error as e:
return headers, e.json, e.status_code
token = token_handler.create_token(request,
refresh_token=self.issue_new_refresh_tokens, save_token=False)
for modifier in self._token_modifiers:
token = modifier(token)
self.request_validator.save_token(token, request)
log.debug('Issuing new token to client id %r (%r), %r.',
request.client_id, request.client, token)
return headers, json.dumps(token), 200
|
[
"def",
"create_token_response",
"(",
"self",
",",
"request",
",",
"token_handler",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'Cache-Control'",
":",
"'no-store'",
",",
"'Pragma'",
":",
"'no-cache'",
",",
"}",
"try",
":",
"log",
".",
"debug",
"(",
"'Validating refresh token request, %r.'",
",",
"request",
")",
"self",
".",
"validate_token_request",
"(",
"request",
")",
"except",
"errors",
".",
"OAuth2Error",
"as",
"e",
":",
"return",
"headers",
",",
"e",
".",
"json",
",",
"e",
".",
"status_code",
"token",
"=",
"token_handler",
".",
"create_token",
"(",
"request",
",",
"refresh_token",
"=",
"self",
".",
"issue_new_refresh_tokens",
",",
"save_token",
"=",
"False",
")",
"for",
"modifier",
"in",
"self",
".",
"_token_modifiers",
":",
"token",
"=",
"modifier",
"(",
"token",
")",
"self",
".",
"request_validator",
".",
"save_token",
"(",
"token",
",",
"request",
")",
"log",
".",
"debug",
"(",
"'Issuing new token to client id %r (%r), %r.'",
",",
"request",
".",
"client_id",
",",
"request",
".",
"client",
",",
"token",
")",
"return",
"headers",
",",
"json",
".",
"dumps",
"(",
"token",
")",
",",
"200"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py#L33-L72
|
|
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
tools/roll_webrtc.py
|
python
|
_PosixPath
|
(path)
|
return path.replace(os.sep, '/')
|
Convert a possibly-Windows path to a posix-style path.
|
Convert a possibly-Windows path to a posix-style path.
|
[
"Convert",
"a",
"possibly",
"-",
"Windows",
"path",
"to",
"a",
"posix",
"-",
"style",
"path",
"."
] |
def _PosixPath(path):
"""Convert a possibly-Windows path to a posix-style path."""
(_, path) = os.path.splitdrive(path)
return path.replace(os.sep, '/')
|
[
"def",
"_PosixPath",
"(",
"path",
")",
":",
"(",
"_",
",",
"path",
")",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"path",
")",
"return",
"path",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"'/'",
")"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/roll_webrtc.py#L65-L68
|
|
HyeonwooNoh/caffe
|
d9e8494a2832d67b25dee37194c7bcb9d52d0e42
|
tools/extra/parse_log.py
|
python
|
save_csv_files
|
(logfile_path, output_dir, train_dict_list, train_dict_names,
test_dict_list, test_dict_names, verbose=False)
|
Save CSV files to output_dir
If the input log file is, e.g., caffe.INFO, the names will be
caffe.INFO.train and caffe.INFO.test
|
Save CSV files to output_dir
|
[
"Save",
"CSV",
"files",
"to",
"output_dir"
] |
def save_csv_files(logfile_path, output_dir, train_dict_list, train_dict_names,
test_dict_list, test_dict_names, verbose=False):
"""Save CSV files to output_dir
If the input log file is, e.g., caffe.INFO, the names will be
caffe.INFO.train and caffe.INFO.test
"""
log_basename = os.path.basename(logfile_path)
train_filename = os.path.join(output_dir, log_basename + '.train')
write_csv(train_filename, train_dict_list, train_dict_names, verbose)
test_filename = os.path.join(output_dir, log_basename + '.test')
write_csv(test_filename, test_dict_list, test_dict_names, verbose)
|
[
"def",
"save_csv_files",
"(",
"logfile_path",
",",
"output_dir",
",",
"train_dict_list",
",",
"train_dict_names",
",",
"test_dict_list",
",",
"test_dict_names",
",",
"verbose",
"=",
"False",
")",
":",
"log_basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"logfile_path",
")",
"train_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"log_basename",
"+",
"'.train'",
")",
"write_csv",
"(",
"train_filename",
",",
"train_dict_list",
",",
"train_dict_names",
",",
"verbose",
")",
"test_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"log_basename",
"+",
"'.test'",
")",
"write_csv",
"(",
"test_filename",
",",
"test_dict_list",
",",
"test_dict_names",
",",
"verbose",
")"
] |
https://github.com/HyeonwooNoh/caffe/blob/d9e8494a2832d67b25dee37194c7bcb9d52d0e42/tools/extra/parse_log.py#L101-L114
|
||
oracle/graaljs
|
36a56e8e993d45fc40939a3a4d9c0c24990720f1
|
graal-nodejs/deps/v8/third_party/jinja2/utils.py
|
python
|
htmlsafe_json_dumps
|
(obj, dumper=None, **kwargs)
|
return Markup(rv)
|
Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
|
Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
|
[
"Works",
"exactly",
"like",
":",
"func",
":",
"dumps",
"but",
"is",
"safe",
"for",
"use",
"in",
"<script",
">",
"tags",
".",
"It",
"accepts",
"the",
"same",
"arguments",
"and",
"returns",
"a",
"JSON",
"string",
".",
"Note",
"that",
"this",
"is",
"available",
"in",
"templates",
"through",
"the",
"|tojson",
"filter",
"which",
"will",
"also",
"mark",
"the",
"result",
"as",
"safe",
".",
"Due",
"to",
"how",
"this",
"function",
"escapes",
"certain",
"characters",
"this",
"is",
"safe",
"even",
"if",
"used",
"outside",
"of",
"<script",
">",
"tags",
"."
] |
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
"""
if dumper is None:
dumper = json.dumps
rv = dumper(obj, **kwargs) \
.replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.replace(u"'", u'\\u0027')
return Markup(rv)
|
[
"def",
"htmlsafe_json_dumps",
"(",
"obj",
",",
"dumper",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dumper",
"is",
"None",
":",
"dumper",
"=",
"json",
".",
"dumps",
"rv",
"=",
"dumper",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
".",
"replace",
"(",
"u'<'",
",",
"u'\\\\u003c'",
")",
".",
"replace",
"(",
"u'>'",
",",
"u'\\\\u003e'",
")",
".",
"replace",
"(",
"u'&'",
",",
"u'\\\\u0026'",
")",
".",
"replace",
"(",
"u\"'\"",
",",
"u'\\\\u0027'",
")",
"return",
"Markup",
"(",
"rv",
")"
] |
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/utils.py#L545-L570
|
|
krishauser/Klampt
|
972cc83ea5befac3f653c1ba20f80155768ad519
|
Python/python2_version/klampt/src/robotsim.py
|
python
|
GeometricPrimitive.setSegment
|
(self, a, b)
|
return _robotsim.GeometricPrimitive_setSegment(self, a, b)
|
setSegment(GeometricPrimitive self, double const [3] a, double const [3] b)
|
setSegment(GeometricPrimitive self, double const [3] a, double const [3] b)
|
[
"setSegment",
"(",
"GeometricPrimitive",
"self",
"double",
"const",
"[",
"3",
"]",
"a",
"double",
"const",
"[",
"3",
"]",
"b",
")"
] |
def setSegment(self, a, b):
"""
setSegment(GeometricPrimitive self, double const [3] a, double const [3] b)
"""
return _robotsim.GeometricPrimitive_setSegment(self, a, b)
|
[
"def",
"setSegment",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"return",
"_robotsim",
".",
"GeometricPrimitive_setSegment",
"(",
"self",
",",
"a",
",",
"b",
")"
] |
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L1374-L1381
|
|
yrnkrn/zapcc
|
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
|
tools/clang/tools/scan-build-py/libear/__init__.py
|
python
|
execute
|
(cmd, *args, **kwargs)
|
return subprocess.check_call(cmd, *args, **kwargs)
|
Make subprocess execution silent.
|
Make subprocess execution silent.
|
[
"Make",
"subprocess",
"execution",
"silent",
"."
] |
def execute(cmd, *args, **kwargs):
""" Make subprocess execution silent. """
import subprocess
kwargs.update({'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT})
return subprocess.check_call(cmd, *args, **kwargs)
|
[
"def",
"execute",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"subprocess",
"kwargs",
".",
"update",
"(",
"{",
"'stdout'",
":",
"subprocess",
".",
"PIPE",
",",
"'stderr'",
":",
"subprocess",
".",
"STDOUT",
"}",
")",
"return",
"subprocess",
".",
"check_call",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/tools/scan-build-py/libear/__init__.py#L62-L67
|
|
ChromiumWebApps/chromium
|
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
|
build/android/lighttpd_server.py
|
python
|
LighttpdServer.ShutdownHttpServer
|
(self)
|
Shuts down our lighttpd processes.
|
Shuts down our lighttpd processes.
|
[
"Shuts",
"down",
"our",
"lighttpd",
"processes",
"."
] |
def ShutdownHttpServer(self):
"""Shuts down our lighttpd processes."""
if self.process:
self.process.terminate()
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
[
"def",
"ShutdownHttpServer",
"(",
"self",
")",
":",
"if",
"self",
".",
"process",
":",
"self",
".",
"process",
".",
"terminate",
"(",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"temp_dir",
",",
"ignore_errors",
"=",
"True",
")"
] |
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/lighttpd_server.py#L112-L116
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
wx/py/filling.py
|
python
|
FillingTree.objHasChildren
|
(self, obj)
|
Return true if object has children.
|
Return true if object has children.
|
[
"Return",
"true",
"if",
"object",
"has",
"children",
"."
] |
def objHasChildren(self, obj):
"""Return true if object has children."""
if self.objGetChildren(obj):
return True
else:
return False
|
[
"def",
"objHasChildren",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"objGetChildren",
"(",
"obj",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/filling.py#L107-L112
|
||
mapnik/mapnik
|
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
|
scons/scons-local-4.1.0/SCons/Taskmaster.py
|
python
|
Taskmaster._validate_pending_children
|
(self)
|
Validate the content of the pending_children set. Assert if an
internal error is found.
This function is used strictly for debugging the taskmaster by
checking that no invariants are violated. It is not used in
normal operation.
The pending_children set is used to detect cycles in the
dependency graph. We call a "pending child" a child that is
found in the "pending" state when checking the dependencies of
its parent node.
A pending child can occur when the Taskmaster completes a loop
through a cycle. For example, let's imagine a graph made of
three nodes (A, B and C) making a cycle. The evaluation starts
at node A. The Taskmaster first considers whether node A's
child B is up-to-date. Then, recursively, node B needs to
check whether node C is up-to-date. This leaves us with a
dependency graph looking like::
Next candidate \
\
Node A (Pending) --> Node B(Pending) --> Node C (NoState)
^ |
| |
+-------------------------------------+
Now, when the Taskmaster examines the Node C's child Node A,
it finds that Node A is in the "pending" state. Therefore,
Node A is a pending child of node C.
Pending children indicate that the Taskmaster has potentially
loop back through a cycle. We say potentially because it could
also occur when a DAG is evaluated in parallel. For example,
consider the following graph::
Node A (Pending) --> Node B(Pending) --> Node C (Pending) --> ...
| ^
| |
+----------> Node D (NoState) --------+
/
Next candidate /
The Taskmaster first evaluates the nodes A, B, and C and
starts building some children of node C. Assuming, that the
maximum parallel level has not been reached, the Taskmaster
will examine Node D. It will find that Node C is a pending
child of Node D.
In summary, evaluating a graph with a cycle will always
involve a pending child at one point. A pending child might
indicate either a cycle or a diamond-shaped DAG. Only a
fraction of the nodes ends-up being a "pending child" of
another node. This keeps the pending_children set small in
practice.
We can differentiate between the two cases if we wait until
the end of the build. At this point, all the pending children
nodes due to a diamond-shaped DAG will have been properly
built (or will have failed to build). But, the pending
children involved in a cycle will still be in the pending
state.
The taskmaster removes nodes from the pending_children set as
soon as a pending_children node moves out of the pending
state. This also helps to keep the pending_children set small.
|
Validate the content of the pending_children set. Assert if an
internal error is found.
|
[
"Validate",
"the",
"content",
"of",
"the",
"pending_children",
"set",
".",
"Assert",
"if",
"an",
"internal",
"error",
"is",
"found",
"."
] |
def _validate_pending_children(self):
"""
Validate the content of the pending_children set. Assert if an
internal error is found.
This function is used strictly for debugging the taskmaster by
checking that no invariants are violated. It is not used in
normal operation.
The pending_children set is used to detect cycles in the
dependency graph. We call a "pending child" a child that is
found in the "pending" state when checking the dependencies of
its parent node.
A pending child can occur when the Taskmaster completes a loop
through a cycle. For example, let's imagine a graph made of
three nodes (A, B and C) making a cycle. The evaluation starts
at node A. The Taskmaster first considers whether node A's
child B is up-to-date. Then, recursively, node B needs to
check whether node C is up-to-date. This leaves us with a
dependency graph looking like::
Next candidate \
\
Node A (Pending) --> Node B(Pending) --> Node C (NoState)
^ |
| |
+-------------------------------------+
Now, when the Taskmaster examines the Node C's child Node A,
it finds that Node A is in the "pending" state. Therefore,
Node A is a pending child of node C.
Pending children indicate that the Taskmaster has potentially
loop back through a cycle. We say potentially because it could
also occur when a DAG is evaluated in parallel. For example,
consider the following graph::
Node A (Pending) --> Node B(Pending) --> Node C (Pending) --> ...
| ^
| |
+----------> Node D (NoState) --------+
/
Next candidate /
The Taskmaster first evaluates the nodes A, B, and C and
starts building some children of node C. Assuming, that the
maximum parallel level has not been reached, the Taskmaster
will examine Node D. It will find that Node C is a pending
child of Node D.
In summary, evaluating a graph with a cycle will always
involve a pending child at one point. A pending child might
indicate either a cycle or a diamond-shaped DAG. Only a
fraction of the nodes ends-up being a "pending child" of
another node. This keeps the pending_children set small in
practice.
We can differentiate between the two cases if we wait until
the end of the build. At this point, all the pending children
nodes due to a diamond-shaped DAG will have been properly
built (or will have failed to build). But, the pending
children involved in a cycle will still be in the pending
state.
The taskmaster removes nodes from the pending_children set as
soon as a pending_children node moves out of the pending
state. This also helps to keep the pending_children set small.
"""
for n in self.pending_children:
assert n.state in (NODE_PENDING, NODE_EXECUTING), \
(str(n), StateString[n.state])
assert len(n.waiting_parents) != 0, (str(n), len(n.waiting_parents))
for p in n.waiting_parents:
assert p.ref_count > 0, (str(n), str(p), p.ref_count)
|
[
"def",
"_validate_pending_children",
"(",
"self",
")",
":",
"for",
"n",
"in",
"self",
".",
"pending_children",
":",
"assert",
"n",
".",
"state",
"in",
"(",
"NODE_PENDING",
",",
"NODE_EXECUTING",
")",
",",
"(",
"str",
"(",
"n",
")",
",",
"StateString",
"[",
"n",
".",
"state",
"]",
")",
"assert",
"len",
"(",
"n",
".",
"waiting_parents",
")",
"!=",
"0",
",",
"(",
"str",
"(",
"n",
")",
",",
"len",
"(",
"n",
".",
"waiting_parents",
")",
")",
"for",
"p",
"in",
"n",
".",
"waiting_parents",
":",
"assert",
"p",
".",
"ref_count",
">",
"0",
",",
"(",
"str",
"(",
"n",
")",
",",
"str",
"(",
"p",
")",
",",
"p",
".",
"ref_count",
")"
] |
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Taskmaster.py#L661-L736
|
||
idaholab/moose
|
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
|
python/chigger/utils/__init__.py
|
python
|
animate
|
(pattern, output, delay=20, restart_delay=500, loop=True)
|
Runs ImageMagic convert to create an animate gif from a series of images.
|
Runs ImageMagic convert to create an animate gif from a series of images.
|
[
"Runs",
"ImageMagic",
"convert",
"to",
"create",
"an",
"animate",
"gif",
"from",
"a",
"series",
"of",
"images",
"."
] |
def animate(pattern, output, delay=20, restart_delay=500, loop=True):
"""
Runs ImageMagic convert to create an animate gif from a series of images.
"""
filenames = sorted(glob.glob(pattern))
delay = [delay]*len(filenames)
delay[-1] = restart_delay
cmd = ['convert']
for d, f in zip(delay, filenames):
cmd += ['-delay', str(d), f]
if loop:
cmd += ['-loop', '0']
cmd += [output]
subprocess.call(cmd)
|
[
"def",
"animate",
"(",
"pattern",
",",
"output",
",",
"delay",
"=",
"20",
",",
"restart_delay",
"=",
"500",
",",
"loop",
"=",
"True",
")",
":",
"filenames",
"=",
"sorted",
"(",
"glob",
".",
"glob",
"(",
"pattern",
")",
")",
"delay",
"=",
"[",
"delay",
"]",
"*",
"len",
"(",
"filenames",
")",
"delay",
"[",
"-",
"1",
"]",
"=",
"restart_delay",
"cmd",
"=",
"[",
"'convert'",
"]",
"for",
"d",
",",
"f",
"in",
"zip",
"(",
"delay",
",",
"filenames",
")",
":",
"cmd",
"+=",
"[",
"'-delay'",
",",
"str",
"(",
"d",
")",
",",
"f",
"]",
"if",
"loop",
":",
"cmd",
"+=",
"[",
"'-loop'",
",",
"'0'",
"]",
"cmd",
"+=",
"[",
"output",
"]",
"subprocess",
".",
"call",
"(",
"cmd",
")"
] |
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/utils/__init__.py#L136-L149
|
||
FreeCAD/FreeCAD
|
ba42231b9c6889b89e064d6d563448ed81e376ec
|
src/Mod/Arch/ArchBuildingPart.py
|
python
|
BuildingPart.getShapes
|
(self,obj)
|
return shapes,materialstable
|
recursively get the shapes of objects inside this BuildingPart
|
recursively get the shapes of objects inside this BuildingPart
|
[
"recursively",
"get",
"the",
"shapes",
"of",
"objects",
"inside",
"this",
"BuildingPart"
] |
def getShapes(self,obj):
"recursively get the shapes of objects inside this BuildingPart"
shapes = []
solidindex = 0
materialstable = {}
for child in Draft.get_group_contents(obj):
if not Draft.get_type(child) in ["Space"]:
if hasattr(child,'Shape') and child.Shape:
shapes.append(child.Shape)
for solid in child.Shape.Solids:
matname = "Undefined"
if hasattr(child,"Material") and child.Material:
matname = child.Material.Name
if matname in materialstable:
materialstable[matname] = materialstable[matname]+","+str(solidindex)
else:
materialstable[matname] = str(solidindex)
solidindex += 1
return shapes,materialstable
|
[
"def",
"getShapes",
"(",
"self",
",",
"obj",
")",
":",
"shapes",
"=",
"[",
"]",
"solidindex",
"=",
"0",
"materialstable",
"=",
"{",
"}",
"for",
"child",
"in",
"Draft",
".",
"get_group_contents",
"(",
"obj",
")",
":",
"if",
"not",
"Draft",
".",
"get_type",
"(",
"child",
")",
"in",
"[",
"\"Space\"",
"]",
":",
"if",
"hasattr",
"(",
"child",
",",
"'Shape'",
")",
"and",
"child",
".",
"Shape",
":",
"shapes",
".",
"append",
"(",
"child",
".",
"Shape",
")",
"for",
"solid",
"in",
"child",
".",
"Shape",
".",
"Solids",
":",
"matname",
"=",
"\"Undefined\"",
"if",
"hasattr",
"(",
"child",
",",
"\"Material\"",
")",
"and",
"child",
".",
"Material",
":",
"matname",
"=",
"child",
".",
"Material",
".",
"Name",
"if",
"matname",
"in",
"materialstable",
":",
"materialstable",
"[",
"matname",
"]",
"=",
"materialstable",
"[",
"matname",
"]",
"+",
"\",\"",
"+",
"str",
"(",
"solidindex",
")",
"else",
":",
"materialstable",
"[",
"matname",
"]",
"=",
"str",
"(",
"solidindex",
")",
"solidindex",
"+=",
"1",
"return",
"shapes",
",",
"materialstable"
] |
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchBuildingPart.py#L453-L473
|
|
miyosuda/TensorFlowAndroidDemo
|
35903e0221aa5f109ea2dbef27f20b52e317f42d
|
jni-build/jni/include/tensorflow/python/ops/ctc_ops.py
|
python
|
_CTCLossShape
|
(op)
|
return [tensor_shape.vector(batch_size), inputs_shape]
|
Shape function for the CTCLoss op.
|
Shape function for the CTCLoss op.
|
[
"Shape",
"function",
"for",
"the",
"CTCLoss",
"op",
"."
] |
def _CTCLossShape(op):
"""Shape function for the CTCLoss op."""
# inputs, label_indices, label_values, sequence_length
inputs_shape = op.inputs[0].get_shape().with_rank(3)
sequence_length_shape = op.inputs[3].get_shape().with_rank(1)
# merge batch_size
sequence_length_shape[0].merge_with(inputs_shape[1])
inputs_shape[1].merge_with(sequence_length_shape[0])
batch_size = inputs_shape[1]
labels_index_shape = op.inputs[1].get_shape().with_rank(2)
labels_value_shape = op.inputs[2].get_shape().with_rank(1)
labels_value_shape[0].merge_with(labels_index_shape[0])
# loss, gradient
return [tensor_shape.vector(batch_size), inputs_shape]
|
[
"def",
"_CTCLossShape",
"(",
"op",
")",
":",
"# inputs, label_indices, label_values, sequence_length",
"inputs_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"3",
")",
"sequence_length_shape",
"=",
"op",
".",
"inputs",
"[",
"3",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"1",
")",
"# merge batch_size",
"sequence_length_shape",
"[",
"0",
"]",
".",
"merge_with",
"(",
"inputs_shape",
"[",
"1",
"]",
")",
"inputs_shape",
"[",
"1",
"]",
".",
"merge_with",
"(",
"sequence_length_shape",
"[",
"0",
"]",
")",
"batch_size",
"=",
"inputs_shape",
"[",
"1",
"]",
"labels_index_shape",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"2",
")",
"labels_value_shape",
"=",
"op",
".",
"inputs",
"[",
"2",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"1",
")",
"labels_value_shape",
"[",
"0",
"]",
".",
"merge_with",
"(",
"labels_index_shape",
"[",
"0",
"]",
")",
"# loss, gradient",
"return",
"[",
"tensor_shape",
".",
"vector",
"(",
"batch_size",
")",
",",
"inputs_shape",
"]"
] |
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/ctc_ops.py#L139-L152
|
|
smilehao/xlua-framework
|
a03801538be2b0e92d39332d445b22caca1ef61f
|
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/encoder.py
|
python
|
GroupEncoder
|
(field_number, is_repeated, is_packed)
|
Returns an encoder for a group field.
|
Returns an encoder for a group field.
|
[
"Returns",
"an",
"encoder",
"for",
"a",
"group",
"field",
"."
] |
def GroupEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a group field."""
start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)
end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
write(start_tag)
element._InternalSerialize(write)
write(end_tag)
return EncodeRepeatedField
else:
def EncodeField(write, value):
write(start_tag)
value._InternalSerialize(write)
return write(end_tag)
return EncodeField
|
[
"def",
"GroupEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"start_tag",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_START_GROUP",
")",
"end_tag",
"=",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_END_GROUP",
")",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"def",
"EncodeRepeatedField",
"(",
"write",
",",
"value",
")",
":",
"for",
"element",
"in",
"value",
":",
"write",
"(",
"start_tag",
")",
"element",
".",
"_InternalSerialize",
"(",
"write",
")",
"write",
"(",
"end_tag",
")",
"return",
"EncodeRepeatedField",
"else",
":",
"def",
"EncodeField",
"(",
"write",
",",
"value",
")",
":",
"write",
"(",
"start_tag",
")",
"value",
".",
"_InternalSerialize",
"(",
"write",
")",
"return",
"write",
"(",
"end_tag",
")",
"return",
"EncodeField"
] |
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/encoder.py#L698-L716
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/build/waf-1.7.13/waflib/Tools/glib2.py
|
python
|
add_enums_from_template
|
(self, source='', target='', template='', comments='')
|
Add a file to the list of enum files to process. Store them in the attribute *enums_list*.
:param source: enum file to process
:type source: string
:param target: target file
:type target: string
:param template: template file
:type template: string
:param comments: comments
:type comments: string
|
Add a file to the list of enum files to process. Store them in the attribute *enums_list*.
|
[
"Add",
"a",
"file",
"to",
"the",
"list",
"of",
"enum",
"files",
"to",
"process",
".",
"Store",
"them",
"in",
"the",
"attribute",
"*",
"enums_list",
"*",
"."
] |
def add_enums_from_template(self, source='', target='', template='', comments=''):
"""
Add a file to the list of enum files to process. Store them in the attribute *enums_list*.
:param source: enum file to process
:type source: string
:param target: target file
:type target: string
:param template: template file
:type template: string
:param comments: comments
:type comments: string
"""
if not hasattr(self, 'enums_list'):
self.enums_list = []
self.meths.append('process_enums')
self.enums_list.append({'source': source,
'target': target,
'template': template,
'file-head': '',
'file-prod': '',
'file-tail': '',
'enum-prod': '',
'value-head': '',
'value-prod': '',
'value-tail': '',
'comments': comments})
|
[
"def",
"add_enums_from_template",
"(",
"self",
",",
"source",
"=",
"''",
",",
"target",
"=",
"''",
",",
"template",
"=",
"''",
",",
"comments",
"=",
"''",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'enums_list'",
")",
":",
"self",
".",
"enums_list",
"=",
"[",
"]",
"self",
".",
"meths",
".",
"append",
"(",
"'process_enums'",
")",
"self",
".",
"enums_list",
".",
"append",
"(",
"{",
"'source'",
":",
"source",
",",
"'target'",
":",
"target",
",",
"'template'",
":",
"template",
",",
"'file-head'",
":",
"''",
",",
"'file-prod'",
":",
"''",
",",
"'file-tail'",
":",
"''",
",",
"'enum-prod'",
":",
"''",
",",
"'value-head'",
":",
"''",
",",
"'value-prod'",
":",
"''",
",",
"'value-tail'",
":",
"''",
",",
"'comments'",
":",
"comments",
"}",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/glib2.py#L90-L116
|
||
pytorch/pytorch
|
7176c92687d3cc847cc046bf002269c6949a21c2
|
torch/jit/mobile/__init__.py
|
python
|
_get_model_bytecode_version
|
(f_input)
|
r"""
Args:
f_input: a file-like object (has to implement read, readline, tell, and seek),
or a string containing a file name
Returns:
version: An integer. If the integer is -1, the version is invalid. A warning
will show in the log.
Example:
.. testcode::
from torch.jit.mobile import _get_model_bytecode_version
# Get bytecode version from a saved file path
version = _get_model_bytecode_version("path/to/model.ptl")
|
r"""
Args:
f_input: a file-like object (has to implement read, readline, tell, and seek),
or a string containing a file name
|
[
"r",
"Args",
":",
"f_input",
":",
"a",
"file",
"-",
"like",
"object",
"(",
"has",
"to",
"implement",
"read",
"readline",
"tell",
"and",
"seek",
")",
"or",
"a",
"string",
"containing",
"a",
"file",
"name"
] |
def _get_model_bytecode_version(f_input) -> int:
r"""
Args:
f_input: a file-like object (has to implement read, readline, tell, and seek),
or a string containing a file name
Returns:
version: An integer. If the integer is -1, the version is invalid. A warning
will show in the log.
Example:
.. testcode::
from torch.jit.mobile import _get_model_bytecode_version
# Get bytecode version from a saved file path
version = _get_model_bytecode_version("path/to/model.ptl")
"""
if isinstance(f_input, str):
if not os.path.exists(f_input):
raise ValueError(f"The provided filename {f_input} does not exist")
if os.path.isdir(f_input):
raise ValueError(f"The provided filename {f_input} is a directory")
if (isinstance(f_input, str) or isinstance(f_input, pathlib.Path)):
return torch._C._get_model_bytecode_version(str(f_input))
else:
return torch._C._get_model_bytecode_version_from_buffer(f_input.read())
|
[
"def",
"_get_model_bytecode_version",
"(",
"f_input",
")",
"->",
"int",
":",
"if",
"isinstance",
"(",
"f_input",
",",
"str",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"f_input",
")",
":",
"raise",
"ValueError",
"(",
"f\"The provided filename {f_input} does not exist\"",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"f_input",
")",
":",
"raise",
"ValueError",
"(",
"f\"The provided filename {f_input} is a directory\"",
")",
"if",
"(",
"isinstance",
"(",
"f_input",
",",
"str",
")",
"or",
"isinstance",
"(",
"f_input",
",",
"pathlib",
".",
"Path",
")",
")",
":",
"return",
"torch",
".",
"_C",
".",
"_get_model_bytecode_version",
"(",
"str",
"(",
"f_input",
")",
")",
"else",
":",
"return",
"torch",
".",
"_C",
".",
"_get_model_bytecode_version_from_buffer",
"(",
"f_input",
".",
"read",
"(",
")",
")"
] |
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/jit/mobile/__init__.py#L78-L107
|
||
Kitware/ParaView
|
f760af9124ff4634b23ebbeab95a4f56e0261955
|
ThirdParty/cinema/paraview/tpl/cinema_python/database/store.py
|
python
|
make_field
|
(name, _values, **kwargs)
|
return properties
|
specialization of make_parameters for parameters that define fields
(aka color inputs). In this case the values is a list of name, type pairs
where types must be one of 'rgb', 'lut', 'depth', 'value', or 'luminance'
May also be given an set of valueRanges, which have min and max values for
named 'value' type color selections.
|
specialization of make_parameters for parameters that define fields
(aka color inputs). In this case the values is a list of name, type pairs
where types must be one of 'rgb', 'lut', 'depth', 'value', or 'luminance'
May also be given an set of valueRanges, which have min and max values for
named 'value' type color selections.
|
[
"specialization",
"of",
"make_parameters",
"for",
"parameters",
"that",
"define",
"fields",
"(",
"aka",
"color",
"inputs",
")",
".",
"In",
"this",
"case",
"the",
"values",
"is",
"a",
"list",
"of",
"name",
"type",
"pairs",
"where",
"types",
"must",
"be",
"one",
"of",
"rgb",
"lut",
"depth",
"value",
"or",
"luminance",
"May",
"also",
"be",
"given",
"an",
"set",
"of",
"valueRanges",
"which",
"have",
"min",
"and",
"max",
"values",
"for",
"named",
"value",
"type",
"color",
"selections",
"."
] |
def make_field(name, _values, **kwargs):
"""
specialization of make_parameters for parameters that define fields
(aka color inputs). In this case the values is a list of name, type pairs
where types must be one of 'rgb', 'lut', 'depth', 'value', or 'luminance'
May also be given an set of valueRanges, which have min and max values for
named 'value' type color selections.
"""
values = list(_values.keys())
img_types = list(_values.values())
valid_itypes = ['rgb', 'lut', 'depth', 'value', 'luminance', 'normals']
for i in img_types:
if i not in valid_itypes:
raise RuntimeError(
"Invalid typechoice, must be one of %s" % str(valid_itypes))
default = kwargs['default'] if 'default' in kwargs else values[0]
if default not in values:
raise RuntimeError("Invalid default, must be one of %s" % str(values))
typechoice = 'hidden'
label = kwargs['label'] if 'label' in kwargs else name
properties = dict()
properties['type'] = typechoice
properties['label'] = label
properties['values'] = values
properties['default'] = default
properties['types'] = img_types
if 'valueRanges' in kwargs:
properties['valueRanges'] = kwargs['valueRanges']
return properties
|
[
"def",
"make_field",
"(",
"name",
",",
"_values",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"list",
"(",
"_values",
".",
"keys",
"(",
")",
")",
"img_types",
"=",
"list",
"(",
"_values",
".",
"values",
"(",
")",
")",
"valid_itypes",
"=",
"[",
"'rgb'",
",",
"'lut'",
",",
"'depth'",
",",
"'value'",
",",
"'luminance'",
",",
"'normals'",
"]",
"for",
"i",
"in",
"img_types",
":",
"if",
"i",
"not",
"in",
"valid_itypes",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid typechoice, must be one of %s\"",
"%",
"str",
"(",
"valid_itypes",
")",
")",
"default",
"=",
"kwargs",
"[",
"'default'",
"]",
"if",
"'default'",
"in",
"kwargs",
"else",
"values",
"[",
"0",
"]",
"if",
"default",
"not",
"in",
"values",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid default, must be one of %s\"",
"%",
"str",
"(",
"values",
")",
")",
"typechoice",
"=",
"'hidden'",
"label",
"=",
"kwargs",
"[",
"'label'",
"]",
"if",
"'label'",
"in",
"kwargs",
"else",
"name",
"properties",
"=",
"dict",
"(",
")",
"properties",
"[",
"'type'",
"]",
"=",
"typechoice",
"properties",
"[",
"'label'",
"]",
"=",
"label",
"properties",
"[",
"'values'",
"]",
"=",
"values",
"properties",
"[",
"'default'",
"]",
"=",
"default",
"properties",
"[",
"'types'",
"]",
"=",
"img_types",
"if",
"'valueRanges'",
"in",
"kwargs",
":",
"properties",
"[",
"'valueRanges'",
"]",
"=",
"kwargs",
"[",
"'valueRanges'",
"]",
"return",
"properties"
] |
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/store.py#L655-L690
|
|
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
third_party/catapult/third_party/webapp2/webapp2_extras/routes.py
|
python
|
PathPrefixRoute.__init__
|
(self, prefix, routes)
|
Initializes a URL route.
:param prefix:
The prefix to be prepended. It must start with a slash but not
end with a slash.
:param routes:
A list of :class:`webapp2.Route` instances.
|
Initializes a URL route.
|
[
"Initializes",
"a",
"URL",
"route",
"."
] |
def __init__(self, prefix, routes):
"""Initializes a URL route.
:param prefix:
The prefix to be prepended. It must start with a slash but not
end with a slash.
:param routes:
A list of :class:`webapp2.Route` instances.
"""
assert prefix.startswith('/') and not prefix.endswith('/'), \
'Path prefixes must start with a slash but not end with a slash.'
super(PathPrefixRoute, self).__init__(prefix, routes)
|
[
"def",
"__init__",
"(",
"self",
",",
"prefix",
",",
"routes",
")",
":",
"assert",
"prefix",
".",
"startswith",
"(",
"'/'",
")",
"and",
"not",
"prefix",
".",
"endswith",
"(",
"'/'",
")",
",",
"'Path prefixes must start with a slash but not end with a slash.'",
"super",
"(",
"PathPrefixRoute",
",",
"self",
")",
".",
"__init__",
"(",
"prefix",
",",
"routes",
")"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2_extras/routes.py#L196-L207
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/delete.py
|
python
|
DeleteObjectTask._main
|
(self, client, bucket, key, extra_args)
|
:param client: The S3 client to use when calling DeleteObject
:type bucket: str
:param bucket: The name of the bucket.
:type key: str
:param key: The name of the object to delete.
:type extra_args: dict
:param extra_args: Extra arguments to pass to the DeleteObject call.
|
[] |
def _main(self, client, bucket, key, extra_args):
"""
:param client: The S3 client to use when calling DeleteObject
:type bucket: str
:param bucket: The name of the bucket.
:type key: str
:param key: The name of the object to delete.
:type extra_args: dict
:param extra_args: Extra arguments to pass to the DeleteObject call.
"""
client.delete_object(Bucket=bucket, Key=key, **extra_args)
|
[
"def",
"_main",
"(",
"self",
",",
"client",
",",
"bucket",
",",
"key",
",",
"extra_args",
")",
":",
"client",
".",
"delete_object",
"(",
"Bucket",
"=",
"bucket",
",",
"Key",
"=",
"key",
",",
"*",
"*",
"extra_args",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/delete.py#L57-L72
|
|||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/aui.py
|
python
|
AuiToolBarItem.GetId
|
(*args, **kwargs)
|
return _aui.AuiToolBarItem_GetId(*args, **kwargs)
|
GetId(self) -> int
|
GetId(self) -> int
|
[
"GetId",
"(",
"self",
")",
"-",
">",
"int"
] |
def GetId(*args, **kwargs):
"""GetId(self) -> int"""
return _aui.AuiToolBarItem_GetId(*args, **kwargs)
|
[
"def",
"GetId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBarItem_GetId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L1741-L1743
|
|
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
scripts/abins/abinsalgorithm.py
|
python
|
AbinsAlgorithm._validate_gaussian_input_file
|
(cls, filename_full_path: str)
|
return cls._validate_ab_initio_file_extension(ab_initio_program="GAUSSIAN",
filename_full_path=filename_full_path,
expected_file_extension=".log")
|
Method to validate input file for GAUSSIAN ab initio program.
:param filename_full_path: full path of a file to check.
:returns: True if file is valid otherwise false.
|
Method to validate input file for GAUSSIAN ab initio program.
:param filename_full_path: full path of a file to check.
:returns: True if file is valid otherwise false.
|
[
"Method",
"to",
"validate",
"input",
"file",
"for",
"GAUSSIAN",
"ab",
"initio",
"program",
".",
":",
"param",
"filename_full_path",
":",
"full",
"path",
"of",
"a",
"file",
"to",
"check",
".",
":",
"returns",
":",
"True",
"if",
"file",
"is",
"valid",
"otherwise",
"false",
"."
] |
def _validate_gaussian_input_file(cls, filename_full_path: str) -> dict:
"""
Method to validate input file for GAUSSIAN ab initio program.
:param filename_full_path: full path of a file to check.
:returns: True if file is valid otherwise false.
"""
logger.information("Validate GAUSSIAN file with vibration data.")
return cls._validate_ab_initio_file_extension(ab_initio_program="GAUSSIAN",
filename_full_path=filename_full_path,
expected_file_extension=".log")
|
[
"def",
"_validate_gaussian_input_file",
"(",
"cls",
",",
"filename_full_path",
":",
"str",
")",
"->",
"dict",
":",
"logger",
".",
"information",
"(",
"\"Validate GAUSSIAN file with vibration data.\"",
")",
"return",
"cls",
".",
"_validate_ab_initio_file_extension",
"(",
"ab_initio_program",
"=",
"\"GAUSSIAN\"",
",",
"filename_full_path",
"=",
"filename_full_path",
",",
"expected_file_extension",
"=",
"\".log\"",
")"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/abinsalgorithm.py#L658-L667
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/util/hashing.py
|
python
|
_combine_hash_arrays
|
(arrays, num_items: int)
|
return out
|
Parameters
----------
arrays : generator
num_items : int
Should be the same as CPython's tupleobject.c
|
Parameters
----------
arrays : generator
num_items : int
|
[
"Parameters",
"----------",
"arrays",
":",
"generator",
"num_items",
":",
"int"
] |
def _combine_hash_arrays(arrays, num_items: int):
"""
Parameters
----------
arrays : generator
num_items : int
Should be the same as CPython's tupleobject.c
"""
try:
first = next(arrays)
except StopIteration:
return np.array([], dtype=np.uint64)
arrays = itertools.chain([first], arrays)
mult = np.uint64(1000003)
out = np.zeros_like(first) + np.uint64(0x345678)
for i, a in enumerate(arrays):
inverse_i = num_items - i
out ^= a
out *= mult
mult += np.uint64(82520 + inverse_i + inverse_i)
assert i + 1 == num_items, "Fed in wrong num_items"
out += np.uint64(97531)
return out
|
[
"def",
"_combine_hash_arrays",
"(",
"arrays",
",",
"num_items",
":",
"int",
")",
":",
"try",
":",
"first",
"=",
"next",
"(",
"arrays",
")",
"except",
"StopIteration",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"np",
".",
"uint64",
")",
"arrays",
"=",
"itertools",
".",
"chain",
"(",
"[",
"first",
"]",
",",
"arrays",
")",
"mult",
"=",
"np",
".",
"uint64",
"(",
"1000003",
")",
"out",
"=",
"np",
".",
"zeros_like",
"(",
"first",
")",
"+",
"np",
".",
"uint64",
"(",
"0x345678",
")",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"arrays",
")",
":",
"inverse_i",
"=",
"num_items",
"-",
"i",
"out",
"^=",
"a",
"out",
"*=",
"mult",
"mult",
"+=",
"np",
".",
"uint64",
"(",
"82520",
"+",
"inverse_i",
"+",
"inverse_i",
")",
"assert",
"i",
"+",
"1",
"==",
"num_items",
",",
"\"Fed in wrong num_items\"",
"out",
"+=",
"np",
".",
"uint64",
"(",
"97531",
")",
"return",
"out"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/util/hashing.py#L30-L55
|
|
natanielruiz/android-yolo
|
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
|
jni-build/jni/include/external/bazel_tools/tools/build_defs/docker/create_image_config.py
|
python
|
DeepCopySkipNull
|
(data)
|
return copy.deepcopy(data)
|
Do a deep copy, skipping null entry.
|
Do a deep copy, skipping null entry.
|
[
"Do",
"a",
"deep",
"copy",
"skipping",
"null",
"entry",
"."
] |
def DeepCopySkipNull(data):
"""Do a deep copy, skipping null entry."""
if isinstance(data, dict):
return dict((DeepCopySkipNull(k), DeepCopySkipNull(v))
for k, v in data.iteritems() if v is not None)
return copy.deepcopy(data)
|
[
"def",
"DeepCopySkipNull",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"DeepCopySkipNull",
"(",
"k",
")",
",",
"DeepCopySkipNull",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"data",
".",
"iteritems",
"(",
")",
"if",
"v",
"is",
"not",
"None",
")",
"return",
"copy",
".",
"deepcopy",
"(",
"data",
")"
] |
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/tools/build_defs/docker/create_image_config.py#L99-L104
|
|
namecoin/namecoin-legacy
|
b043fba28018721b68c90edfc81b9eacb070b47d
|
client/DNS/lazy.py
|
python
|
revlookup
|
(name)
|
convenience routine for doing a reverse lookup of an address
|
convenience routine for doing a reverse lookup of an address
|
[
"convenience",
"routine",
"for",
"doing",
"a",
"reverse",
"lookup",
"of",
"an",
"address"
] |
def revlookup(name):
"convenience routine for doing a reverse lookup of an address"
if Base.defaults['server'] == []: Base.DiscoverNameServers()
a = string.split(name, '.')
a.reverse()
b = string.join(a, '.')+'.in-addr.arpa'
# this will only return one of any records returned.
result = Base.DnsRequest(b, qtype = 'ptr').req()
if result.header['status'] != 'NOERROR':
raise StatusError("DNS query status: %s" % result.header['status'])
elif len(result.answers) == 0:
raise NoDataError("No PTR records for %s" % name)
else:
return result.answers[0]['data']
|
[
"def",
"revlookup",
"(",
"name",
")",
":",
"if",
"Base",
".",
"defaults",
"[",
"'server'",
"]",
"==",
"[",
"]",
":",
"Base",
".",
"DiscoverNameServers",
"(",
")",
"a",
"=",
"string",
".",
"split",
"(",
"name",
",",
"'.'",
")",
"a",
".",
"reverse",
"(",
")",
"b",
"=",
"string",
".",
"join",
"(",
"a",
",",
"'.'",
")",
"+",
"'.in-addr.arpa'",
"# this will only return one of any records returned.",
"result",
"=",
"Base",
".",
"DnsRequest",
"(",
"b",
",",
"qtype",
"=",
"'ptr'",
")",
".",
"req",
"(",
")",
"if",
"result",
".",
"header",
"[",
"'status'",
"]",
"!=",
"'NOERROR'",
":",
"raise",
"StatusError",
"(",
"\"DNS query status: %s\"",
"%",
"result",
".",
"header",
"[",
"'status'",
"]",
")",
"elif",
"len",
"(",
"result",
".",
"answers",
")",
"==",
"0",
":",
"raise",
"NoDataError",
"(",
"\"No PTR records for %s\"",
"%",
"name",
")",
"else",
":",
"return",
"result",
".",
"answers",
"[",
"0",
"]",
"[",
"'data'",
"]"
] |
https://github.com/namecoin/namecoin-legacy/blob/b043fba28018721b68c90edfc81b9eacb070b47d/client/DNS/lazy.py#L16-L29
|
||
nasa/fprime
|
595cf3682d8365943d86c1a6fe7c78f0a116acf0
|
Autocoders/Python/src/fprime_ac/generators/DictStart.py
|
python
|
DictStart.addVisitor
|
(self, visitor)
|
Add a visitor to the list of visitors.
@param visitor: the visitor to add, must be derived from AbstractVisitor.
|
Add a visitor to the list of visitors.
|
[
"Add",
"a",
"visitor",
"to",
"the",
"list",
"of",
"visitors",
"."
] |
def addVisitor(self, visitor):
"""
Add a visitor to the list of visitors.
@param visitor: the visitor to add, must be derived from AbstractVisitor.
"""
if issubclass(visitor.__class__, AbstractVisitor.AbstractVisitor):
self.__visitor_list.append(visitor)
else:
DEBUG.error(
"DictStartVisit.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!"
)
raise Exception(
"DictStartVisit.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!"
)
|
[
"def",
"addVisitor",
"(",
"self",
",",
"visitor",
")",
":",
"if",
"issubclass",
"(",
"visitor",
".",
"__class__",
",",
"AbstractVisitor",
".",
"AbstractVisitor",
")",
":",
"self",
".",
"__visitor_list",
".",
"append",
"(",
"visitor",
")",
"else",
":",
"DEBUG",
".",
"error",
"(",
"\"DictStartVisit.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!\"",
")",
"raise",
"Exception",
"(",
"\"DictStartVisit.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!\"",
")"
] |
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/DictStart.py#L86-L99
|
||
google/syzygy
|
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
|
third_party/numpy/files/numpy/oldnumeric/ma.py
|
python
|
MaskedArray.__xor__
|
(self, other)
|
return bitwise_xor(self, other)
|
Return bitwise_xor
|
Return bitwise_xor
|
[
"Return",
"bitwise_xor"
] |
def __xor__(self, other):
"Return bitwise_xor"
return bitwise_xor(self, other)
|
[
"def",
"__xor__",
"(",
"self",
",",
"other",
")",
":",
"return",
"bitwise_xor",
"(",
"self",
",",
"other",
")"
] |
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L879-L881
|
|
y123456yz/reading-and-annotate-mongodb-3.6
|
93280293672ca7586dc24af18132aa61e4ed7fcf
|
mongo/buildscripts/clang_format.py
|
python
|
ClangFormat._validate_version
|
(self)
|
return False
|
Validate clang-format is the expected version
|
Validate clang-format is the expected version
|
[
"Validate",
"clang",
"-",
"format",
"is",
"the",
"expected",
"version"
] |
def _validate_version(self):
"""Validate clang-format is the expected version
"""
cf_version = callo([self.path, "--version"])
if CLANG_FORMAT_VERSION in cf_version:
return True
print("WARNING: clang-format found in path, but incorrect version found at " +
self.path + " with version: " + cf_version)
return False
|
[
"def",
"_validate_version",
"(",
"self",
")",
":",
"cf_version",
"=",
"callo",
"(",
"[",
"self",
".",
"path",
",",
"\"--version\"",
"]",
")",
"if",
"CLANG_FORMAT_VERSION",
"in",
"cf_version",
":",
"return",
"True",
"print",
"(",
"\"WARNING: clang-format found in path, but incorrect version found at \"",
"+",
"self",
".",
"path",
"+",
"\" with version: \"",
"+",
"cf_version",
")",
"return",
"False"
] |
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/clang_format.py#L215-L226
|
|
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/refactor.py
|
python
|
RefactoringTool._read_python_source
|
(self, filename)
|
Do our best to decode a Python source file correctly.
|
Do our best to decode a Python source file correctly.
|
[
"Do",
"our",
"best",
"to",
"decode",
"a",
"Python",
"source",
"file",
"correctly",
"."
] |
def _read_python_source(self, filename):
"""
Do our best to decode a Python source file correctly.
"""
try:
f = open(filename, "rb")
except IOError as err:
self.log_error("Can't open %s: %s", filename, err)
return None, None
try:
encoding = tokenize.detect_encoding(f.readline)[0]
finally:
f.close()
with _open_with_encoding(filename, "r", encoding=encoding) as f:
return _from_system_newlines(f.read()), encoding
|
[
"def",
"_read_python_source",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"except",
"IOError",
"as",
"err",
":",
"self",
".",
"log_error",
"(",
"\"Can't open %s: %s\"",
",",
"filename",
",",
"err",
")",
"return",
"None",
",",
"None",
"try",
":",
"encoding",
"=",
"tokenize",
".",
"detect_encoding",
"(",
"f",
".",
"readline",
")",
"[",
"0",
"]",
"finally",
":",
"f",
".",
"close",
"(",
")",
"with",
"_open_with_encoding",
"(",
"filename",
",",
"\"r\"",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"return",
"_from_system_newlines",
"(",
"f",
".",
"read",
"(",
")",
")",
",",
"encoding"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/refactor.py#L323-L337
|
||
miyosuda/TensorFlowAndroidMNIST
|
7b5a4603d2780a8a2834575706e9001977524007
|
jni-build/jni/include/tensorflow/models/image/imagenet/classify_image.py
|
python
|
maybe_download_and_extract
|
()
|
Download and extract model tar file.
|
Download and extract model tar file.
|
[
"Download",
"and",
"extract",
"model",
"tar",
"file",
"."
] |
def maybe_download_and_extract():
"""Download and extract model tar file."""
dest_directory = FLAGS.model_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dest_directory)
|
[
"def",
"maybe_download_and_extract",
"(",
")",
":",
"dest_directory",
"=",
"FLAGS",
".",
"model_dir",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest_directory",
")",
":",
"os",
".",
"makedirs",
"(",
"dest_directory",
")",
"filename",
"=",
"DATA_URL",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest_directory",
",",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
":",
"def",
"_progress",
"(",
"count",
",",
"block_size",
",",
"total_size",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\r>> Downloading %s %.1f%%'",
"%",
"(",
"filename",
",",
"float",
"(",
"count",
"*",
"block_size",
")",
"/",
"float",
"(",
"total_size",
")",
"*",
"100.0",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"filepath",
",",
"_",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"DATA_URL",
",",
"filepath",
",",
"_progress",
")",
"print",
"(",
")",
"statinfo",
"=",
"os",
".",
"stat",
"(",
"filepath",
")",
"print",
"(",
"'Succesfully downloaded'",
",",
"filename",
",",
"statinfo",
".",
"st_size",
",",
"'bytes.'",
")",
"tarfile",
".",
"open",
"(",
"filepath",
",",
"'r:gz'",
")",
".",
"extractall",
"(",
"dest_directory",
")"
] |
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/models/image/imagenet/classify_image.py#L185-L201
|
||
intel-iot-devkit/how-to-code-samples
|
b4ea616f36bbfa2e042beb1698f968cfd651d79f
|
fire-alarm/python/iot_fire_alarm/hardware/board.py
|
python
|
Board.trigger_hardware_event
|
(self, event, *args, **kwargs)
|
Signal hardware event.
|
Signal hardware event.
|
[
"Signal",
"hardware",
"event",
"."
] |
def trigger_hardware_event(self, event, *args, **kwargs):
"""
Signal hardware event.
"""
self.emitter.emit(event, *args, **kwargs)
|
[
"def",
"trigger_hardware_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"emitter",
".",
"emit",
"(",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/fire-alarm/python/iot_fire_alarm/hardware/board.py#L67-L73
|
||
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
qt/python/mantidqtinterfaces/mantidqtinterfaces/PyChop/ISISDisk.py
|
python
|
ISISDisk.getResFlux
|
(self, Etrans=None, Ei_in=None, frequency=None)
|
return self.getResolution(Etrans, Ei_in, frequency), self.getFlux(Ei_in, frequency)
|
Returns the resolution and flux at a given Ei as a tuple
|
Returns the resolution and flux at a given Ei as a tuple
|
[
"Returns",
"the",
"resolution",
"and",
"flux",
"at",
"a",
"given",
"Ei",
"as",
"a",
"tuple"
] |
def getResFlux(self, Etrans=None, Ei_in=None, frequency=None):
"""
Returns the resolution and flux at a given Ei as a tuple
"""
return self.getResolution(Etrans, Ei_in, frequency), self.getFlux(Ei_in, frequency)
|
[
"def",
"getResFlux",
"(",
"self",
",",
"Etrans",
"=",
"None",
",",
"Ei_in",
"=",
"None",
",",
"frequency",
"=",
"None",
")",
":",
"return",
"self",
".",
"getResolution",
"(",
"Etrans",
",",
"Ei_in",
",",
"frequency",
")",
",",
"self",
".",
"getFlux",
"(",
"Ei_in",
",",
"frequency",
")"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/PyChop/ISISDisk.py#L372-L376
|
|
kamyu104/LeetCode-Solutions
|
77605708a927ea3b85aee5a479db733938c7c211
|
Python/find-unique-binary-string.py
|
python
|
Solution2.findDifferentBinaryString
|
(self, nums)
|
return next(bin(i)[2:].zfill(len(nums[0])) for i in xrange(2**len(nums[0])) if i not in lookup)
|
:type nums: List[str]
:rtype: str
|
:type nums: List[str]
:rtype: str
|
[
":",
"type",
"nums",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"str"
] |
def findDifferentBinaryString(self, nums):
"""
:type nums: List[str]
:rtype: str
"""
lookup = set(map(lambda x: int(x, 2), nums)) # Time: O(k * n) = O(n^2)
return next(bin(i)[2:].zfill(len(nums[0])) for i in xrange(2**len(nums[0])) if i not in lookup)
|
[
"def",
"findDifferentBinaryString",
"(",
"self",
",",
"nums",
")",
":",
"lookup",
"=",
"set",
"(",
"map",
"(",
"lambda",
"x",
":",
"int",
"(",
"x",
",",
"2",
")",
",",
"nums",
")",
")",
"# Time: O(k * n) = O(n^2)",
"return",
"next",
"(",
"bin",
"(",
"i",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"len",
"(",
"nums",
"[",
"0",
"]",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"2",
"**",
"len",
"(",
"nums",
"[",
"0",
"]",
")",
")",
"if",
"i",
"not",
"in",
"lookup",
")"
] |
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-unique-binary-string.py#L17-L23
|
|
mongodb/mongo
|
d8ff665343ad29cf286ee2cf4a1960d29371937b
|
buildscripts/resmokelib/symbolizer/__init__.py
|
python
|
SymbolizerPlugin.add_subcommand
|
(self, subparsers)
|
Add 'symbolize' subcommand.
:param subparsers: argparse parser to add to
:return: None
|
Add 'symbolize' subcommand.
|
[
"Add",
"symbolize",
"subcommand",
"."
] |
def add_subcommand(self, subparsers):
"""
Add 'symbolize' subcommand.
:param subparsers: argparse parser to add to
:return: None
"""
parser = subparsers.add_parser(_COMMAND, help=_HELP)
parser.add_argument(
"--task-id", '-t', action="store", type=str, required=True,
help="Fetch corresponding binaries and/or symbols given an Evergreen task ID")
parser.add_argument(
"--binary-name", "-b", action="store", type=str, default="mongod",
help="Base name of the binary that generated the stacktrace; e.g. `mongod` or `mongos`")
parser.add_argument("--download-symbols-only", "-s", action="store_true", default=False,
help="Just download the debug symbol tarball for the given task-id")
parser.add_argument("--debug", "-d", dest="debug", action="store_true", default=False,
help="Set DEBUG logging level.")
group = parser.add_argument_group(
"Verbatim mongosymb.py options for advanced usages",
description="Compatibility not guaranteed, use at your own risk")
mongosymb.make_argument_parser(group)
|
[
"def",
"add_subcommand",
"(",
"self",
",",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"_COMMAND",
",",
"help",
"=",
"_HELP",
")",
"parser",
".",
"add_argument",
"(",
"\"--task-id\"",
",",
"'-t'",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"str",
",",
"required",
"=",
"True",
",",
"help",
"=",
"\"Fetch corresponding binaries and/or symbols given an Evergreen task ID\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--binary-name\"",
",",
"\"-b\"",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"mongod\"",
",",
"help",
"=",
"\"Base name of the binary that generated the stacktrace; e.g. `mongod` or `mongos`\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--download-symbols-only\"",
",",
"\"-s\"",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Just download the debug symbol tarball for the given task-id\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--debug\"",
",",
"\"-d\"",
",",
"dest",
"=",
"\"debug\"",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Set DEBUG logging level.\"",
")",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Verbatim mongosymb.py options for advanced usages\"",
",",
"description",
"=",
"\"Compatibility not guaranteed, use at your own risk\"",
")",
"mongosymb",
".",
"make_argument_parser",
"(",
"group",
")"
] |
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/symbolizer/__init__.py#L208-L233
|
||
ChromiumWebApps/chromium
|
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
|
tools/perf/metrics/v8_object_stats.py
|
python
|
V8ObjectStatsMetric.Stop
|
(self, page, tab)
|
Get the values in the stats table after the page is loaded.
|
Get the values in the stats table after the page is loaded.
|
[
"Get",
"the",
"values",
"in",
"the",
"stats",
"table",
"after",
"the",
"page",
"is",
"loaded",
"."
] |
def Stop(self, page, tab):
"""Get the values in the stats table after the page is loaded."""
self._results = V8ObjectStatsMetric.GetV8StatsTable(tab, self._counters)
if not self._results:
logging.warning('No V8 object stats from website: ' + page.display_name)
|
[
"def",
"Stop",
"(",
"self",
",",
"page",
",",
"tab",
")",
":",
"self",
".",
"_results",
"=",
"V8ObjectStatsMetric",
".",
"GetV8StatsTable",
"(",
"tab",
",",
"self",
".",
"_counters",
")",
"if",
"not",
"self",
".",
"_results",
":",
"logging",
".",
"warning",
"(",
"'No V8 object stats from website: '",
"+",
"page",
".",
"display_name",
")"
] |
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/perf/metrics/v8_object_stats.py#L205-L209
|
||
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
third_party/protobuf/python/google/protobuf/text_format.py
|
python
|
_Tokenizer.Consume
|
(self, token)
|
Consumes a piece of text.
Args:
token: Text to consume.
Raises:
ParseError: If the text couldn't be consumed.
|
Consumes a piece of text.
|
[
"Consumes",
"a",
"piece",
"of",
"text",
"."
] |
def Consume(self, token):
"""Consumes a piece of text.
Args:
token: Text to consume.
Raises:
ParseError: If the text couldn't be consumed.
"""
if not self.TryConsume(token):
raise self._ParseError('Expected "%s".' % token)
|
[
"def",
"Consume",
"(",
"self",
",",
"token",
")",
":",
"if",
"not",
"self",
".",
"TryConsume",
"(",
"token",
")",
":",
"raise",
"self",
".",
"_ParseError",
"(",
"'Expected \"%s\".'",
"%",
"token",
")"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/text_format.py#L841-L851
|
||
apache/incubator-mxnet
|
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
|
python/mxnet/ndarray/ndarray.py
|
python
|
NDArray.__div__
|
(self, other)
|
return divide(self, other)
|
x.__div__(y) <=> x/y <=> mx.nd.divide(x, y)
|
x.__div__(y) <=> x/y <=> mx.nd.divide(x, y)
|
[
"x",
".",
"__div__",
"(",
"y",
")",
"<",
"=",
">",
"x",
"/",
"y",
"<",
"=",
">",
"mx",
".",
"nd",
".",
"divide",
"(",
"x",
"y",
")"
] |
def __div__(self, other):
"""x.__div__(y) <=> x/y <=> mx.nd.divide(x, y) """
return divide(self, other)
|
[
"def",
"__div__",
"(",
"self",
",",
"other",
")",
":",
"return",
"divide",
"(",
"self",
",",
"other",
")"
] |
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L366-L368
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/package_finder.py
|
python
|
PackageFinder.find_all_candidates
|
(self, project_name)
|
return file_versions + find_links_versions + page_versions
|
Find all available InstallationCandidate for project_name
This checks index_urls and find_links.
All versions found are returned as an InstallationCandidate list.
See LinkEvaluator.evaluate_link() for details on which files
are accepted.
|
Find all available InstallationCandidate for project_name
|
[
"Find",
"all",
"available",
"InstallationCandidate",
"for",
"project_name"
] |
def find_all_candidates(self, project_name):
# type: (str) -> List[InstallationCandidate]
"""Find all available InstallationCandidate for project_name
This checks index_urls and find_links.
All versions found are returned as an InstallationCandidate list.
See LinkEvaluator.evaluate_link() for details on which files
are accepted.
"""
collected_links = self._link_collector.collect_links(project_name)
link_evaluator = self.make_link_evaluator(project_name)
find_links_versions = self.evaluate_links(
link_evaluator,
links=collected_links.find_links,
)
page_versions = []
for project_url in collected_links.project_urls:
package_links = self.process_project_url(
project_url, link_evaluator=link_evaluator,
)
page_versions.extend(package_links)
file_versions = self.evaluate_links(
link_evaluator,
links=collected_links.files,
)
if file_versions:
file_versions.sort(reverse=True)
logger.debug(
'Local files found: %s',
', '.join([
url_to_path(candidate.link.url)
for candidate in file_versions
])
)
# This is an intentional priority ordering
return file_versions + find_links_versions + page_versions
|
[
"def",
"find_all_candidates",
"(",
"self",
",",
"project_name",
")",
":",
"# type: (str) -> List[InstallationCandidate]",
"collected_links",
"=",
"self",
".",
"_link_collector",
".",
"collect_links",
"(",
"project_name",
")",
"link_evaluator",
"=",
"self",
".",
"make_link_evaluator",
"(",
"project_name",
")",
"find_links_versions",
"=",
"self",
".",
"evaluate_links",
"(",
"link_evaluator",
",",
"links",
"=",
"collected_links",
".",
"find_links",
",",
")",
"page_versions",
"=",
"[",
"]",
"for",
"project_url",
"in",
"collected_links",
".",
"project_urls",
":",
"package_links",
"=",
"self",
".",
"process_project_url",
"(",
"project_url",
",",
"link_evaluator",
"=",
"link_evaluator",
",",
")",
"page_versions",
".",
"extend",
"(",
"package_links",
")",
"file_versions",
"=",
"self",
".",
"evaluate_links",
"(",
"link_evaluator",
",",
"links",
"=",
"collected_links",
".",
"files",
",",
")",
"if",
"file_versions",
":",
"file_versions",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"logger",
".",
"debug",
"(",
"'Local files found: %s'",
",",
"', '",
".",
"join",
"(",
"[",
"url_to_path",
"(",
"candidate",
".",
"link",
".",
"url",
")",
"for",
"candidate",
"in",
"file_versions",
"]",
")",
")",
"# This is an intentional priority ordering",
"return",
"file_versions",
"+",
"find_links_versions",
"+",
"page_versions"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/package_finder.py#L794-L835
|
|
mongodb/mongo
|
d8ff665343ad29cf286ee2cf4a1960d29371937b
|
buildscripts/idl/idl_compatibility_errors.py
|
python
|
IDLCompatibilityContext.add_new_command_or_param_type_bson_any_error
|
(self, command_name: str, new_type: str,
file: str, field_name: Optional[str],
is_command_parameter: bool)
|
Add an error about BSON serialization type.
Add an error about the new command or command parameter type's
bson serialization type being of type 'any' when the old type is non-any or
when it is not explicitly allowed.
|
Add an error about BSON serialization type.
|
[
"Add",
"an",
"error",
"about",
"BSON",
"serialization",
"type",
"."
] |
def add_new_command_or_param_type_bson_any_error(self, command_name: str, new_type: str,
file: str, field_name: Optional[str],
is_command_parameter: bool) -> None:
# pylint: disable=too-many-arguments
"""
Add an error about BSON serialization type.
Add an error about the new command or command parameter type's
bson serialization type being of type 'any' when the old type is non-any or
when it is not explicitly allowed.
"""
if is_command_parameter:
self._add_error(
ERROR_ID_NEW_COMMAND_PARAMETER_TYPE_BSON_SERIALIZATION_TYPE_ANY, command_name,
"The '%s' command has field or sub-field '%s' that has type '%s' "
"that has a bson serialization type 'any'" % (command_name, field_name, new_type),
file)
else:
self._add_error(
ERROR_ID_NEW_COMMAND_TYPE_BSON_SERIALIZATION_TYPE_ANY, command_name,
"The '%s' command or its sub-struct has type '%s' that "
"has a bson serialization type 'any'" % (command_name, new_type), file)
|
[
"def",
"add_new_command_or_param_type_bson_any_error",
"(",
"self",
",",
"command_name",
":",
"str",
",",
"new_type",
":",
"str",
",",
"file",
":",
"str",
",",
"field_name",
":",
"Optional",
"[",
"str",
"]",
",",
"is_command_parameter",
":",
"bool",
")",
"->",
"None",
":",
"# pylint: disable=too-many-arguments",
"if",
"is_command_parameter",
":",
"self",
".",
"_add_error",
"(",
"ERROR_ID_NEW_COMMAND_PARAMETER_TYPE_BSON_SERIALIZATION_TYPE_ANY",
",",
"command_name",
",",
"\"The '%s' command has field or sub-field '%s' that has type '%s' \"",
"\"that has a bson serialization type 'any'\"",
"%",
"(",
"command_name",
",",
"field_name",
",",
"new_type",
")",
",",
"file",
")",
"else",
":",
"self",
".",
"_add_error",
"(",
"ERROR_ID_NEW_COMMAND_TYPE_BSON_SERIALIZATION_TYPE_ANY",
",",
"command_name",
",",
"\"The '%s' command or its sub-struct has type '%s' that \"",
"\"has a bson serialization type 'any'\"",
"%",
"(",
"command_name",
",",
"new_type",
")",
",",
"file",
")"
] |
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl_compatibility_errors.py#L373-L394
|
||
tensorflow/tensorflow
|
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
|
tensorflow/python/ops/ragged/ragged_math_ops.py
|
python
|
_infer_matching_dtype
|
(tensors, dtype_hierarchy)
|
return [math_ops.cast(t, inferred_dtype) for t in tensors]
|
Infers a matching dtype for tensors, and casts them to that dtype.
|
Infers a matching dtype for tensors, and casts them to that dtype.
|
[
"Infers",
"a",
"matching",
"dtype",
"for",
"tensors",
"and",
"casts",
"them",
"to",
"that",
"dtype",
"."
] |
def _infer_matching_dtype(tensors, dtype_hierarchy):
"""Infers a matching dtype for tensors, and casts them to that dtype."""
assert all(t.dtype in dtype_hierarchy for t in tensors)
inferred_dtype = max([t.dtype for t in tensors], key=dtype_hierarchy.index)
return [math_ops.cast(t, inferred_dtype) for t in tensors]
|
[
"def",
"_infer_matching_dtype",
"(",
"tensors",
",",
"dtype_hierarchy",
")",
":",
"assert",
"all",
"(",
"t",
".",
"dtype",
"in",
"dtype_hierarchy",
"for",
"t",
"in",
"tensors",
")",
"inferred_dtype",
"=",
"max",
"(",
"[",
"t",
".",
"dtype",
"for",
"t",
"in",
"tensors",
"]",
",",
"key",
"=",
"dtype_hierarchy",
".",
"index",
")",
"return",
"[",
"math_ops",
".",
"cast",
"(",
"t",
",",
"inferred_dtype",
")",
"for",
"t",
"in",
"tensors",
"]"
] |
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_math_ops.py#L115-L119
|
|
miyosuda/TensorFlowAndroidMNIST
|
7b5a4603d2780a8a2834575706e9001977524007
|
jni-build/jni/include/tensorflow/python/ops/math_grad.py
|
python
|
_MeanGrad
|
(op, grad)
|
return sum_grad / math_ops.cast(factor, sum_grad.dtype), None
|
Gradient for Mean.
|
Gradient for Mean.
|
[
"Gradient",
"for",
"Mean",
"."
] |
def _MeanGrad(op, grad):
"""Gradient for Mean."""
sum_grad = _SumGrad(op, grad)[0]
input_shape = array_ops.shape(op.inputs[0])
output_shape = array_ops.shape(op.outputs[0])
factor = _safe_shape_div(math_ops.reduce_prod(input_shape),
math_ops.reduce_prod(output_shape))
return sum_grad / math_ops.cast(factor, sum_grad.dtype), None
|
[
"def",
"_MeanGrad",
"(",
"op",
",",
"grad",
")",
":",
"sum_grad",
"=",
"_SumGrad",
"(",
"op",
",",
"grad",
")",
"[",
"0",
"]",
"input_shape",
"=",
"array_ops",
".",
"shape",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
"output_shape",
"=",
"array_ops",
".",
"shape",
"(",
"op",
".",
"outputs",
"[",
"0",
"]",
")",
"factor",
"=",
"_safe_shape_div",
"(",
"math_ops",
".",
"reduce_prod",
"(",
"input_shape",
")",
",",
"math_ops",
".",
"reduce_prod",
"(",
"output_shape",
")",
")",
"return",
"sum_grad",
"/",
"math_ops",
".",
"cast",
"(",
"factor",
",",
"sum_grad",
".",
"dtype",
")",
",",
"None"
] |
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/math_grad.py#L99-L106
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/dataview.py
|
python
|
DataViewRenderer.DisableEllipsize
|
(*args, **kwargs)
|
return _dataview.DataViewRenderer_DisableEllipsize(*args, **kwargs)
|
DisableEllipsize(self)
|
DisableEllipsize(self)
|
[
"DisableEllipsize",
"(",
"self",
")"
] |
def DisableEllipsize(*args, **kwargs):
"""DisableEllipsize(self)"""
return _dataview.DataViewRenderer_DisableEllipsize(*args, **kwargs)
|
[
"def",
"DisableEllipsize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewRenderer_DisableEllipsize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1188-L1190
|
|
apache/trafodion
|
8455c839ad6b6d7b6e04edda5715053095b78046
|
core/sqf/src/seatrans/hbase-trx/src/main/python/thrift1/gen-py/hbase/Hbase.py
|
python
|
Iface.scannerClose
|
(self, id)
|
Closes the server-state associated with an open scanner.
@throws IllegalArgument if ScannerID is invalid
Parameters:
- id: id of a scanner returned by scannerOpen
|
Closes the server-state associated with an open scanner.
|
[
"Closes",
"the",
"server",
"-",
"state",
"associated",
"with",
"an",
"open",
"scanner",
"."
] |
def scannerClose(self, id):
"""
Closes the server-state associated with an open scanner.
@throws IllegalArgument if ScannerID is invalid
Parameters:
- id: id of a scanner returned by scannerOpen
"""
pass
|
[
"def",
"scannerClose",
"(",
"self",
",",
"id",
")",
":",
"pass"
] |
https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/core/sqf/src/seatrans/hbase-trx/src/main/python/thrift1/gen-py/hbase/Hbase.py#L578-L587
|
||
google/earthenterprise
|
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
|
earth_enterprise/src/server/wsgi/wms/ogc/common/tiles.py
|
python
|
_PasteTile
|
(im_dest, im_src, box)
|
Copy the image.
Args:
im_dest: Destination of the image to be copied.
im_src: Source image to be copied.
box: the dimentions of the image.
|
Copy the image.
|
[
"Copy",
"the",
"image",
"."
] |
def _PasteTile(im_dest, im_src, box):
"""Copy the image.
Args:
im_dest: Destination of the image to be copied.
im_src: Source image to be copied.
box: the dimentions of the image.
"""
try:
im_dest.paste(im_src, box)
except ValueError, e:
logger.error("Failed to paste:%s", str(e.args[0]))
logger.debug("Size %s vs %s", str(im_src.size), str(im_dest.size))
logger.debug("Mode %s vs %s", str(im_src.mode), str(im_dest.mode))
raise
|
[
"def",
"_PasteTile",
"(",
"im_dest",
",",
"im_src",
",",
"box",
")",
":",
"try",
":",
"im_dest",
".",
"paste",
"(",
"im_src",
",",
"box",
")",
"except",
"ValueError",
",",
"e",
":",
"logger",
".",
"error",
"(",
"\"Failed to paste:%s\"",
",",
"str",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
")",
"logger",
".",
"debug",
"(",
"\"Size %s vs %s\"",
",",
"str",
"(",
"im_src",
".",
"size",
")",
",",
"str",
"(",
"im_dest",
".",
"size",
")",
")",
"logger",
".",
"debug",
"(",
"\"Mode %s vs %s\"",
",",
"str",
"(",
"im_src",
".",
"mode",
")",
",",
"str",
"(",
"im_dest",
".",
"mode",
")",
")",
"raise"
] |
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/wms/ogc/common/tiles.py#L357-L371
|
||
bumptop/BumpTop
|
466d23597a07ae738f4265262fa01087fc6e257c
|
trunk/win/Source/bin/jinja2/filters.py
|
python
|
do_replace
|
(environment, s, old, new, count=None)
|
return s.replace(soft_unicode(old), soft_unicode(new), count)
|
Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
|
Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
|
[
"Return",
"a",
"copy",
"of",
"the",
"value",
"with",
"all",
"occurrences",
"of",
"a",
"substring",
"replaced",
"with",
"a",
"new",
"one",
".",
"The",
"first",
"argument",
"is",
"the",
"substring",
"that",
"should",
"be",
"replaced",
"the",
"second",
"is",
"the",
"replacement",
"string",
".",
"If",
"the",
"optional",
"third",
"argument",
"count",
"is",
"given",
"only",
"the",
"first",
"count",
"occurrences",
"are",
"replaced",
":"
] |
def do_replace(environment, s, old, new, count=None):
"""Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
"""
if count is None:
count = -1
if not environment.autoescape:
return unicode(s).replace(unicode(old), unicode(new), count)
if hasattr(old, '__html__') or hasattr(new, '__html__') and \
not hasattr(s, '__html__'):
s = escape(s)
else:
s = soft_unicode(s)
return s.replace(soft_unicode(old), soft_unicode(new), count)
|
[
"def",
"do_replace",
"(",
"environment",
",",
"s",
",",
"old",
",",
"new",
",",
"count",
"=",
"None",
")",
":",
"if",
"count",
"is",
"None",
":",
"count",
"=",
"-",
"1",
"if",
"not",
"environment",
".",
"autoescape",
":",
"return",
"unicode",
"(",
"s",
")",
".",
"replace",
"(",
"unicode",
"(",
"old",
")",
",",
"unicode",
"(",
"new",
")",
",",
"count",
")",
"if",
"hasattr",
"(",
"old",
",",
"'__html__'",
")",
"or",
"hasattr",
"(",
"new",
",",
"'__html__'",
")",
"and",
"not",
"hasattr",
"(",
"s",
",",
"'__html__'",
")",
":",
"s",
"=",
"escape",
"(",
"s",
")",
"else",
":",
"s",
"=",
"soft_unicode",
"(",
"s",
")",
"return",
"s",
".",
"replace",
"(",
"soft_unicode",
"(",
"old",
")",
",",
"soft_unicode",
"(",
"new",
")",
",",
"count",
")"
] |
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/filters.py#L52-L76
|
|
eclipse/sumo
|
7132a9b8b6eea734bdec38479026b4d8c4336d03
|
tools/contributed/sumopy/agilepy/lib_wx/wxmisc.py
|
python
|
AgileStatusbar.set_fields
|
(self, fields)
|
Sets basic data of fields in status bar.
Argument field is a list with the following format:
[(name1,width1),(name2,width2),...]
|
Sets basic data of fields in status bar.
Argument field is a list with the following format:
[(name1,width1),(name2,width2),...]
|
[
"Sets",
"basic",
"data",
"of",
"fields",
"in",
"status",
"bar",
".",
"Argument",
"field",
"is",
"a",
"list",
"with",
"the",
"following",
"format",
":",
"[",
"(",
"name1",
"width1",
")",
"(",
"name2",
"width2",
")",
"...",
"]"
] |
def set_fields(self, fields):
"""
Sets basic data of fields in status bar.
Argument field is a list with the following format:
[(name1,width1),(name2,width2),...]
"""
self._ind_fields = {}
widths = []
ind = 0
for name, width in fields:
widths.append(width)
self._ind_fields[name] = ind
ind += 1
self.SetFieldsCount(ind)
self.SetStatusWidths(widths)
|
[
"def",
"set_fields",
"(",
"self",
",",
"fields",
")",
":",
"self",
".",
"_ind_fields",
"=",
"{",
"}",
"widths",
"=",
"[",
"]",
"ind",
"=",
"0",
"for",
"name",
",",
"width",
"in",
"fields",
":",
"widths",
".",
"append",
"(",
"width",
")",
"self",
".",
"_ind_fields",
"[",
"name",
"]",
"=",
"ind",
"ind",
"+=",
"1",
"self",
".",
"SetFieldsCount",
"(",
"ind",
")",
"self",
".",
"SetStatusWidths",
"(",
"widths",
")"
] |
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/wxmisc.py#L810-L824
|
||
PaddlePaddle/Paddle
|
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
|
python/paddle/fluid/incubate/fleet/collective/__init__.py
|
python
|
Collective.save_inference_model
|
(self,
executor,
dirname,
feeded_var_names=None,
target_vars=None,
main_program=None,
export_for_deployment=True)
|
Prune the given `main_program` to build a new program especially for
inference, and then save it and all related parameters to given
`dirname` by the `executor`.
|
Prune the given `main_program` to build a new program especially for
inference, and then save it and all related parameters to given
`dirname` by the `executor`.
|
[
"Prune",
"the",
"given",
"main_program",
"to",
"build",
"a",
"new",
"program",
"especially",
"for",
"inference",
"and",
"then",
"save",
"it",
"and",
"all",
"related",
"parameters",
"to",
"given",
"dirname",
"by",
"the",
"executor",
"."
] |
def save_inference_model(self,
executor,
dirname,
feeded_var_names=None,
target_vars=None,
main_program=None,
export_for_deployment=True):
"""
Prune the given `main_program` to build a new program especially for
inference, and then save it and all related parameters to given
`dirname` by the `executor`.
"""
assert isinstance(executor, Executor), \
"In fleet.save_inference_model() function, executor must be as" \
" Executor type."
if main_program is None:
main_program = self._origin_program
assert isinstance(main_program, Program), \
"In fleet.save_inference_model() function, main_program " \
"must be as Program type."
io.save_inference_model(dirname, feeded_var_names, target_vars,
executor, main_program, None, None,
export_for_deployment)
|
[
"def",
"save_inference_model",
"(",
"self",
",",
"executor",
",",
"dirname",
",",
"feeded_var_names",
"=",
"None",
",",
"target_vars",
"=",
"None",
",",
"main_program",
"=",
"None",
",",
"export_for_deployment",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"executor",
",",
"Executor",
")",
",",
"\"In fleet.save_inference_model() function, executor must be as\"",
"\" Executor type.\"",
"if",
"main_program",
"is",
"None",
":",
"main_program",
"=",
"self",
".",
"_origin_program",
"assert",
"isinstance",
"(",
"main_program",
",",
"Program",
")",
",",
"\"In fleet.save_inference_model() function, main_program \"",
"\"must be as Program type.\"",
"io",
".",
"save_inference_model",
"(",
"dirname",
",",
"feeded_var_names",
",",
"target_vars",
",",
"executor",
",",
"main_program",
",",
"None",
",",
"None",
",",
"export_for_deployment",
")"
] |
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/collective/__init__.py#L88-L112
|
||
grpc/grpc
|
27bc6fe7797e43298dc931b96dc57322d0852a9f
|
tools/buildgen/plugins/expand_version.py
|
python
|
Version.php
|
(self)
|
return s
|
Version string for PHP PECL package
|
Version string for PHP PECL package
|
[
"Version",
"string",
"for",
"PHP",
"PECL",
"package"
] |
def php(self):
"""Version string for PHP PECL package"""
s = '%d.%d.%d' % (self.major, self.minor, self.patch)
if self.tag:
if self.tag == 'dev':
s += 'dev'
elif len(self.tag) >= 3 and self.tag[0:3] == 'pre':
s += 'RC%d' % int(self.tag[3:])
else:
raise Exception(
'Don\'t know how to translate version tag "%s" to PECL version'
% self.tag)
return s
|
[
"def",
"php",
"(",
"self",
")",
":",
"s",
"=",
"'%d.%d.%d'",
"%",
"(",
"self",
".",
"major",
",",
"self",
".",
"minor",
",",
"self",
".",
"patch",
")",
"if",
"self",
".",
"tag",
":",
"if",
"self",
".",
"tag",
"==",
"'dev'",
":",
"s",
"+=",
"'dev'",
"elif",
"len",
"(",
"self",
".",
"tag",
")",
">=",
"3",
"and",
"self",
".",
"tag",
"[",
"0",
":",
"3",
"]",
"==",
"'pre'",
":",
"s",
"+=",
"'RC%d'",
"%",
"int",
"(",
"self",
".",
"tag",
"[",
"3",
":",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Don\\'t know how to translate version tag \"%s\" to PECL version'",
"%",
"self",
".",
"tag",
")",
"return",
"s"
] |
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/tools/buildgen/plugins/expand_version.py#L78-L90
|
|
seqan/seqan
|
f5f658343c366c9c3d44ba358ffc9317e78a09ed
|
util/py_lib/seqan/auto_build.py
|
python
|
MinisculeGitWrapper.lsRemote
|
(self, url)
|
return res
|
Execute 'git ls-remote ${url} --tags'.
|
Execute 'git ls-remote ${url} --tags'.
|
[
"Execute",
"git",
"ls",
"-",
"remote",
"$",
"{",
"url",
"}",
"--",
"tags",
"."
] |
def lsRemote(self, url):
"""Execute 'git ls-remote ${url} --tags'."""
# Execute ls-remote command.
print('Executing "%s %s %s"' % (GIT_BINARY, 'ls-remote --tags', url), file=sys.stderr)
popen = subprocess.Popen([GIT_BINARY, 'ls-remote', '--tags', url],
stdout=subprocess.PIPE)
out_data, err_data = popen.communicate()
print(' => %d' % popen.returncode, file=sys.stderr)
if popen.returncode != 0:
print('ERROR during git call.', file=sys.stderr)
return 1
# Parse out revisions and tags names.
lines = out_data.splitlines()
revs_tags = [(line.split()[0], line.split()[-1]) for line in lines]
res = []
for rev, tag in revs_tags:
if '^{}' in tag:
continue # Skip with ^{} in tag name
tag2 = tag[10:]
res.append((rev, tag2))
return res
|
[
"def",
"lsRemote",
"(",
"self",
",",
"url",
")",
":",
"# Execute ls-remote command.",
"print",
"(",
"'Executing \"%s %s %s\"'",
"%",
"(",
"GIT_BINARY",
",",
"'ls-remote --tags'",
",",
"url",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"GIT_BINARY",
",",
"'ls-remote'",
",",
"'--tags'",
",",
"url",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"out_data",
",",
"err_data",
"=",
"popen",
".",
"communicate",
"(",
")",
"print",
"(",
"' => %d'",
"%",
"popen",
".",
"returncode",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"if",
"popen",
".",
"returncode",
"!=",
"0",
":",
"print",
"(",
"'ERROR during git call.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
"1",
"# Parse out revisions and tags names.",
"lines",
"=",
"out_data",
".",
"splitlines",
"(",
")",
"revs_tags",
"=",
"[",
"(",
"line",
".",
"split",
"(",
")",
"[",
"0",
"]",
",",
"line",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
")",
"for",
"line",
"in",
"lines",
"]",
"res",
"=",
"[",
"]",
"for",
"rev",
",",
"tag",
"in",
"revs_tags",
":",
"if",
"'^{}'",
"in",
"tag",
":",
"continue",
"# Skip with ^{} in tag name",
"tag2",
"=",
"tag",
"[",
"10",
":",
"]",
"res",
".",
"append",
"(",
"(",
"rev",
",",
"tag2",
")",
")",
"return",
"res"
] |
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/auto_build.py#L32-L52
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/_gdi.py
|
python
|
Font.SetWeight
|
(*args, **kwargs)
|
return _gdi_.Font_SetWeight(*args, **kwargs)
|
SetWeight(self, int weight)
Sets the font weight.
|
SetWeight(self, int weight)
|
[
"SetWeight",
"(",
"self",
"int",
"weight",
")"
] |
def SetWeight(*args, **kwargs):
"""
SetWeight(self, int weight)
Sets the font weight.
"""
return _gdi_.Font_SetWeight(*args, **kwargs)
|
[
"def",
"SetWeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Font_SetWeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L2420-L2426
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py
|
python
|
makeXMLTags
|
(tagStr)
|
return _makeTags( tagStr, True )
|
Helper to construct opening and closing tag expressions for XML, given a tag name. Matches
tags only in the given upper/lower case.
Example: similar to L{makeHTMLTags}
|
Helper to construct opening and closing tag expressions for XML, given a tag name. Matches
tags only in the given upper/lower case.
|
[
"Helper",
"to",
"construct",
"opening",
"and",
"closing",
"tag",
"expressions",
"for",
"XML",
"given",
"a",
"tag",
"name",
".",
"Matches",
"tags",
"only",
"in",
"the",
"given",
"upper",
"/",
"lower",
"case",
"."
] |
def makeXMLTags(tagStr):
"""
Helper to construct opening and closing tag expressions for XML, given a tag name. Matches
tags only in the given upper/lower case.
Example: similar to L{makeHTMLTags}
"""
return _makeTags( tagStr, True )
|
[
"def",
"makeXMLTags",
"(",
"tagStr",
")",
":",
"return",
"_makeTags",
"(",
"tagStr",
",",
"True",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py#L4923-L4930
|
|
vslavik/poedit
|
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
|
deps/boost/libs/metaparse/tools/benchmark/char_stat.py
|
python
|
generate_statistics
|
(root)
|
return out
|
Generate the statistics from all files in root (recursively)
|
Generate the statistics from all files in root (recursively)
|
[
"Generate",
"the",
"statistics",
"from",
"all",
"files",
"in",
"root",
"(",
"recursively",
")"
] |
def generate_statistics(root):
"""Generate the statistics from all files in root (recursively)"""
out = dict()
count_characters(root, out)
return out
|
[
"def",
"generate_statistics",
"(",
"root",
")",
":",
"out",
"=",
"dict",
"(",
")",
"count_characters",
"(",
"root",
",",
"out",
")",
"return",
"out"
] |
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/libs/metaparse/tools/benchmark/char_stat.py#L27-L31
|
|
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
tools/grit/grit/grit_runner.py
|
python
|
Options.ReadOptions
|
(self, args)
|
return args
|
Reads options from the start of args and returns the remainder.
|
Reads options from the start of args and returns the remainder.
|
[
"Reads",
"options",
"from",
"the",
"start",
"of",
"args",
"and",
"returns",
"the",
"remainder",
"."
] |
def ReadOptions(self, args):
"""Reads options from the start of args and returns the remainder."""
(opts, args) = getopt.getopt(args, 'g:qdvxc:i:p:h:', ('psyco',))
for (key, val) in opts:
if key == '-d': self.disconnected = True
elif key == '-c': self.client = val
elif key == '-h': self.hash = val
elif key == '-i': self.input = val
elif key == '-v':
self.verbose = True
util.verbose = True
elif key == '-x':
self.verbose = True
util.verbose = True
self.extra_verbose = True
util.extra_verbose = True
elif key == '-p': self.profile_dest = val
elif key == '--psyco': self.psyco = True
if not self.input:
if 'GRIT_INPUT' in os.environ:
self.input = os.environ['GRIT_INPUT']
else:
self.input = 'resource.grd'
return args
|
[
"def",
"ReadOptions",
"(",
"self",
",",
"args",
")",
":",
"(",
"opts",
",",
"args",
")",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"'g:qdvxc:i:p:h:'",
",",
"(",
"'psyco'",
",",
")",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"opts",
":",
"if",
"key",
"==",
"'-d'",
":",
"self",
".",
"disconnected",
"=",
"True",
"elif",
"key",
"==",
"'-c'",
":",
"self",
".",
"client",
"=",
"val",
"elif",
"key",
"==",
"'-h'",
":",
"self",
".",
"hash",
"=",
"val",
"elif",
"key",
"==",
"'-i'",
":",
"self",
".",
"input",
"=",
"val",
"elif",
"key",
"==",
"'-v'",
":",
"self",
".",
"verbose",
"=",
"True",
"util",
".",
"verbose",
"=",
"True",
"elif",
"key",
"==",
"'-x'",
":",
"self",
".",
"verbose",
"=",
"True",
"util",
".",
"verbose",
"=",
"True",
"self",
".",
"extra_verbose",
"=",
"True",
"util",
".",
"extra_verbose",
"=",
"True",
"elif",
"key",
"==",
"'-p'",
":",
"self",
".",
"profile_dest",
"=",
"val",
"elif",
"key",
"==",
"'--psyco'",
":",
"self",
".",
"psyco",
"=",
"True",
"if",
"not",
"self",
".",
"input",
":",
"if",
"'GRIT_INPUT'",
"in",
"os",
".",
"environ",
":",
"self",
".",
"input",
"=",
"os",
".",
"environ",
"[",
"'GRIT_INPUT'",
"]",
"else",
":",
"self",
".",
"input",
"=",
"'resource.grd'",
"return",
"args"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/grit_runner.py#L165-L190
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
wx/lib/agw/aui/aui_utilities.py
|
python
|
GetBaseColour
|
()
|
return base_colour
|
Returns the face shading colour on push buttons/backgrounds,
mimicking as closely as possible the platform UI colours.
|
Returns the face shading colour on push buttons/backgrounds,
mimicking as closely as possible the platform UI colours.
|
[
"Returns",
"the",
"face",
"shading",
"colour",
"on",
"push",
"buttons",
"/",
"backgrounds",
"mimicking",
"as",
"closely",
"as",
"possible",
"the",
"platform",
"UI",
"colours",
"."
] |
def GetBaseColour():
"""
Returns the face shading colour on push buttons/backgrounds,
mimicking as closely as possible the platform UI colours.
"""
if wx.Platform == "__WXMAC__":
if hasattr(wx, 'MacThemeColour'):
base_colour = wx.MacThemeColour(Carbon.Appearance.kThemeBrushToolbarBackground)
else:
brush = wx.Brush(wx.BLACK)
brush.MacSetTheme(Carbon.Appearance.kThemeBrushToolbarBackground)
base_colour = brush.GetColour()
else:
base_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)
# the base_colour is too pale to use as our base colour,
# so darken it a bit
if ((255-base_colour.Red()) +
(255-base_colour.Green()) +
(255-base_colour.Blue()) < 60):
base_colour = StepColour(base_colour, 92)
return base_colour
|
[
"def",
"GetBaseColour",
"(",
")",
":",
"if",
"wx",
".",
"Platform",
"==",
"\"__WXMAC__\"",
":",
"if",
"hasattr",
"(",
"wx",
",",
"'MacThemeColour'",
")",
":",
"base_colour",
"=",
"wx",
".",
"MacThemeColour",
"(",
"Carbon",
".",
"Appearance",
".",
"kThemeBrushToolbarBackground",
")",
"else",
":",
"brush",
"=",
"wx",
".",
"Brush",
"(",
"wx",
".",
"BLACK",
")",
"brush",
".",
"MacSetTheme",
"(",
"Carbon",
".",
"Appearance",
".",
"kThemeBrushToolbarBackground",
")",
"base_colour",
"=",
"brush",
".",
"GetColour",
"(",
")",
"else",
":",
"base_colour",
"=",
"wx",
".",
"SystemSettings",
".",
"GetColour",
"(",
"wx",
".",
"SYS_COLOUR_3DFACE",
")",
"# the base_colour is too pale to use as our base colour,",
"# so darken it a bit",
"if",
"(",
"(",
"255",
"-",
"base_colour",
".",
"Red",
"(",
")",
")",
"+",
"(",
"255",
"-",
"base_colour",
".",
"Green",
"(",
")",
")",
"+",
"(",
"255",
"-",
"base_colour",
".",
"Blue",
"(",
")",
")",
"<",
"60",
")",
":",
"base_colour",
"=",
"StepColour",
"(",
"base_colour",
",",
"92",
")",
"return",
"base_colour"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/aui_utilities.py#L162-L189
|
|
BlzFans/wke
|
b0fa21158312e40c5fbd84682d643022b6c34a93
|
cygwin/lib/python2.6/mailbox.py
|
python
|
Maildir.__setitem__
|
(self, key, message)
|
Replace the keyed message; raise KeyError if it doesn't exist.
|
Replace the keyed message; raise KeyError if it doesn't exist.
|
[
"Replace",
"the",
"keyed",
"message",
";",
"raise",
"KeyError",
"if",
"it",
"doesn",
"t",
"exist",
"."
] |
def __setitem__(self, key, message):
"""Replace the keyed message; raise KeyError if it doesn't exist."""
old_subpath = self._lookup(key)
temp_key = self.add(message)
temp_subpath = self._lookup(temp_key)
if isinstance(message, MaildirMessage):
# temp's subdir and suffix were specified by message.
dominant_subpath = temp_subpath
else:
# temp's subdir and suffix were defaults from add().
dominant_subpath = old_subpath
subdir = os.path.dirname(dominant_subpath)
if self.colon in dominant_subpath:
suffix = self.colon + dominant_subpath.split(self.colon)[-1]
else:
suffix = ''
self.discard(key)
new_path = os.path.join(self._path, subdir, key + suffix)
os.rename(os.path.join(self._path, temp_subpath), new_path)
if isinstance(message, MaildirMessage):
os.utime(new_path, (os.path.getatime(new_path),
message.get_date()))
|
[
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
":",
"old_subpath",
"=",
"self",
".",
"_lookup",
"(",
"key",
")",
"temp_key",
"=",
"self",
".",
"add",
"(",
"message",
")",
"temp_subpath",
"=",
"self",
".",
"_lookup",
"(",
"temp_key",
")",
"if",
"isinstance",
"(",
"message",
",",
"MaildirMessage",
")",
":",
"# temp's subdir and suffix were specified by message.",
"dominant_subpath",
"=",
"temp_subpath",
"else",
":",
"# temp's subdir and suffix were defaults from add().",
"dominant_subpath",
"=",
"old_subpath",
"subdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dominant_subpath",
")",
"if",
"self",
".",
"colon",
"in",
"dominant_subpath",
":",
"suffix",
"=",
"self",
".",
"colon",
"+",
"dominant_subpath",
".",
"split",
"(",
"self",
".",
"colon",
")",
"[",
"-",
"1",
"]",
"else",
":",
"suffix",
"=",
"''",
"self",
".",
"discard",
"(",
"key",
")",
"new_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"subdir",
",",
"key",
"+",
"suffix",
")",
"os",
".",
"rename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"temp_subpath",
")",
",",
"new_path",
")",
"if",
"isinstance",
"(",
"message",
",",
"MaildirMessage",
")",
":",
"os",
".",
"utime",
"(",
"new_path",
",",
"(",
"os",
".",
"path",
".",
"getatime",
"(",
"new_path",
")",
",",
"message",
".",
"get_date",
"(",
")",
")",
")"
] |
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L290-L311
|
||
y123456yz/reading-and-annotate-mongodb-3.6
|
93280293672ca7586dc24af18132aa61e4ed7fcf
|
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Scanner/__init__.py
|
python
|
Base.__call__
|
(self, node, env, path = ())
|
return nodes
|
This method scans a single object. 'node' is the node
that will be passed to the scanner function, and 'env' is the
environment that will be passed to the scanner function. A list of
direct dependency nodes for the specified node will be returned.
|
This method scans a single object. 'node' is the node
that will be passed to the scanner function, and 'env' is the
environment that will be passed to the scanner function. A list of
direct dependency nodes for the specified node will be returned.
|
[
"This",
"method",
"scans",
"a",
"single",
"object",
".",
"node",
"is",
"the",
"node",
"that",
"will",
"be",
"passed",
"to",
"the",
"scanner",
"function",
"and",
"env",
"is",
"the",
"environment",
"that",
"will",
"be",
"passed",
"to",
"the",
"scanner",
"function",
".",
"A",
"list",
"of",
"direct",
"dependency",
"nodes",
"for",
"the",
"specified",
"node",
"will",
"be",
"returned",
"."
] |
def __call__(self, node, env, path = ()):
"""
This method scans a single object. 'node' is the node
that will be passed to the scanner function, and 'env' is the
environment that will be passed to the scanner function. A list of
direct dependency nodes for the specified node will be returned.
"""
if self.scan_check and not self.scan_check(node, env):
return []
self = self.select(node)
if not self.argument is _null:
list = self.function(node, env, path, self.argument)
else:
list = self.function(node, env, path)
kw = {}
if hasattr(node, 'dir'):
kw['directory'] = node.dir
node_factory = env.get_factory(self.node_factory)
nodes = []
for l in list:
if self.node_class and not isinstance(l, self.node_class):
l = node_factory(l, **kw)
nodes.append(l)
return nodes
|
[
"def",
"__call__",
"(",
"self",
",",
"node",
",",
"env",
",",
"path",
"=",
"(",
")",
")",
":",
"if",
"self",
".",
"scan_check",
"and",
"not",
"self",
".",
"scan_check",
"(",
"node",
",",
"env",
")",
":",
"return",
"[",
"]",
"self",
"=",
"self",
".",
"select",
"(",
"node",
")",
"if",
"not",
"self",
".",
"argument",
"is",
"_null",
":",
"list",
"=",
"self",
".",
"function",
"(",
"node",
",",
"env",
",",
"path",
",",
"self",
".",
"argument",
")",
"else",
":",
"list",
"=",
"self",
".",
"function",
"(",
"node",
",",
"env",
",",
"path",
")",
"kw",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"node",
",",
"'dir'",
")",
":",
"kw",
"[",
"'directory'",
"]",
"=",
"node",
".",
"dir",
"node_factory",
"=",
"env",
".",
"get_factory",
"(",
"self",
".",
"node_factory",
")",
"nodes",
"=",
"[",
"]",
"for",
"l",
"in",
"list",
":",
"if",
"self",
".",
"node_class",
"and",
"not",
"isinstance",
"(",
"l",
",",
"self",
".",
"node_class",
")",
":",
"l",
"=",
"node_factory",
"(",
"l",
",",
"*",
"*",
"kw",
")",
"nodes",
".",
"append",
"(",
"l",
")",
"return",
"nodes"
] |
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Scanner/__init__.py#L196-L222
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.