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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/decoder.py | python | _RaiseInvalidWireType | (buffer, pos, end) | Skip function for unknown wire types. Raises an exception. | Skip function for unknown wire types. Raises an exception. | [
"Skip",
"function",
"for",
"unknown",
"wire",
"types",
".",
"Raises",
"an",
"exception",
"."
] | def _RaiseInvalidWireType(buffer, pos, end):
"""Skip function for unknown wire types. Raises an exception."""
raise _DecodeError('Tag had invalid wire type.') | [
"def",
"_RaiseInvalidWireType",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"raise",
"_DecodeError",
"(",
"'Tag had invalid wire type.'",
")"
] | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/decoder.py#L682-L685 | ||
qt/qt | 0a2f2382541424726168804be2c90b91381608c6 | src/3rdparty/freetype/src/tools/docmaker/content.py | python | ContentProcessor.process_content | ( self, content ) | return self.markups | process a block content and return a list of DocMarkup objects
corresponding to it | process a block content and return a list of DocMarkup objects
corresponding to it | [
"process",
"a",
"block",
"content",
"and",
"return",
"a",
"list",
"of",
"DocMarkup",
"objects",
"corresponding",
"to",
"it"
] | def process_content( self, content ):
"""process a block content and return a list of DocMarkup objects
corresponding to it"""
markup = None
markup_lines = []
first = 1
for line in content:
found = None
for t in re_markup_tags:
m = t.match( line )
if m:
found = string.lower( m.group( 1 ) )
prefix = len( m.group( 0 ) )
line = " " * prefix + line[prefix:] # remove markup from line
break
# is it the start of a new markup section ?
if found:
first = 0
self.add_markup() # add current markup content
self.markup = found
if len( string.strip( line ) ) > 0:
self.markup_lines.append( line )
elif first == 0:
self.markup_lines.append( line )
self.add_markup()
return self.markups | [
"def",
"process_content",
"(",
"self",
",",
"content",
")",
":",
"markup",
"=",
"None",
"markup_lines",
"=",
"[",
"]",
"first",
"=",
"1",
"for",
"line",
"in",
"content",
":",
"found",
"=",
"None",
"for",
"t",
"in",
"re_markup_tags",
":",
"m",
"=",
"t",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"found",
"=",
"string",
".",
"lower",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"prefix",
"=",
"len",
"(",
"m",
".",
"group",
"(",
"0",
")",
")",
"line",
"=",
"\" \"",
"*",
"prefix",
"+",
"line",
"[",
"prefix",
":",
"]",
"# remove markup from line",
"break",
"# is it the start of a new markup section ?",
"if",
"found",
":",
"first",
"=",
"0",
"self",
".",
"add_markup",
"(",
")",
"# add current markup content",
"self",
".",
"markup",
"=",
"found",
"if",
"len",
"(",
"string",
".",
"strip",
"(",
"line",
")",
")",
">",
"0",
":",
"self",
".",
"markup_lines",
".",
"append",
"(",
"line",
")",
"elif",
"first",
"==",
"0",
":",
"self",
".",
"markup_lines",
".",
"append",
"(",
"line",
")",
"self",
".",
"add_markup",
"(",
")",
"return",
"self",
".",
"markups"
] | https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/freetype/src/tools/docmaker/content.py#L389-L418 | |
feelpp/feelpp | 2d547ed701cc5adb01639185b4a8eb47940367c7 | toolboxes/pyfeelpp-toolboxes/feelpp/toolboxes/thermoelectric/__init__.py | python | thermoelectric | (dim=2, orderPotential=1, worldComm=None, keyword="thermo-electric", subprefix="", modelRep=None) | return _thermoelectrics[key](prefix="thermo-electric", keyword=keyword, worldComm=worldComm, subprefix="", modelRep=modelRep) | create a thermoelectric toolbox solver
Keyword arguments:
dim -- the dimension (default: 2)
orderPotential -- the polynomial order for the potential (default: 1)
worldComm -- the parallel communicator for the mesh (default: core.Environment::worldCommPtr()) | create a thermoelectric toolbox solver
Keyword arguments:
dim -- the dimension (default: 2)
orderPotential -- the polynomial order for the potential (default: 1)
worldComm -- the parallel communicator for the mesh (default: core.Environment::worldCommPtr()) | [
"create",
"a",
"thermoelectric",
"toolbox",
"solver",
"Keyword",
"arguments",
":",
"dim",
"--",
"the",
"dimension",
"(",
"default",
":",
"2",
")",
"orderPotential",
"--",
"the",
"polynomial",
"order",
"for",
"the",
"potential",
"(",
"default",
":",
"1",
")",
"worldComm",
"--",
"the",
"parallel",
"communicator",
"for",
"the",
"mesh",
"(",
"default",
":",
"core",
".",
"Environment",
"::",
"worldCommPtr",
"()",
")"
] | def thermoelectric(dim=2, orderPotential=1, worldComm=None, keyword="thermo-electric", subprefix="", modelRep=None):
"""create a thermoelectric toolbox solver
Keyword arguments:
dim -- the dimension (default: 2)
orderPotential -- the polynomial order for the potential (default: 1)
worldComm -- the parallel communicator for the mesh (default: core.Environment::worldCommPtr())
"""
if worldComm is None:
worldComm = feelpp.Environment.worldCommPtr()
key='thermoelectric('+str(dim)+','+str(orderPotential)+')'
if worldComm.isMasterRank():
print(key)
if key not in _thermoelectrics:
raise RuntimeError('Thermoelectric solver '+key+' not existing')
if modelRep is None:
modelRep = ModelBaseRepository()
return _thermoelectrics[key](prefix="thermo-electric", keyword=keyword, worldComm=worldComm, subprefix="", modelRep=modelRep) | [
"def",
"thermoelectric",
"(",
"dim",
"=",
"2",
",",
"orderPotential",
"=",
"1",
",",
"worldComm",
"=",
"None",
",",
"keyword",
"=",
"\"thermo-electric\"",
",",
"subprefix",
"=",
"\"\"",
",",
"modelRep",
"=",
"None",
")",
":",
"if",
"worldComm",
"is",
"None",
":",
"worldComm",
"=",
"feelpp",
".",
"Environment",
".",
"worldCommPtr",
"(",
")",
"key",
"=",
"'thermoelectric('",
"+",
"str",
"(",
"dim",
")",
"+",
"','",
"+",
"str",
"(",
"orderPotential",
")",
"+",
"')'",
"if",
"worldComm",
".",
"isMasterRank",
"(",
")",
":",
"print",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"_thermoelectrics",
":",
"raise",
"RuntimeError",
"(",
"'Thermoelectric solver '",
"+",
"key",
"+",
"' not existing'",
")",
"if",
"modelRep",
"is",
"None",
":",
"modelRep",
"=",
"ModelBaseRepository",
"(",
")",
"return",
"_thermoelectrics",
"[",
"key",
"]",
"(",
"prefix",
"=",
"\"thermo-electric\"",
",",
"keyword",
"=",
"keyword",
",",
"worldComm",
"=",
"worldComm",
",",
"subprefix",
"=",
"\"\"",
",",
"modelRep",
"=",
"modelRep",
")"
] | https://github.com/feelpp/feelpp/blob/2d547ed701cc5adb01639185b4a8eb47940367c7/toolboxes/pyfeelpp-toolboxes/feelpp/toolboxes/thermoelectric/__init__.py#L21-L37 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/ma/extras.py | python | flatnotmasked_contiguous | (a) | return result | Find contiguous unmasked data in a masked array along the given axis.
Parameters
----------
a : narray
The input array.
Returns
-------
slice_list : list
A sorted sequence of `slice` objects (start index, end index).
.. versionchanged:: 1.15.0
Now returns an empty list instead of None for a fully masked array
See Also
--------
flatnotmasked_edges, notmasked_contiguous, notmasked_edges
clump_masked, clump_unmasked
Notes
-----
Only accepts 2-D arrays at most.
Examples
--------
>>> a = np.ma.arange(10)
>>> np.ma.flatnotmasked_contiguous(a)
[slice(0, 10, None)]
>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> a[mask] = np.ma.masked
>>> np.array(a[~a.mask])
array([3, 4, 6, 7, 8])
>>> np.ma.flatnotmasked_contiguous(a)
[slice(3, 5, None), slice(6, 9, None)]
>>> a[:] = np.ma.masked
>>> np.ma.flatnotmasked_contiguous(a)
[] | Find contiguous unmasked data in a masked array along the given axis. | [
"Find",
"contiguous",
"unmasked",
"data",
"in",
"a",
"masked",
"array",
"along",
"the",
"given",
"axis",
"."
] | def flatnotmasked_contiguous(a):
"""
Find contiguous unmasked data in a masked array along the given axis.
Parameters
----------
a : narray
The input array.
Returns
-------
slice_list : list
A sorted sequence of `slice` objects (start index, end index).
.. versionchanged:: 1.15.0
Now returns an empty list instead of None for a fully masked array
See Also
--------
flatnotmasked_edges, notmasked_contiguous, notmasked_edges
clump_masked, clump_unmasked
Notes
-----
Only accepts 2-D arrays at most.
Examples
--------
>>> a = np.ma.arange(10)
>>> np.ma.flatnotmasked_contiguous(a)
[slice(0, 10, None)]
>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> a[mask] = np.ma.masked
>>> np.array(a[~a.mask])
array([3, 4, 6, 7, 8])
>>> np.ma.flatnotmasked_contiguous(a)
[slice(3, 5, None), slice(6, 9, None)]
>>> a[:] = np.ma.masked
>>> np.ma.flatnotmasked_contiguous(a)
[]
"""
m = getmask(a)
if m is nomask:
return [slice(0, a.size)]
i = 0
result = []
for (k, g) in itertools.groupby(m.ravel()):
n = len(list(g))
if not k:
result.append(slice(i, i + n))
i += n
return result | [
"def",
"flatnotmasked_contiguous",
"(",
"a",
")",
":",
"m",
"=",
"getmask",
"(",
"a",
")",
"if",
"m",
"is",
"nomask",
":",
"return",
"[",
"slice",
"(",
"0",
",",
"a",
".",
"size",
")",
"]",
"i",
"=",
"0",
"result",
"=",
"[",
"]",
"for",
"(",
"k",
",",
"g",
")",
"in",
"itertools",
".",
"groupby",
"(",
"m",
".",
"ravel",
"(",
")",
")",
":",
"n",
"=",
"len",
"(",
"list",
"(",
"g",
")",
")",
"if",
"not",
"k",
":",
"result",
".",
"append",
"(",
"slice",
"(",
"i",
",",
"i",
"+",
"n",
")",
")",
"i",
"+=",
"n",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/extras.py#L1630-L1684 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/array_ops.py | python | one_hot | (indices, depth, on_value=None, off_value=None,
axis=None, dtype=None, name=None) | Returns a one-hot tensor.
The locations represented by indices in `indices` take value `on_value`,
while all other locations take value `off_value`.
`on_value` and `off_value` must have matching data types. If `dtype` is also
provided, they must be the same data type as specified by `dtype`.
If `on_value` is not provided, it will default to the value `1` with type
`dtype`
If `off_value` is not provided, it will default to the value `0` with type
`dtype`
If the input `indices` is rank `N`, the output will have rank `N+1`. The
new axis is created at dimension `axis` (default: the new axis is appended
at the end).
If `indices` is a scalar the output shape will be a vector of length `depth`
If `indices` is a vector of length `features`, the output shape will be:
```
features x depth if axis == -1
depth x features if axis == 0
```
If `indices` is a matrix (batch) with shape `[batch, features]`, the output
shape will be:
```
batch x features x depth if axis == -1
batch x depth x features if axis == 1
depth x batch x features if axis == 0
```
If `dtype` is not provided, it will attempt to assume the data type of
`on_value` or `off_value`, if one or both are passed in. If none of
`on_value`, `off_value`, or `dtype` are provided, `dtype` will default to the
value `tf.float32`
Note: If a non-numeric data type output is desired (tf.string, tf.bool, etc.),
both `on_value` and `off_value` _must_ be provided to `one_hot`
Examples
=========
Suppose that
```
indices = [0, 2, -1, 1]
depth = 3
on_value = 5.0
off_value = 0.0
axis = -1
```
Then output is `[4 x 3]`:
```
output =
[5.0 0.0 0.0] // one_hot(0)
[0.0 0.0 5.0] // one_hot(2)
[0.0 0.0 0.0] // one_hot(-1)
[0.0 5.0 0.0] // one_hot(1)
```
Suppose that
```
indices = [[0, 2], [1, -1]]
depth = 3
on_value = 1.0
off_value = 0.0
axis = -1
```
Then output is `[2 x 2 x 3]`:
```
output =
[
[1.0, 0.0, 0.0] // one_hot(0)
[0.0, 0.0, 1.0] // one_hot(2)
][
[0.0, 1.0, 0.0] // one_hot(1)
[0.0, 0.0, 0.0] // one_hot(-1)
]
```
Using default values for `on_value` and `off_value`:
```
indices = [0, 1, 2]
depth = 3
```
The output will be
```
output =
[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]
```
Args:
indices: A `Tensor` of indices.
depth: A scalar defining the depth of the one hot dimension.
on_value: A scalar defining the value to fill in output when `indices[j]
= i`. (default: 1)
off_value: A scalar defining the value to fill in output when `indices[j]
!= i`. (default: 0)
axis: The axis to fill (default: -1, a new inner-most axis).
dtype: The data type of the output tensor.
Returns:
output: The one-hot tensor.
Raises:
TypeError: If dtype of either `on_value` or `off_value` don't match `dtype`
TypeError: If dtype of `on_value` and `off_value` don't match one another | Returns a one-hot tensor. | [
"Returns",
"a",
"one",
"-",
"hot",
"tensor",
"."
] | def one_hot(indices, depth, on_value=None, off_value=None,
axis=None, dtype=None, name=None):
"""Returns a one-hot tensor.
The locations represented by indices in `indices` take value `on_value`,
while all other locations take value `off_value`.
`on_value` and `off_value` must have matching data types. If `dtype` is also
provided, they must be the same data type as specified by `dtype`.
If `on_value` is not provided, it will default to the value `1` with type
`dtype`
If `off_value` is not provided, it will default to the value `0` with type
`dtype`
If the input `indices` is rank `N`, the output will have rank `N+1`. The
new axis is created at dimension `axis` (default: the new axis is appended
at the end).
If `indices` is a scalar the output shape will be a vector of length `depth`
If `indices` is a vector of length `features`, the output shape will be:
```
features x depth if axis == -1
depth x features if axis == 0
```
If `indices` is a matrix (batch) with shape `[batch, features]`, the output
shape will be:
```
batch x features x depth if axis == -1
batch x depth x features if axis == 1
depth x batch x features if axis == 0
```
If `dtype` is not provided, it will attempt to assume the data type of
`on_value` or `off_value`, if one or both are passed in. If none of
`on_value`, `off_value`, or `dtype` are provided, `dtype` will default to the
value `tf.float32`
Note: If a non-numeric data type output is desired (tf.string, tf.bool, etc.),
both `on_value` and `off_value` _must_ be provided to `one_hot`
Examples
=========
Suppose that
```
indices = [0, 2, -1, 1]
depth = 3
on_value = 5.0
off_value = 0.0
axis = -1
```
Then output is `[4 x 3]`:
```
output =
[5.0 0.0 0.0] // one_hot(0)
[0.0 0.0 5.0] // one_hot(2)
[0.0 0.0 0.0] // one_hot(-1)
[0.0 5.0 0.0] // one_hot(1)
```
Suppose that
```
indices = [[0, 2], [1, -1]]
depth = 3
on_value = 1.0
off_value = 0.0
axis = -1
```
Then output is `[2 x 2 x 3]`:
```
output =
[
[1.0, 0.0, 0.0] // one_hot(0)
[0.0, 0.0, 1.0] // one_hot(2)
][
[0.0, 1.0, 0.0] // one_hot(1)
[0.0, 0.0, 0.0] // one_hot(-1)
]
```
Using default values for `on_value` and `off_value`:
```
indices = [0, 1, 2]
depth = 3
```
The output will be
```
output =
[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]
```
Args:
indices: A `Tensor` of indices.
depth: A scalar defining the depth of the one hot dimension.
on_value: A scalar defining the value to fill in output when `indices[j]
= i`. (default: 1)
off_value: A scalar defining the value to fill in output when `indices[j]
!= i`. (default: 0)
axis: The axis to fill (default: -1, a new inner-most axis).
dtype: The data type of the output tensor.
Returns:
output: The one-hot tensor.
Raises:
TypeError: If dtype of either `on_value` or `off_value` don't match `dtype`
TypeError: If dtype of `on_value` and `off_value` don't match one another
"""
with ops.op_scope([indices, depth, on_value, off_value,
axis, dtype], name, "one_hot") as name:
on_exists = on_value is not None
off_exists = off_value is not None
on_dtype = ops.convert_to_tensor(on_value).dtype.base_dtype if on_exists \
else None
off_dtype = ops.convert_to_tensor(off_value).dtype.base_dtype if off_exists\
else None
if on_exists or off_exists:
if dtype is not None:
# Ensure provided on_value and/or off_value match dtype
if (on_exists and on_dtype != dtype):
raise TypeError("dtype {0} of on_value does not match " \
"dtype parameter {1}".format(on_dtype, dtype))
if (off_exists and off_dtype != dtype):
raise TypeError("dtype {0} of off_value does not match " \
"dtype parameter {1}".format(off_dtype, dtype))
else:
# dtype not provided: automatically assign it
dtype = on_dtype if on_exists else off_dtype
elif dtype is None:
# None of on_value, off_value, or dtype provided. Default dtype to float32
dtype = dtypes.float32
if not on_exists:
# on_value not provided: assign to value 1 of type dtype
on_value = ops.convert_to_tensor(1, dtype, name="on_value")
on_dtype = dtype
if not off_exists:
# off_value not provided: assign to value 0 of type dtype
off_value = ops.convert_to_tensor(0, dtype, name="off_value")
off_dtype = dtype
if on_dtype != off_dtype:
raise TypeError("dtype {0} of on_value does not match " \
"dtype {1} of off_value".format(on_dtype, off_dtype))
return gen_array_ops._one_hot(indices, depth, on_value, off_value, axis,
name) | [
"def",
"one_hot",
"(",
"indices",
",",
"depth",
",",
"on_value",
"=",
"None",
",",
"off_value",
"=",
"None",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"indices",
",",
"depth",
",",
"on_value",
",",
"off_value",
",",
"axis",
",",
"dtype",
"]",
",",
"name",
",",
"\"one_hot\"",
")",
"as",
"name",
":",
"on_exists",
"=",
"on_value",
"is",
"not",
"None",
"off_exists",
"=",
"off_value",
"is",
"not",
"None",
"on_dtype",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"on_value",
")",
".",
"dtype",
".",
"base_dtype",
"if",
"on_exists",
"else",
"None",
"off_dtype",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"off_value",
")",
".",
"dtype",
".",
"base_dtype",
"if",
"off_exists",
"else",
"None",
"if",
"on_exists",
"or",
"off_exists",
":",
"if",
"dtype",
"is",
"not",
"None",
":",
"# Ensure provided on_value and/or off_value match dtype",
"if",
"(",
"on_exists",
"and",
"on_dtype",
"!=",
"dtype",
")",
":",
"raise",
"TypeError",
"(",
"\"dtype {0} of on_value does not match \"",
"\"dtype parameter {1}\"",
".",
"format",
"(",
"on_dtype",
",",
"dtype",
")",
")",
"if",
"(",
"off_exists",
"and",
"off_dtype",
"!=",
"dtype",
")",
":",
"raise",
"TypeError",
"(",
"\"dtype {0} of off_value does not match \"",
"\"dtype parameter {1}\"",
".",
"format",
"(",
"off_dtype",
",",
"dtype",
")",
")",
"else",
":",
"# dtype not provided: automatically assign it",
"dtype",
"=",
"on_dtype",
"if",
"on_exists",
"else",
"off_dtype",
"elif",
"dtype",
"is",
"None",
":",
"# None of on_value, off_value, or dtype provided. Default dtype to float32",
"dtype",
"=",
"dtypes",
".",
"float32",
"if",
"not",
"on_exists",
":",
"# on_value not provided: assign to value 1 of type dtype",
"on_value",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"1",
",",
"dtype",
",",
"name",
"=",
"\"on_value\"",
")",
"on_dtype",
"=",
"dtype",
"if",
"not",
"off_exists",
":",
"# off_value not provided: assign to value 0 of type dtype",
"off_value",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"0",
",",
"dtype",
",",
"name",
"=",
"\"off_value\"",
")",
"off_dtype",
"=",
"dtype",
"if",
"on_dtype",
"!=",
"off_dtype",
":",
"raise",
"TypeError",
"(",
"\"dtype {0} of on_value does not match \"",
"\"dtype {1} of off_value\"",
".",
"format",
"(",
"on_dtype",
",",
"off_dtype",
")",
")",
"return",
"gen_array_ops",
".",
"_one_hot",
"(",
"indices",
",",
"depth",
",",
"on_value",
",",
"off_value",
",",
"axis",
",",
"name",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L2554-L2717 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/concurrent/futures/_base.py | python | _yield_finished_futures | (fs, waiter, ref_collect) | Iterate on the list *fs*, yielding finished futures one by one in
reverse order.
Before yielding a future, *waiter* is removed from its waiters
and the future is removed from each set in the collection of sets
*ref_collect*.
The aim of this function is to avoid keeping stale references after
the future is yielded and before the iterator resumes. | Iterate on the list *fs*, yielding finished futures one by one in
reverse order.
Before yielding a future, *waiter* is removed from its waiters
and the future is removed from each set in the collection of sets
*ref_collect*. | [
"Iterate",
"on",
"the",
"list",
"*",
"fs",
"*",
"yielding",
"finished",
"futures",
"one",
"by",
"one",
"in",
"reverse",
"order",
".",
"Before",
"yielding",
"a",
"future",
"*",
"waiter",
"*",
"is",
"removed",
"from",
"its",
"waiters",
"and",
"the",
"future",
"is",
"removed",
"from",
"each",
"set",
"in",
"the",
"collection",
"of",
"sets",
"*",
"ref_collect",
"*",
"."
] | def _yield_finished_futures(fs, waiter, ref_collect):
"""
Iterate on the list *fs*, yielding finished futures one by one in
reverse order.
Before yielding a future, *waiter* is removed from its waiters
and the future is removed from each set in the collection of sets
*ref_collect*.
The aim of this function is to avoid keeping stale references after
the future is yielded and before the iterator resumes.
"""
while fs:
f = fs[-1]
for futures_set in ref_collect:
futures_set.remove(f)
with f._condition:
f._waiters.remove(waiter)
del f
# Careful not to keep a reference to the popped value
yield fs.pop() | [
"def",
"_yield_finished_futures",
"(",
"fs",
",",
"waiter",
",",
"ref_collect",
")",
":",
"while",
"fs",
":",
"f",
"=",
"fs",
"[",
"-",
"1",
"]",
"for",
"futures_set",
"in",
"ref_collect",
":",
"futures_set",
".",
"remove",
"(",
"f",
")",
"with",
"f",
".",
"_condition",
":",
"f",
".",
"_waiters",
".",
"remove",
"(",
"waiter",
")",
"del",
"f",
"# Careful not to keep a reference to the popped value",
"yield",
"fs",
".",
"pop",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/concurrent/futures/_base.py#L179-L198 | ||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/text_format.py | python | _Tokenizer.ConsumeByteString | (self) | return "".join(list) | Consumes a byte array value.
Returns:
The array parsed (as a string).
Raises:
ParseError: If a byte array value couldn't be consumed. | Consumes a byte array value. | [
"Consumes",
"a",
"byte",
"array",
"value",
"."
] | def ConsumeByteString(self):
"""Consumes a byte array value.
Returns:
The array parsed (as a string).
Raises:
ParseError: If a byte array value couldn't be consumed.
"""
list = [self._ConsumeSingleByteString()]
while len(self.token) > 0 and self.token[0] in ('\'', '"'):
list.append(self._ConsumeSingleByteString())
return "".join(list) | [
"def",
"ConsumeByteString",
"(",
"self",
")",
":",
"list",
"=",
"[",
"self",
".",
"_ConsumeSingleByteString",
"(",
")",
"]",
"while",
"len",
"(",
"self",
".",
"token",
")",
">",
"0",
"and",
"self",
".",
"token",
"[",
"0",
"]",
"in",
"(",
"'\\''",
",",
"'\"'",
")",
":",
"list",
".",
"append",
"(",
"self",
".",
"_ConsumeSingleByteString",
"(",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"list",
")"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/text_format.py#L506-L518 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/activations.py | python | relu | (x, alpha=0., max_value=None, threshold=0) | return K.relu(x, alpha=alpha, max_value=max_value, threshold=threshold) | Rectified Linear Unit.
With default values, it returns element-wise `max(x, 0)`.
Otherwise, it follows:
`f(x) = max_value` for `x >= max_value`,
`f(x) = x` for `threshold <= x < max_value`,
`f(x) = alpha * (x - threshold)` otherwise.
Arguments:
x: A tensor or variable.
alpha: A scalar, slope of negative section (default=`0.`).
max_value: float. Saturation threshold.
threshold: float. Threshold value for thresholded activation.
Returns:
A tensor. | Rectified Linear Unit. | [
"Rectified",
"Linear",
"Unit",
"."
] | def relu(x, alpha=0., max_value=None, threshold=0):
"""Rectified Linear Unit.
With default values, it returns element-wise `max(x, 0)`.
Otherwise, it follows:
`f(x) = max_value` for `x >= max_value`,
`f(x) = x` for `threshold <= x < max_value`,
`f(x) = alpha * (x - threshold)` otherwise.
Arguments:
x: A tensor or variable.
alpha: A scalar, slope of negative section (default=`0.`).
max_value: float. Saturation threshold.
threshold: float. Threshold value for thresholded activation.
Returns:
A tensor.
"""
return K.relu(x, alpha=alpha, max_value=max_value, threshold=threshold) | [
"def",
"relu",
"(",
"x",
",",
"alpha",
"=",
"0.",
",",
"max_value",
"=",
"None",
",",
"threshold",
"=",
"0",
")",
":",
"return",
"K",
".",
"relu",
"(",
"x",
",",
"alpha",
"=",
"alpha",
",",
"max_value",
"=",
"max_value",
",",
"threshold",
"=",
"threshold",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/activations.py#L179-L198 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | Pen.IsNonTransparent | (*args, **kwargs) | return _gdi_.Pen_IsNonTransparent(*args, **kwargs) | IsNonTransparent(self) -> bool | IsNonTransparent(self) -> bool | [
"IsNonTransparent",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsNonTransparent(*args, **kwargs):
"""IsNonTransparent(self) -> bool"""
return _gdi_.Pen_IsNonTransparent(*args, **kwargs) | [
"def",
"IsNonTransparent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Pen_IsNonTransparent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L472-L474 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/jinja2/environment.py | python | Environment.parse | (self, source, name=None, filename=None) | Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja2 extensions <writing-extensions>`
this gives you a good overview of the node tree generated. | Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates. | [
"Parse",
"the",
"sourcecode",
"and",
"return",
"the",
"abstract",
"syntax",
"tree",
".",
"This",
"tree",
"of",
"nodes",
"is",
"used",
"by",
"the",
"compiler",
"to",
"convert",
"the",
"template",
"into",
"executable",
"source",
"-",
"or",
"bytecode",
".",
"This",
"is",
"useful",
"for",
"debugging",
"or",
"to",
"extract",
"information",
"from",
"templates",
"."
] | def parse(self, source, name=None, filename=None):
"""Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja2 extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
"""
try:
return self._parse(source, name, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source) | [
"def",
"parse",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_parse",
"(",
"source",
",",
"name",
",",
"filename",
")",
"except",
"TemplateSyntaxError",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"self",
".",
"handle_exception",
"(",
"exc_info",
",",
"source_hint",
"=",
"source",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/environment.py#L442-L455 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/artmanager.py | python | ArtManager.GetTransparency | (self) | return self._transparency | Returns the alpha channel value for transparent windows.
:return: An integer representing the alpha channel value. | Returns the alpha channel value for transparent windows. | [
"Returns",
"the",
"alpha",
"channel",
"value",
"for",
"transparent",
"windows",
"."
] | def GetTransparency(self):
"""
Returns the alpha channel value for transparent windows.
:return: An integer representing the alpha channel value.
"""
return self._transparency | [
"def",
"GetTransparency",
"(",
"self",
")",
":",
"return",
"self",
".",
"_transparency"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/artmanager.py#L676-L683 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/framework/dtypes.py | python | DType.__init__ | (self, type_enum) | Creates a new `DataType`.
NOTE(mrry): In normal circumstances, you should not need to
construct a `DataType` object directly. Instead, use the
`tf.as_dtype()` function.
Args:
type_enum: A `types_pb2.DataType` enum value.
Raises:
TypeError: If `type_enum` is not a value `types_pb2.DataType`. | Creates a new `DataType`. | [
"Creates",
"a",
"new",
"DataType",
"."
] | def __init__(self, type_enum):
"""Creates a new `DataType`.
NOTE(mrry): In normal circumstances, you should not need to
construct a `DataType` object directly. Instead, use the
`tf.as_dtype()` function.
Args:
type_enum: A `types_pb2.DataType` enum value.
Raises:
TypeError: If `type_enum` is not a value `types_pb2.DataType`.
"""
# TODO(mrry): Make the necessary changes (using __new__) to ensure
# that calling this returns one of the interned values.
type_enum = int(type_enum)
if (type_enum not in types_pb2.DataType.values()
or type_enum == types_pb2.DT_INVALID):
raise TypeError(
"type_enum is not a valid types_pb2.DataType: %s" % type_enum)
self._type_enum = type_enum | [
"def",
"__init__",
"(",
"self",
",",
"type_enum",
")",
":",
"# TODO(mrry): Make the necessary changes (using __new__) to ensure",
"# that calling this returns one of the interned values.",
"type_enum",
"=",
"int",
"(",
"type_enum",
")",
"if",
"(",
"type_enum",
"not",
"in",
"types_pb2",
".",
"DataType",
".",
"values",
"(",
")",
"or",
"type_enum",
"==",
"types_pb2",
".",
"DT_INVALID",
")",
":",
"raise",
"TypeError",
"(",
"\"type_enum is not a valid types_pb2.DataType: %s\"",
"%",
"type_enum",
")",
"self",
".",
"_type_enum",
"=",
"type_enum"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/dtypes.py#L73-L94 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ToolBarToolBase.Attach | (*args, **kwargs) | return _controls_.ToolBarToolBase_Attach(*args, **kwargs) | Attach(self, ToolBarBase tbar) | Attach(self, ToolBarBase tbar) | [
"Attach",
"(",
"self",
"ToolBarBase",
"tbar",
")"
] | def Attach(*args, **kwargs):
"""Attach(self, ToolBarBase tbar)"""
return _controls_.ToolBarToolBase_Attach(*args, **kwargs) | [
"def",
"Attach",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarToolBase_Attach",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3549-L3551 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | _find_adapter | (registry, ob) | Return an adapter factory for `ob` from `registry` | Return an adapter factory for `ob` from `registry` | [
"Return",
"an",
"adapter",
"factory",
"for",
"ob",
"from",
"registry"
] | def _find_adapter(registry, ob):
"""Return an adapter factory for `ob` from `registry`"""
types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
for t in types:
if t in registry:
return registry[t] | [
"def",
"_find_adapter",
"(",
"registry",
",",
"ob",
")",
":",
"types",
"=",
"_always_object",
"(",
"inspect",
".",
"getmro",
"(",
"getattr",
"(",
"ob",
",",
"'__class__'",
",",
"type",
"(",
"ob",
")",
")",
")",
")",
"for",
"t",
"in",
"types",
":",
"if",
"t",
"in",
"registry",
":",
"return",
"registry",
"[",
"t",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L3162-L3167 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBBreakpointName.GetAllowDisable | (self) | return _lldb.SBBreakpointName_GetAllowDisable(self) | GetAllowDisable(SBBreakpointName self) -> bool | GetAllowDisable(SBBreakpointName self) -> bool | [
"GetAllowDisable",
"(",
"SBBreakpointName",
"self",
")",
"-",
">",
"bool"
] | def GetAllowDisable(self):
"""GetAllowDisable(SBBreakpointName self) -> bool"""
return _lldb.SBBreakpointName_GetAllowDisable(self) | [
"def",
"GetAllowDisable",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBBreakpointName_GetAllowDisable",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L2349-L2351 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | Dialog.GetReturnCode | (*args, **kwargs) | return _windows_.Dialog_GetReturnCode(*args, **kwargs) | GetReturnCode(self) -> int | GetReturnCode(self) -> int | [
"GetReturnCode",
"(",
"self",
")",
"-",
">",
"int"
] | def GetReturnCode(*args, **kwargs):
"""GetReturnCode(self) -> int"""
return _windows_.Dialog_GetReturnCode(*args, **kwargs) | [
"def",
"GetReturnCode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"Dialog_GetReturnCode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L749-L751 | |
google/tink | 59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14 | python/tink/prf/_prf_key_templates.py | python | _create_aes_cmac_key_template | (key_size: int) | return key_template | Creates an AES CMAC PRF KeyTemplate, and fills in its values. | Creates an AES CMAC PRF KeyTemplate, and fills in its values. | [
"Creates",
"an",
"AES",
"CMAC",
"PRF",
"KeyTemplate",
"and",
"fills",
"in",
"its",
"values",
"."
] | def _create_aes_cmac_key_template(key_size: int) -> tink_pb2.KeyTemplate:
"""Creates an AES CMAC PRF KeyTemplate, and fills in its values."""
key_format = aes_cmac_prf_pb2.AesCmacPrfKeyFormat()
key_format.key_size = key_size
key_format.version = 0
key_template = tink_pb2.KeyTemplate()
key_template.value = key_format.SerializeToString()
key_template.type_url = _AES_CMAC_PRF_KEY_TYPE_URL
key_template.output_prefix_type = tink_pb2.RAW
return key_template | [
"def",
"_create_aes_cmac_key_template",
"(",
"key_size",
":",
"int",
")",
"->",
"tink_pb2",
".",
"KeyTemplate",
":",
"key_format",
"=",
"aes_cmac_prf_pb2",
".",
"AesCmacPrfKeyFormat",
"(",
")",
"key_format",
".",
"key_size",
"=",
"key_size",
"key_format",
".",
"version",
"=",
"0",
"key_template",
"=",
"tink_pb2",
".",
"KeyTemplate",
"(",
")",
"key_template",
".",
"value",
"=",
"key_format",
".",
"SerializeToString",
"(",
")",
"key_template",
".",
"type_url",
"=",
"_AES_CMAC_PRF_KEY_TYPE_URL",
"key_template",
".",
"output_prefix_type",
"=",
"tink_pb2",
".",
"RAW",
"return",
"key_template"
] | https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/prf/_prf_key_templates.py#L35-L44 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/genericpath.py | python | _splitext | (p, sep, altsep, extsep) | return p, '' | Split the extension from a pathname.
Extension is everything from the last dot to the end, ignoring
leading dots. Returns "(root, ext)"; ext may be empty. | Split the extension from a pathname. | [
"Split",
"the",
"extension",
"from",
"a",
"pathname",
"."
] | def _splitext(p, sep, altsep, extsep):
"""Split the extension from a pathname.
Extension is everything from the last dot to the end, ignoring
leading dots. Returns "(root, ext)"; ext may be empty."""
sepIndex = p.rfind(sep)
if altsep:
altsepIndex = p.rfind(altsep)
sepIndex = max(sepIndex, altsepIndex)
dotIndex = p.rfind(extsep)
if dotIndex > sepIndex:
# skip all leading dots
filenameIndex = sepIndex + 1
while filenameIndex < dotIndex:
if p[filenameIndex] != extsep:
return p[:dotIndex], p[dotIndex:]
filenameIndex += 1
return p, '' | [
"def",
"_splitext",
"(",
"p",
",",
"sep",
",",
"altsep",
",",
"extsep",
")",
":",
"sepIndex",
"=",
"p",
".",
"rfind",
"(",
"sep",
")",
"if",
"altsep",
":",
"altsepIndex",
"=",
"p",
".",
"rfind",
"(",
"altsep",
")",
"sepIndex",
"=",
"max",
"(",
"sepIndex",
",",
"altsepIndex",
")",
"dotIndex",
"=",
"p",
".",
"rfind",
"(",
"extsep",
")",
"if",
"dotIndex",
">",
"sepIndex",
":",
"# skip all leading dots",
"filenameIndex",
"=",
"sepIndex",
"+",
"1",
"while",
"filenameIndex",
"<",
"dotIndex",
":",
"if",
"p",
"[",
"filenameIndex",
"]",
"!=",
"extsep",
":",
"return",
"p",
"[",
":",
"dotIndex",
"]",
",",
"p",
"[",
"dotIndex",
":",
"]",
"filenameIndex",
"+=",
"1",
"return",
"p",
",",
"''"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/genericpath.py#L85-L105 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/resample.py | python | Resampler.__iter__ | (self) | return super().__iter__() | Resampler iterator.
Returns
-------
Generator yielding sequence of (name, subsetted object)
for each group.
See Also
--------
GroupBy.__iter__ | Resampler iterator. | [
"Resampler",
"iterator",
"."
] | def __iter__(self):
"""
Resampler iterator.
Returns
-------
Generator yielding sequence of (name, subsetted object)
for each group.
See Also
--------
GroupBy.__iter__
"""
self._set_binner()
return super().__iter__() | [
"def",
"__iter__",
"(",
"self",
")",
":",
"self",
".",
"_set_binner",
"(",
")",
"return",
"super",
"(",
")",
".",
"__iter__",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/resample.py#L109-L123 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/tools/release/check_clusterfuzz.py | python | APIRequest | (key, **params) | return None | Send a request to the clusterfuzz api.
Returns a json dict of the response. | Send a request to the clusterfuzz api. | [
"Send",
"a",
"request",
"to",
"the",
"clusterfuzz",
"api",
"."
] | def APIRequest(key, **params):
"""Send a request to the clusterfuzz api.
Returns a json dict of the response.
"""
params["api_key"] = key
params = urllib.urlencode(params)
headers = {"Content-type": "application/x-www-form-urlencoded"}
try:
conn = httplib.HTTPSConnection(HOSTNAME)
conn.request("POST", "/_api/", params, headers)
response = conn.getresponse()
# Never leak "data" into public logs.
data = response.read()
except:
raise Exception("ERROR: Connection problem.")
try:
return json.loads(data)
except:
raise Exception("ERROR: Could not read response. Is your key valid?")
return None | [
"def",
"APIRequest",
"(",
"key",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"\"api_key\"",
"]",
"=",
"key",
"params",
"=",
"urllib",
".",
"urlencode",
"(",
"params",
")",
"headers",
"=",
"{",
"\"Content-type\"",
":",
"\"application/x-www-form-urlencoded\"",
"}",
"try",
":",
"conn",
"=",
"httplib",
".",
"HTTPSConnection",
"(",
"HOSTNAME",
")",
"conn",
".",
"request",
"(",
"\"POST\"",
",",
"\"/_api/\"",
",",
"params",
",",
"headers",
")",
"response",
"=",
"conn",
".",
"getresponse",
"(",
")",
"# Never leak \"data\" into public logs.",
"data",
"=",
"response",
".",
"read",
"(",
")",
"except",
":",
"raise",
"Exception",
"(",
"\"ERROR: Connection problem.\"",
")",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"data",
")",
"except",
":",
"raise",
"Exception",
"(",
"\"ERROR: Could not read response. Is your key valid?\"",
")",
"return",
"None"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/release/check_clusterfuzz.py#L161-L188 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | FileDirPickerEvent.SetPath | (*args, **kwargs) | return _controls_.FileDirPickerEvent_SetPath(*args, **kwargs) | SetPath(self, String p) | SetPath(self, String p) | [
"SetPath",
"(",
"self",
"String",
"p",
")"
] | def SetPath(*args, **kwargs):
"""SetPath(self, String p)"""
return _controls_.FileDirPickerEvent_SetPath(*args, **kwargs) | [
"def",
"SetPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"FileDirPickerEvent_SetPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L7132-L7134 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests_toolbelt/auth/handler.py | python | AuthHandler.add_strategy | (self, domain, strategy) | Add a new domain and authentication strategy.
:param str domain: The domain you wish to match against. For example:
``'https://api.github.com'``
:param str strategy: The authentication strategy you wish to use for
that domain. For example: ``('username', 'password')`` or
``requests.HTTPDigestAuth('username', 'password')``
.. code-block:: python
a = AuthHandler({})
a.add_strategy('https://api.github.com', ('username', 'password')) | Add a new domain and authentication strategy. | [
"Add",
"a",
"new",
"domain",
"and",
"authentication",
"strategy",
"."
] | def add_strategy(self, domain, strategy):
"""Add a new domain and authentication strategy.
:param str domain: The domain you wish to match against. For example:
``'https://api.github.com'``
:param str strategy: The authentication strategy you wish to use for
that domain. For example: ``('username', 'password')`` or
``requests.HTTPDigestAuth('username', 'password')``
.. code-block:: python
a = AuthHandler({})
a.add_strategy('https://api.github.com', ('username', 'password'))
"""
# Turn tuples into Basic Authentication objects
if isinstance(strategy, tuple):
strategy = HTTPBasicAuth(*strategy)
key = self._key_from_url(domain)
self.strategies[key] = strategy | [
"def",
"add_strategy",
"(",
"self",
",",
"domain",
",",
"strategy",
")",
":",
"# Turn tuples into Basic Authentication objects",
"if",
"isinstance",
"(",
"strategy",
",",
"tuple",
")",
":",
"strategy",
"=",
"HTTPBasicAuth",
"(",
"*",
"strategy",
")",
"key",
"=",
"self",
".",
"_key_from_url",
"(",
"domain",
")",
"self",
".",
"strategies",
"[",
"key",
"]",
"=",
"strategy"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests_toolbelt/auth/handler.py#L79-L99 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/internal/encoder.py | python | MapEncoder | (field_descriptor) | return EncodeField | Encoder for extensions of MessageSet.
Maps always have a wire format like this:
message MapEntry {
key_type key = 1;
value_type value = 2;
}
repeated MapEntry map = N; | Encoder for extensions of MessageSet. | [
"Encoder",
"for",
"extensions",
"of",
"MessageSet",
"."
] | def MapEncoder(field_descriptor):
"""Encoder for extensions of MessageSet.
Maps always have a wire format like this:
message MapEntry {
key_type key = 1;
value_type value = 2;
}
repeated MapEntry map = N;
"""
# Can't look at field_descriptor.message_type._concrete_class because it may
# not have been initialized yet.
message_type = field_descriptor.message_type
encode_message = MessageEncoder(field_descriptor.number, False, False)
def EncodeField(write, value, deterministic):
value_keys = sorted(value.keys()) if deterministic else value
for key in value_keys:
entry_msg = message_type._concrete_class(key=key, value=value[key])
encode_message(write, entry_msg, deterministic)
return EncodeField | [
"def",
"MapEncoder",
"(",
"field_descriptor",
")",
":",
"# Can't look at field_descriptor.message_type._concrete_class because it may",
"# not have been initialized yet.",
"message_type",
"=",
"field_descriptor",
".",
"message_type",
"encode_message",
"=",
"MessageEncoder",
"(",
"field_descriptor",
".",
"number",
",",
"False",
",",
"False",
")",
"def",
"EncodeField",
"(",
"write",
",",
"value",
",",
"deterministic",
")",
":",
"value_keys",
"=",
"sorted",
"(",
"value",
".",
"keys",
"(",
")",
")",
"if",
"deterministic",
"else",
"value",
"for",
"key",
"in",
"value_keys",
":",
"entry_msg",
"=",
"message_type",
".",
"_concrete_class",
"(",
"key",
"=",
"key",
",",
"value",
"=",
"value",
"[",
"key",
"]",
")",
"encode_message",
"(",
"write",
",",
"entry_msg",
",",
"deterministic",
")",
"return",
"EncodeField"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/encoder.py#L809-L830 | |
DanielSWolf/rhubarb-lip-sync | 5cface0af3b6e4e58c0b829c51561d784fb9f52f | rhubarb/lib/webrtc-8d2248ff/tools/sslroots/generate_sslroots.py | python | main | () | The main entrypoint. | The main entrypoint. | [
"The",
"main",
"entrypoint",
"."
] | def main():
"""The main entrypoint."""
parser = OptionParser('usage %prog FILE')
parser.add_option('-v', '--verbose', dest='verbose', action='store_true')
parser.add_option('-f', '--full_cert', dest='full_cert', action='store_true')
options, args = parser.parse_args()
if len(args) < 1:
parser.error('No crt file specified.')
return
root_dir = _SplitCrt(args[0], options)
_GenCFiles(root_dir, options)
_Cleanup(root_dir) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"'usage %prog FILE'",
")",
"parser",
".",
"add_option",
"(",
"'-v'",
",",
"'--verbose'",
",",
"dest",
"=",
"'verbose'",
",",
"action",
"=",
"'store_true'",
")",
"parser",
".",
"add_option",
"(",
"'-f'",
",",
"'--full_cert'",
",",
"dest",
"=",
"'full_cert'",
",",
"action",
"=",
"'store_true'",
")",
"options",
",",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"parser",
".",
"error",
"(",
"'No crt file specified.'",
")",
"return",
"root_dir",
"=",
"_SplitCrt",
"(",
"args",
"[",
"0",
"]",
",",
"options",
")",
"_GenCFiles",
"(",
"root_dir",
",",
"options",
")",
"_Cleanup",
"(",
"root_dir",
")"
] | https://github.com/DanielSWolf/rhubarb-lip-sync/blob/5cface0af3b6e4e58c0b829c51561d784fb9f52f/rhubarb/lib/webrtc-8d2248ff/tools/sslroots/generate_sslroots.py#L43-L54 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py | python | Cursor.is_const_method | (self) | return conf.lib.clang_CXXMethod_isConst(self) | Returns True if the cursor refers to a C++ member function or member
function template that is declared 'const'. | Returns True if the cursor refers to a C++ member function or member
function template that is declared 'const'. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"member",
"function",
"or",
"member",
"function",
"template",
"that",
"is",
"declared",
"const",
"."
] | def is_const_method(self):
"""Returns True if the cursor refers to a C++ member function or member
function template that is declared 'const'.
"""
return conf.lib.clang_CXXMethod_isConst(self) | [
"def",
"is_const_method",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXMethod_isConst",
"(",
"self",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py#L1444-L1448 | |
cmu-db/bustub | fe1b9e984bd2967997b52df872c873d80f71cf7d | build_support/cpplint.py | python | CheckCStyleCast | (filename, clean_lines, linenum, cast_type, pattern, error) | return True | Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise. | Checks for a C-style cast by looking for the pattern. | [
"Checks",
"for",
"a",
"C",
"-",
"style",
"cast",
"by",
"looking",
"for",
"the",
"pattern",
"."
] | def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
line = clean_lines.elided[linenum]
match = Search(pattern, line)
if not match:
return False
# Exclude lines with keywords that tend to look like casts
context = line[0:match.start(1) - 1]
if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
return False
# Try expanding current context to see if we one level of
# parentheses inside a macro.
if linenum > 0:
for i in xrange(linenum - 1, max(0, linenum - 5), -1):
context = clean_lines.elided[i] + context
if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
return False
# operator++(int) and operator--(int)
if context.endswith(' operator++') or context.endswith(' operator--'):
return False
# A single unnamed argument for a function tends to look like old style cast.
# If we see those, don't issue warnings for deprecated casts.
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
remainder):
return False
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True | [
"def",
"CheckCStyleCast",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"cast_type",
",",
"pattern",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"not",
"match",
":",
"return",
"False",
"# Exclude lines with keywords that tend to look like casts",
"context",
"=",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
"if",
"Match",
"(",
"r'.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$'",
",",
"context",
")",
":",
"return",
"False",
"# Try expanding current context to see if we one level of",
"# parentheses inside a macro.",
"if",
"linenum",
">",
"0",
":",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
"-",
"1",
",",
"max",
"(",
"0",
",",
"linenum",
"-",
"5",
")",
",",
"-",
"1",
")",
":",
"context",
"=",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
"+",
"context",
"if",
"Match",
"(",
"r'.*\\b[_A-Z][_A-Z0-9]*\\s*\\((?:\\([^()]*\\)|[^()])*$'",
",",
"context",
")",
":",
"return",
"False",
"# operator++(int) and operator--(int)",
"if",
"context",
".",
"endswith",
"(",
"' operator++'",
")",
"or",
"context",
".",
"endswith",
"(",
"' operator--'",
")",
":",
"return",
"False",
"# A single unnamed argument for a function tends to look like old style cast.",
"# If we see those, don't issue warnings for deprecated casts.",
"remainder",
"=",
"line",
"[",
"match",
".",
"end",
"(",
"0",
")",
":",
"]",
"if",
"Match",
"(",
"r'^\\s*(?:;|const\\b|throw\\b|final\\b|override\\b|[=>{),]|->)'",
",",
"remainder",
")",
":",
"return",
"False",
"# At this point, all that should be left is actual casts.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/casting'",
",",
"4",
",",
"'Using C-style cast. Use %s<%s>(...) instead'",
"%",
"(",
"cast_type",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"return",
"True"
] | https://github.com/cmu-db/bustub/blob/fe1b9e984bd2967997b52df872c873d80f71cf7d/build_support/cpplint.py#L5542-L5592 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/find-first-palindromic-string-in-the-array.py | python | Solution2.firstPalindrome | (self, words) | return next((x for x in words if x == x[::-1]), "") | :type words: List[str]
:rtype: str | :type words: List[str]
:rtype: str | [
":",
"type",
"words",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"str"
] | def firstPalindrome(self, words):
"""
:type words: List[str]
:rtype: str
"""
return next((x for x in words if x == x[::-1]), "") | [
"def",
"firstPalindrome",
"(",
"self",
",",
"words",
")",
":",
"return",
"next",
"(",
"(",
"x",
"for",
"x",
"in",
"words",
"if",
"x",
"==",
"x",
"[",
":",
":",
"-",
"1",
"]",
")",
",",
"\"\"",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-first-palindromic-string-in-the-array.py#L28-L33 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/AutoCompleteWindow.py | python | AutoCompleteWindow._complete_string | (self, s) | return first_comp[:i] | Assuming that s is the prefix of a string in self.completions,
return the longest string which is a prefix of all the strings which
s is a prefix of them. If s is not a prefix of a string, return s. | Assuming that s is the prefix of a string in self.completions,
return the longest string which is a prefix of all the strings which
s is a prefix of them. If s is not a prefix of a string, return s. | [
"Assuming",
"that",
"s",
"is",
"the",
"prefix",
"of",
"a",
"string",
"in",
"self",
".",
"completions",
"return",
"the",
"longest",
"string",
"which",
"is",
"a",
"prefix",
"of",
"all",
"the",
"strings",
"which",
"s",
"is",
"a",
"prefix",
"of",
"them",
".",
"If",
"s",
"is",
"not",
"a",
"prefix",
"of",
"a",
"string",
"return",
"s",
"."
] | def _complete_string(self, s):
"""Assuming that s is the prefix of a string in self.completions,
return the longest string which is a prefix of all the strings which
s is a prefix of them. If s is not a prefix of a string, return s."""
first = self._binary_search(s)
if self.completions[first][:len(s)] != s:
# There is not even one completion which s is a prefix of.
return s
# Find the end of the range of completions where s is a prefix of.
i = first + 1
j = len(self.completions)
while j > i:
m = (i + j) // 2
if self.completions[m][:len(s)] != s:
j = m
else:
i = m + 1
last = i-1
if first == last: # only one possible completion
return self.completions[first]
# We should return the maximum prefix of first and last
first_comp = self.completions[first]
last_comp = self.completions[last]
min_len = min(len(first_comp), len(last_comp))
i = len(s)
while i < min_len and first_comp[i] == last_comp[i]:
i += 1
return first_comp[:i] | [
"def",
"_complete_string",
"(",
"self",
",",
"s",
")",
":",
"first",
"=",
"self",
".",
"_binary_search",
"(",
"s",
")",
"if",
"self",
".",
"completions",
"[",
"first",
"]",
"[",
":",
"len",
"(",
"s",
")",
"]",
"!=",
"s",
":",
"# There is not even one completion which s is a prefix of.",
"return",
"s",
"# Find the end of the range of completions where s is a prefix of.",
"i",
"=",
"first",
"+",
"1",
"j",
"=",
"len",
"(",
"self",
".",
"completions",
")",
"while",
"j",
">",
"i",
":",
"m",
"=",
"(",
"i",
"+",
"j",
")",
"//",
"2",
"if",
"self",
".",
"completions",
"[",
"m",
"]",
"[",
":",
"len",
"(",
"s",
")",
"]",
"!=",
"s",
":",
"j",
"=",
"m",
"else",
":",
"i",
"=",
"m",
"+",
"1",
"last",
"=",
"i",
"-",
"1",
"if",
"first",
"==",
"last",
":",
"# only one possible completion",
"return",
"self",
".",
"completions",
"[",
"first",
"]",
"# We should return the maximum prefix of first and last",
"first_comp",
"=",
"self",
".",
"completions",
"[",
"first",
"]",
"last_comp",
"=",
"self",
".",
"completions",
"[",
"last",
"]",
"min_len",
"=",
"min",
"(",
"len",
"(",
"first_comp",
")",
",",
"len",
"(",
"last_comp",
")",
")",
"i",
"=",
"len",
"(",
"s",
")",
"while",
"i",
"<",
"min_len",
"and",
"first_comp",
"[",
"i",
"]",
"==",
"last_comp",
"[",
"i",
"]",
":",
"i",
"+=",
"1",
"return",
"first_comp",
"[",
":",
"i",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/AutoCompleteWindow.py#L82-L111 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/difflib.py | python | _format_range_unified | (start, stop) | return '{},{}'.format(beginning, length) | Convert range to the "ed" format | Convert range to the "ed" format | [
"Convert",
"range",
"to",
"the",
"ed",
"format"
] | def _format_range_unified(start, stop):
'Convert range to the "ed" format'
# Per the diff spec at http://www.unix.org/single_unix_specification/
beginning = start + 1 # lines start numbering with one
length = stop - start
if length == 1:
return '{}'.format(beginning)
if not length:
beginning -= 1 # empty ranges begin at line just before the range
return '{},{}'.format(beginning, length) | [
"def",
"_format_range_unified",
"(",
"start",
",",
"stop",
")",
":",
"# Per the diff spec at http://www.unix.org/single_unix_specification/",
"beginning",
"=",
"start",
"+",
"1",
"# lines start numbering with one",
"length",
"=",
"stop",
"-",
"start",
"if",
"length",
"==",
"1",
":",
"return",
"'{}'",
".",
"format",
"(",
"beginning",
")",
"if",
"not",
"length",
":",
"beginning",
"-=",
"1",
"# empty ranges begin at line just before the range",
"return",
"'{},{}'",
".",
"format",
"(",
"beginning",
",",
"length",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/difflib.py#L1147-L1156 | |
DanielSWolf/rhubarb-lip-sync | 5cface0af3b6e4e58c0b829c51561d784fb9f52f | rhubarb/lib/webrtc-8d2248ff/webrtc/video/full_stack_plot.py | python | plot_configs_from_args | (args) | return plot_configs | Generates plot configs for given command line arguments. | Generates plot configs for given command line arguments. | [
"Generates",
"plot",
"configs",
"for",
"given",
"command",
"line",
"arguments",
"."
] | def plot_configs_from_args(args):
"""Generates plot configs for given command line arguments."""
# The way it works:
# First we detect separators -n/--next and split arguments into groups, one
# for each plot. For each group, we partially parse it with
# argparse.ArgumentParser, modified to remember the order of arguments.
# Then we traverse the argument list and fill the PlotConfig.
args = itertools.groupby(args, lambda x: x in ["-n", "--next"])
args = list(list(group) for match, group in args if not match)
parser = get_parser()
plot_configs = []
for index, raw_args in enumerate(args):
graph_args = parser.parse_args(raw_args).ordered_args
plot_configs.append(_plot_config_from_args(graph_args, index))
return plot_configs | [
"def",
"plot_configs_from_args",
"(",
"args",
")",
":",
"# The way it works:",
"# First we detect separators -n/--next and split arguments into groups, one",
"# for each plot. For each group, we partially parse it with",
"# argparse.ArgumentParser, modified to remember the order of arguments.",
"# Then we traverse the argument list and fill the PlotConfig.",
"args",
"=",
"itertools",
".",
"groupby",
"(",
"args",
",",
"lambda",
"x",
":",
"x",
"in",
"[",
"\"-n\"",
",",
"\"--next\"",
"]",
")",
"args",
"=",
"list",
"(",
"list",
"(",
"group",
")",
"for",
"match",
",",
"group",
"in",
"args",
"if",
"not",
"match",
")",
"parser",
"=",
"get_parser",
"(",
")",
"plot_configs",
"=",
"[",
"]",
"for",
"index",
",",
"raw_args",
"in",
"enumerate",
"(",
"args",
")",
":",
"graph_args",
"=",
"parser",
".",
"parse_args",
"(",
"raw_args",
")",
".",
"ordered_args",
"plot_configs",
".",
"append",
"(",
"_plot_config_from_args",
"(",
"graph_args",
",",
"index",
")",
")",
"return",
"plot_configs"
] | https://github.com/DanielSWolf/rhubarb-lip-sync/blob/5cface0af3b6e4e58c0b829c51561d784fb9f52f/rhubarb/lib/webrtc-8d2248ff/webrtc/video/full_stack_plot.py#L381-L396 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/multiprocessing/pool.py | python | Pool.map | (self, func, iterable, chunksize=None) | return self.map_async(func, iterable, chunksize).get() | Equivalent of `map()` builtin | Equivalent of `map()` builtin | [
"Equivalent",
"of",
"map",
"()",
"builtin"
] | def map(self, func, iterable, chunksize=None):
'''
Equivalent of `map()` builtin
'''
assert self._state == RUN
return self.map_async(func, iterable, chunksize).get() | [
"def",
"map",
"(",
"self",
",",
"func",
",",
"iterable",
",",
"chunksize",
"=",
"None",
")",
":",
"assert",
"self",
".",
"_state",
"==",
"RUN",
"return",
"self",
".",
"map_async",
"(",
"func",
",",
"iterable",
",",
"chunksize",
")",
".",
"get",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/multiprocessing/pool.py#L248-L253 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/threading.py | python | Barrier.parties | (self) | return self._parties | Return the number of threads required to trip the barrier. | Return the number of threads required to trip the barrier. | [
"Return",
"the",
"number",
"of",
"threads",
"required",
"to",
"trip",
"the",
"barrier",
"."
] | def parties(self):
"""Return the number of threads required to trip the barrier."""
return self._parties | [
"def",
"parties",
"(",
"self",
")",
":",
"return",
"self",
".",
"_parties"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/threading.py#L702-L704 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/legendre.py | python | legint | (c, m=1, k=[], lbnd=0, scl=1, axis=0) | return c | Integrate a Legendre series.
Returns the Legendre series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients from low to high degree along each axis, e.g., [1,2,3]
represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]]
represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) +
2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
Parameters
----------
c : array_like
Array of Legendre series coefficients. If c is multidimensional the
different axis correspond to different variables with the degree in
each axis given by the corresponding index.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at
``lbnd`` is the first value in the list, the value of the second
integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
default), all constants are set to zero. If ``m == 1``, a single
scalar can be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
Legendre series coefficient array of the integral.
Raises
------
ValueError
If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
``np.ndim(scl) != 0``.
See Also
--------
legder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a` - perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "reprojected" onto the C-series basis set. Thus, typically,
the result of this function is "unintuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial import legendre as L
>>> c = (1,2,3)
>>> L.legint(c)
array([ 0.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
>>> L.legint(c, 3)
array([ 1.66666667e-02, -1.78571429e-02, 4.76190476e-02, # may vary
-1.73472348e-18, 1.90476190e-02, 9.52380952e-03])
>>> L.legint(c, k=3)
array([ 3.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
>>> L.legint(c, lbnd=-2)
array([ 7.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
>>> L.legint(c, scl=2)
array([ 0.66666667, 0.8 , 1.33333333, 1.2 ]) # may vary | Integrate a Legendre series. | [
"Integrate",
"a",
"Legendre",
"series",
"."
] | def legint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
"""
Integrate a Legendre series.
Returns the Legendre series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients from low to high degree along each axis, e.g., [1,2,3]
represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]]
represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) +
2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
Parameters
----------
c : array_like
Array of Legendre series coefficients. If c is multidimensional the
different axis correspond to different variables with the degree in
each axis given by the corresponding index.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at
``lbnd`` is the first value in the list, the value of the second
integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
default), all constants are set to zero. If ``m == 1``, a single
scalar can be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
Legendre series coefficient array of the integral.
Raises
------
ValueError
If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
``np.ndim(scl) != 0``.
See Also
--------
legder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a` - perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "reprojected" onto the C-series basis set. Thus, typically,
the result of this function is "unintuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial import legendre as L
>>> c = (1,2,3)
>>> L.legint(c)
array([ 0.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
>>> L.legint(c, 3)
array([ 1.66666667e-02, -1.78571429e-02, 4.76190476e-02, # may vary
-1.73472348e-18, 1.90476190e-02, 9.52380952e-03])
>>> L.legint(c, k=3)
array([ 3.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
>>> L.legint(c, lbnd=-2)
array([ 7.33333333, 0.4 , 0.66666667, 0.6 ]) # may vary
>>> L.legint(c, scl=2)
array([ 0.66666667, 0.8 , 1.33333333, 1.2 ]) # may vary
"""
c = np.array(c, ndmin=1, copy=True)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if not np.iterable(k):
k = [k]
cnt = pu._deprecate_as_int(m, "the order of integration")
iaxis = pu._deprecate_as_int(axis, "the axis")
if cnt < 0:
raise ValueError("The order of integration must be non-negative")
if len(k) > cnt:
raise ValueError("Too many integration constants")
if np.ndim(lbnd) != 0:
raise ValueError("lbnd must be a scalar.")
if np.ndim(scl) != 0:
raise ValueError("scl must be a scalar.")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt == 0:
return c
c = np.moveaxis(c, iaxis, 0)
k = list(k) + [0]*(cnt - len(k))
for i in range(cnt):
n = len(c)
c *= scl
if n == 1 and np.all(c[0] == 0):
c[0] += k[i]
else:
tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
tmp[0] = c[0]*0
tmp[1] = c[0]
if n > 1:
tmp[2] = c[1]/3
for j in range(2, n):
t = c[j]/(2*j + 1)
tmp[j + 1] = t
tmp[j - 1] -= t
tmp[0] += k[i] - legval(lbnd, tmp)
c = tmp
c = np.moveaxis(c, 0, iaxis)
return c | [
"def",
"legint",
"(",
"c",
",",
"m",
"=",
"1",
",",
"k",
"=",
"[",
"]",
",",
"lbnd",
"=",
"0",
",",
"scl",
"=",
"1",
",",
"axis",
"=",
"0",
")",
":",
"c",
"=",
"np",
".",
"array",
"(",
"c",
",",
"ndmin",
"=",
"1",
",",
"copy",
"=",
"True",
")",
"if",
"c",
".",
"dtype",
".",
"char",
"in",
"'?bBhHiIlLqQpP'",
":",
"c",
"=",
"c",
".",
"astype",
"(",
"np",
".",
"double",
")",
"if",
"not",
"np",
".",
"iterable",
"(",
"k",
")",
":",
"k",
"=",
"[",
"k",
"]",
"cnt",
"=",
"pu",
".",
"_deprecate_as_int",
"(",
"m",
",",
"\"the order of integration\"",
")",
"iaxis",
"=",
"pu",
".",
"_deprecate_as_int",
"(",
"axis",
",",
"\"the axis\"",
")",
"if",
"cnt",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"The order of integration must be non-negative\"",
")",
"if",
"len",
"(",
"k",
")",
">",
"cnt",
":",
"raise",
"ValueError",
"(",
"\"Too many integration constants\"",
")",
"if",
"np",
".",
"ndim",
"(",
"lbnd",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"lbnd must be a scalar.\"",
")",
"if",
"np",
".",
"ndim",
"(",
"scl",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"scl must be a scalar.\"",
")",
"iaxis",
"=",
"normalize_axis_index",
"(",
"iaxis",
",",
"c",
".",
"ndim",
")",
"if",
"cnt",
"==",
"0",
":",
"return",
"c",
"c",
"=",
"np",
".",
"moveaxis",
"(",
"c",
",",
"iaxis",
",",
"0",
")",
"k",
"=",
"list",
"(",
"k",
")",
"+",
"[",
"0",
"]",
"*",
"(",
"cnt",
"-",
"len",
"(",
"k",
")",
")",
"for",
"i",
"in",
"range",
"(",
"cnt",
")",
":",
"n",
"=",
"len",
"(",
"c",
")",
"c",
"*=",
"scl",
"if",
"n",
"==",
"1",
"and",
"np",
".",
"all",
"(",
"c",
"[",
"0",
"]",
"==",
"0",
")",
":",
"c",
"[",
"0",
"]",
"+=",
"k",
"[",
"i",
"]",
"else",
":",
"tmp",
"=",
"np",
".",
"empty",
"(",
"(",
"n",
"+",
"1",
",",
")",
"+",
"c",
".",
"shape",
"[",
"1",
":",
"]",
",",
"dtype",
"=",
"c",
".",
"dtype",
")",
"tmp",
"[",
"0",
"]",
"=",
"c",
"[",
"0",
"]",
"*",
"0",
"tmp",
"[",
"1",
"]",
"=",
"c",
"[",
"0",
"]",
"if",
"n",
">",
"1",
":",
"tmp",
"[",
"2",
"]",
"=",
"c",
"[",
"1",
"]",
"/",
"3",
"for",
"j",
"in",
"range",
"(",
"2",
",",
"n",
")",
":",
"t",
"=",
"c",
"[",
"j",
"]",
"/",
"(",
"2",
"*",
"j",
"+",
"1",
")",
"tmp",
"[",
"j",
"+",
"1",
"]",
"=",
"t",
"tmp",
"[",
"j",
"-",
"1",
"]",
"-=",
"t",
"tmp",
"[",
"0",
"]",
"+=",
"k",
"[",
"i",
"]",
"-",
"legval",
"(",
"lbnd",
",",
"tmp",
")",
"c",
"=",
"tmp",
"c",
"=",
"np",
".",
"moveaxis",
"(",
"c",
",",
"0",
",",
"iaxis",
")",
"return",
"c"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/legendre.py#L704-L829 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py | python | load_compile_rules_for_host | (conf, waf_host_platform) | return host_function_name | Load host specific compile rules
:param conf: Configuration context
:param waf_host_platform: The current waf host platform
:return: The host function name to call for initialization | Load host specific compile rules | [
"Load",
"host",
"specific",
"compile",
"rules"
] | def load_compile_rules_for_host(conf, waf_host_platform):
"""
Load host specific compile rules
:param conf: Configuration context
:param waf_host_platform: The current waf host platform
:return: The host function name to call for initialization
"""
host_module_file = 'compile_rules_{}_host'.format(waf_host_platform)
try:
conf.load(host_module_file, tooldir=[LMBR_WAF_TOOL_DIR])
except Exception as err:
conf.fatal("[ERROR] Unable to load compile rules module file '{}': {}".format(host_module_file, str(err)))
host_function_name = 'load_{}_host_settings'.format(waf_host_platform)
if not hasattr(conf, host_function_name):
conf.fatal('[ERROR] Required Configuration Function \'{}\' not found in configuration file {}'.format(host_function_name, host_module_file))
return host_function_name | [
"def",
"load_compile_rules_for_host",
"(",
"conf",
",",
"waf_host_platform",
")",
":",
"host_module_file",
"=",
"'compile_rules_{}_host'",
".",
"format",
"(",
"waf_host_platform",
")",
"try",
":",
"conf",
".",
"load",
"(",
"host_module_file",
",",
"tooldir",
"=",
"[",
"LMBR_WAF_TOOL_DIR",
"]",
")",
"except",
"Exception",
"as",
"err",
":",
"conf",
".",
"fatal",
"(",
"\"[ERROR] Unable to load compile rules module file '{}': {}\"",
".",
"format",
"(",
"host_module_file",
",",
"str",
"(",
"err",
")",
")",
")",
"host_function_name",
"=",
"'load_{}_host_settings'",
".",
"format",
"(",
"waf_host_platform",
")",
"if",
"not",
"hasattr",
"(",
"conf",
",",
"host_function_name",
")",
":",
"conf",
".",
"fatal",
"(",
"'[ERROR] Required Configuration Function \\'{}\\' not found in configuration file {}'",
".",
"format",
"(",
"host_function_name",
",",
"host_module_file",
")",
")",
"return",
"host_function_name"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py#L1116-L1134 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | While | (cond, body, loop_vars, parallel_iterations=10, back_prop=True,
swap_memory=False, name=None) | return while_loop(cond=cond, body=body, loop_vars=loop_vars,
parallel_iterations=parallel_iterations,
back_prop=back_prop, swap_memory=swap_memory, name=name) | DEPRECATED: Use `while_loop`. | DEPRECATED: Use `while_loop`. | [
"DEPRECATED",
":",
"Use",
"while_loop",
"."
] | def While(cond, body, loop_vars, parallel_iterations=10, back_prop=True,
swap_memory=False, name=None):
"""DEPRECATED: Use `while_loop`."""
return while_loop(cond=cond, body=body, loop_vars=loop_vars,
parallel_iterations=parallel_iterations,
back_prop=back_prop, swap_memory=swap_memory, name=name) | [
"def",
"While",
"(",
"cond",
",",
"body",
",",
"loop_vars",
",",
"parallel_iterations",
"=",
"10",
",",
"back_prop",
"=",
"True",
",",
"swap_memory",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"return",
"while_loop",
"(",
"cond",
"=",
"cond",
",",
"body",
"=",
"body",
",",
"loop_vars",
"=",
"loop_vars",
",",
"parallel_iterations",
"=",
"parallel_iterations",
",",
"back_prop",
"=",
"back_prop",
",",
"swap_memory",
"=",
"swap_memory",
",",
"name",
"=",
"name",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L1998-L2003 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/dumbmake/dumbmake.py | python | get_components | (path) | return paths | Take a path and return all the components of the path. | Take a path and return all the components of the path. | [
"Take",
"a",
"path",
"and",
"return",
"all",
"the",
"components",
"of",
"the",
"path",
"."
] | def get_components(path):
"""Take a path and return all the components of the path."""
paths = [path]
while True:
parent = dirname(paths[-1])
if parent == "":
break
paths.append(parent)
paths.reverse()
return paths | [
"def",
"get_components",
"(",
"path",
")",
":",
"paths",
"=",
"[",
"path",
"]",
"while",
"True",
":",
"parent",
"=",
"dirname",
"(",
"paths",
"[",
"-",
"1",
"]",
")",
"if",
"parent",
"==",
"\"\"",
":",
"break",
"paths",
".",
"append",
"(",
"parent",
")",
"paths",
".",
"reverse",
"(",
")",
"return",
"paths"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/dumbmake/dumbmake.py#L73-L83 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/bandwidth.py | python | BandwidthRateTracker.record_consumption_rate | (self, amt, time_at_consumption) | Record the consumption rate based off amount and time point
:type amt: int
:param amt: The amount that got consumed
:type time_at_consumption: float
:param time_at_consumption: The time at which the amount was consumed | Record the consumption rate based off amount and time point | [
"Record",
"the",
"consumption",
"rate",
"based",
"off",
"amount",
"and",
"time",
"point"
] | def record_consumption_rate(self, amt, time_at_consumption):
"""Record the consumption rate based off amount and time point
:type amt: int
:param amt: The amount that got consumed
:type time_at_consumption: float
:param time_at_consumption: The time at which the amount was consumed
"""
if self._last_time is None:
self._last_time = time_at_consumption
self._current_rate = 0.0
return
self._current_rate = self._calculate_exponential_moving_average_rate(
amt, time_at_consumption)
self._last_time = time_at_consumption | [
"def",
"record_consumption_rate",
"(",
"self",
",",
"amt",
",",
"time_at_consumption",
")",
":",
"if",
"self",
".",
"_last_time",
"is",
"None",
":",
"self",
".",
"_last_time",
"=",
"time_at_consumption",
"self",
".",
"_current_rate",
"=",
"0.0",
"return",
"self",
".",
"_current_rate",
"=",
"self",
".",
"_calculate_exponential_moving_average_rate",
"(",
"amt",
",",
"time_at_consumption",
")",
"self",
".",
"_last_time",
"=",
"time_at_consumption"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/bandwidth.py#L386-L401 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | DragImage.Move | (*args, **kwargs) | return _controls_.DragImage_Move(*args, **kwargs) | Move(self, Point pt) -> bool | Move(self, Point pt) -> bool | [
"Move",
"(",
"self",
"Point",
"pt",
")",
"-",
">",
"bool"
] | def Move(*args, **kwargs):
"""Move(self, Point pt) -> bool"""
return _controls_.DragImage_Move(*args, **kwargs) | [
"def",
"Move",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"DragImage_Move",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L6368-L6370 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/screen.py | python | screen.__str__ | (self) | return '\n'.join([''.join(c) for c in self.w]) | This returns a printable representation of the screen. The end of
each screen line is terminated by a newline. | This returns a printable representation of the screen. The end of
each screen line is terminated by a newline. | [
"This",
"returns",
"a",
"printable",
"representation",
"of",
"the",
"screen",
".",
"The",
"end",
"of",
"each",
"screen",
"line",
"is",
"terminated",
"by",
"a",
"newline",
"."
] | def __str__(self):
"""This returns a printable representation of the screen. The end of
each screen line is terminated by a newline. """
return '\n'.join([''.join(c) for c in self.w]) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"''",
".",
"join",
"(",
"c",
")",
"for",
"c",
"in",
"self",
".",
"w",
"]",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/screen.py#L62-L66 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/command/sdist.py | python | sdist._remove_os_link | () | In a context, remove and restore os.link if it exists | In a context, remove and restore os.link if it exists | [
"In",
"a",
"context",
"remove",
"and",
"restore",
"os",
".",
"link",
"if",
"it",
"exists"
] | def _remove_os_link():
"""
In a context, remove and restore os.link if it exists
"""
class NoValue:
pass
orig_val = getattr(os, 'link', NoValue)
try:
del os.link
except Exception:
pass
try:
yield
finally:
if orig_val is not NoValue:
setattr(os, 'link', orig_val) | [
"def",
"_remove_os_link",
"(",
")",
":",
"class",
"NoValue",
":",
"pass",
"orig_val",
"=",
"getattr",
"(",
"os",
",",
"'link'",
",",
"NoValue",
")",
"try",
":",
"del",
"os",
".",
"link",
"except",
"Exception",
":",
"pass",
"try",
":",
"yield",
"finally",
":",
"if",
"orig_val",
"is",
"not",
"NoValue",
":",
"setattr",
"(",
"os",
",",
"'link'",
",",
"orig_val",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/command/sdist.py#L84-L101 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge3.py | python | ExodusModel.count_disconnected_blocks | (self, element_block_ids='all') | return block_count | Return the number of disconnected blocks.
A disconnected block is a group of elements which are connected to
each other through one or more nodes. | Return the number of disconnected blocks. | [
"Return",
"the",
"number",
"of",
"disconnected",
"blocks",
"."
] | def count_disconnected_blocks(self, element_block_ids='all'):
"""
Return the number of disconnected blocks.
A disconnected block is a group of elements which are connected to
each other through one or more nodes.
"""
element_block_ids = self._format_element_block_id_list(
element_block_ids, empty_list_okay=False)
nodes = self.get_nodes_in_element_block(element_block_ids)
# for each node, find the lowest index node that it's connected to
master = list(range(len(self.nodes)))
for element_block_id in element_block_ids:
connectivity = self.get_connectivity(element_block_id)
nodes_per_element = self.get_nodes_per_element(element_block_id)
element_count = self.get_element_count(element_block_id)
for i in range(element_count):
local_node = connectivity[i * nodes_per_element:(i + 1) *
nodes_per_element]
# find lowest index master out of these
low = min(local_node)
for x in local_node:
this_low = x
while this_low != master[this_low]:
this_low = master[this_low]
low = min(low, this_low)
# now set the current master to the lowest index found
for x in local_node:
this_low = x
while this_low != master[this_low]:
this_low = master[this_low]
master[this_low] = low
master[this_low] = low
# now make sure master node list is one-deep
for i in nodes:
master[i] = master[master[i]]
# double check that master node list is one-deep
for i in nodes:
assert master[i] == master[master[i]]
# count the number of master nodes
block_count = sum(1 for x in nodes if master[x] == x)
return block_count | [
"def",
"count_disconnected_blocks",
"(",
"self",
",",
"element_block_ids",
"=",
"'all'",
")",
":",
"element_block_ids",
"=",
"self",
".",
"_format_element_block_id_list",
"(",
"element_block_ids",
",",
"empty_list_okay",
"=",
"False",
")",
"nodes",
"=",
"self",
".",
"get_nodes_in_element_block",
"(",
"element_block_ids",
")",
"# for each node, find the lowest index node that it's connected to",
"master",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"nodes",
")",
")",
")",
"for",
"element_block_id",
"in",
"element_block_ids",
":",
"connectivity",
"=",
"self",
".",
"get_connectivity",
"(",
"element_block_id",
")",
"nodes_per_element",
"=",
"self",
".",
"get_nodes_per_element",
"(",
"element_block_id",
")",
"element_count",
"=",
"self",
".",
"get_element_count",
"(",
"element_block_id",
")",
"for",
"i",
"in",
"range",
"(",
"element_count",
")",
":",
"local_node",
"=",
"connectivity",
"[",
"i",
"*",
"nodes_per_element",
":",
"(",
"i",
"+",
"1",
")",
"*",
"nodes_per_element",
"]",
"# find lowest index master out of these",
"low",
"=",
"min",
"(",
"local_node",
")",
"for",
"x",
"in",
"local_node",
":",
"this_low",
"=",
"x",
"while",
"this_low",
"!=",
"master",
"[",
"this_low",
"]",
":",
"this_low",
"=",
"master",
"[",
"this_low",
"]",
"low",
"=",
"min",
"(",
"low",
",",
"this_low",
")",
"# now set the current master to the lowest index found",
"for",
"x",
"in",
"local_node",
":",
"this_low",
"=",
"x",
"while",
"this_low",
"!=",
"master",
"[",
"this_low",
"]",
":",
"this_low",
"=",
"master",
"[",
"this_low",
"]",
"master",
"[",
"this_low",
"]",
"=",
"low",
"master",
"[",
"this_low",
"]",
"=",
"low",
"# now make sure master node list is one-deep",
"for",
"i",
"in",
"nodes",
":",
"master",
"[",
"i",
"]",
"=",
"master",
"[",
"master",
"[",
"i",
"]",
"]",
"# double check that master node list is one-deep",
"for",
"i",
"in",
"nodes",
":",
"assert",
"master",
"[",
"i",
"]",
"==",
"master",
"[",
"master",
"[",
"i",
"]",
"]",
"# count the number of master nodes",
"block_count",
"=",
"sum",
"(",
"1",
"for",
"x",
"in",
"nodes",
"if",
"master",
"[",
"x",
"]",
"==",
"x",
")",
"return",
"block_count"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L8405-L8447 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/so2.py | python | inv | (a) | return -a | The inverse rotation | The inverse rotation | [
"The",
"inverse",
"rotation"
] | def inv(a):
"""The inverse rotation"""
return -a | [
"def",
"inv",
"(",
"a",
")",
":",
"return",
"-",
"a"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/so2.py#L13-L15 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/InputFileEditor.py | python | InputFileEditor.setInputFile | (self, input_file) | return False | The input file has changed.
Input:
input_file[str]: The new input file | The input file has changed.
Input:
input_file[str]: The new input file | [
"The",
"input",
"file",
"has",
"changed",
".",
"Input",
":",
"input_file",
"[",
"str",
"]",
":",
"The",
"new",
"input",
"file"
] | def setInputFile(self, input_file):
"""
The input file has changed.
Input:
input_file[str]: The new input file
"""
self._closeBlockEditor()
if self.tree.app_info.valid():
input_file = os.path.abspath(input_file)
if self.tree.setInputFile(input_file):
self.block_tree.setInputTree(self.tree)
self.inputFileChanged.emit(input_file)
return True
elif input_file:
mooseutils.mooseError("Failed to read input file", dialog=True)
else:
self.tree.input_filename = input_file
return False | [
"def",
"setInputFile",
"(",
"self",
",",
"input_file",
")",
":",
"self",
".",
"_closeBlockEditor",
"(",
")",
"if",
"self",
".",
"tree",
".",
"app_info",
".",
"valid",
"(",
")",
":",
"input_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"input_file",
")",
"if",
"self",
".",
"tree",
".",
"setInputFile",
"(",
"input_file",
")",
":",
"self",
".",
"block_tree",
".",
"setInputTree",
"(",
"self",
".",
"tree",
")",
"self",
".",
"inputFileChanged",
".",
"emit",
"(",
"input_file",
")",
"return",
"True",
"elif",
"input_file",
":",
"mooseutils",
".",
"mooseError",
"(",
"\"Failed to read input file\"",
",",
"dialog",
"=",
"True",
")",
"else",
":",
"self",
".",
"tree",
".",
"input_filename",
"=",
"input_file",
"return",
"False"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/InputFileEditor.py#L137-L155 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/urlhandler/protocol_socket.py | python | Serial.fileno | (self) | return self._socket.fileno() | Get the file handle of the underlying socket for use with select | Get the file handle of the underlying socket for use with select | [
"Get",
"the",
"file",
"handle",
"of",
"the",
"underlying",
"socket",
"for",
"use",
"with",
"select"
] | def fileno(self):
"""Get the file handle of the underlying socket for use with select"""
return self._socket.fileno() | [
"def",
"fileno",
"(",
"self",
")",
":",
"return",
"self",
".",
"_socket",
".",
"fileno",
"(",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/urlhandler/protocol_socket.py#L339-L341 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/ma/core.py | python | append | (a, b, axis=None) | return concatenate([a, b], axis) | Append values to the end of an array.
.. versionadded:: 1.9.0
Parameters
----------
a : array_like
Values are appended to a copy of this array.
b : array_like
These values are appended to a copy of `a`. It must be of the
correct shape (the same shape as `a`, excluding `axis`). If `axis`
is not specified, `b` can be any shape and will be flattened
before use.
axis : int, optional
The axis along which `v` are appended. If `axis` is not given,
both `a` and `b` are flattened before use.
Returns
-------
append : MaskedArray
A copy of `a` with `b` appended to `axis`. Note that `append`
does not occur in-place: a new array is allocated and filled. If
`axis` is None, the result is a flattened array.
See Also
--------
numpy.append : Equivalent function in the top-level NumPy module.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_values([1, 2, 3], 2)
>>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
>>> ma.append(a, b)
masked_array(data=[1, --, 3, 4, 5, 6, --, 8, 9],
mask=[False, True, False, False, False, False, True, False,
False],
fill_value=999999) | Append values to the end of an array. | [
"Append",
"values",
"to",
"the",
"end",
"of",
"an",
"array",
"."
] | def append(a, b, axis=None):
"""Append values to the end of an array.
.. versionadded:: 1.9.0
Parameters
----------
a : array_like
Values are appended to a copy of this array.
b : array_like
These values are appended to a copy of `a`. It must be of the
correct shape (the same shape as `a`, excluding `axis`). If `axis`
is not specified, `b` can be any shape and will be flattened
before use.
axis : int, optional
The axis along which `v` are appended. If `axis` is not given,
both `a` and `b` are flattened before use.
Returns
-------
append : MaskedArray
A copy of `a` with `b` appended to `axis`. Note that `append`
does not occur in-place: a new array is allocated and filled. If
`axis` is None, the result is a flattened array.
See Also
--------
numpy.append : Equivalent function in the top-level NumPy module.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_values([1, 2, 3], 2)
>>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
>>> ma.append(a, b)
masked_array(data=[1, --, 3, 4, 5, 6, --, 8, 9],
mask=[False, True, False, False, False, False, True, False,
False],
fill_value=999999)
"""
return concatenate([a, b], axis) | [
"def",
"append",
"(",
"a",
",",
"b",
",",
"axis",
"=",
"None",
")",
":",
"return",
"concatenate",
"(",
"[",
"a",
",",
"b",
"]",
",",
"axis",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/core.py#L8146-L8186 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/platform/profiling_controller_backend.py | python | ProfilingControllerBackend.Start | (self, profiler_name, base_output_file) | Starts profiling using |profiler_name|. Results are saved to
|base_output_file|.<process_name>. | Starts profiling using |profiler_name|. Results are saved to
|base_output_file|.<process_name>. | [
"Starts",
"profiling",
"using",
"|profiler_name|",
".",
"Results",
"are",
"saved",
"to",
"|base_output_file|",
".",
"<process_name",
">",
"."
] | def Start(self, profiler_name, base_output_file):
"""Starts profiling using |profiler_name|. Results are saved to
|base_output_file|.<process_name>."""
assert not self._active_profilers, 'Already profiling. Must stop first.'
profiler_class = profiler_finder.FindProfiler(profiler_name)
if not profiler_class.is_supported(self._browser_backend.browser_type):
raise Exception('The %s profiler is not '
'supported on this platform.' % profiler_name)
if not profiler_class in self._profilers_states:
self._profilers_states[profiler_class] = {}
self._active_profilers.append(
profiler_class(self._browser_backend, self._platform_backend,
base_output_file, self._profilers_states[profiler_class])) | [
"def",
"Start",
"(",
"self",
",",
"profiler_name",
",",
"base_output_file",
")",
":",
"assert",
"not",
"self",
".",
"_active_profilers",
",",
"'Already profiling. Must stop first.'",
"profiler_class",
"=",
"profiler_finder",
".",
"FindProfiler",
"(",
"profiler_name",
")",
"if",
"not",
"profiler_class",
".",
"is_supported",
"(",
"self",
".",
"_browser_backend",
".",
"browser_type",
")",
":",
"raise",
"Exception",
"(",
"'The %s profiler is not '",
"'supported on this platform.'",
"%",
"profiler_name",
")",
"if",
"not",
"profiler_class",
"in",
"self",
".",
"_profilers_states",
":",
"self",
".",
"_profilers_states",
"[",
"profiler_class",
"]",
"=",
"{",
"}",
"self",
".",
"_active_profilers",
".",
"append",
"(",
"profiler_class",
"(",
"self",
".",
"_browser_backend",
",",
"self",
".",
"_platform_backend",
",",
"base_output_file",
",",
"self",
".",
"_profilers_states",
"[",
"profiler_class",
"]",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/platform/profiling_controller_backend.py#L14-L30 | ||
baoboa/pyqt5 | 11d5f43bc6f213d9d60272f3954a0048569cfc7c | configure.py | python | check_python | (target_config) | Check the Python installation. target_config is the target
configuration. | Check the Python installation. target_config is the target
configuration. | [
"Check",
"the",
"Python",
"installation",
".",
"target_config",
"is",
"the",
"target",
"configuration",
"."
] | def check_python(target_config):
""" Check the Python installation. target_config is the target
configuration.
"""
# Check the Python version number. This allows us to assume relative
# imports and ElemenTree are available.
if target_config.py_version < 0x020600:
error("PyQt5 requires Python v2.6 or later.") | [
"def",
"check_python",
"(",
"target_config",
")",
":",
"# Check the Python version number. This allows us to assume relative",
"# imports and ElemenTree are available.",
"if",
"target_config",
".",
"py_version",
"<",
"0x020600",
":",
"error",
"(",
"\"PyQt5 requires Python v2.6 or later.\"",
")"
] | https://github.com/baoboa/pyqt5/blob/11d5f43bc6f213d9d60272f3954a0048569cfc7c/configure.py#L2825-L2833 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/io_ops.py | python | _MatchingFilesShape | (op) | return [tensor_shape.unknown_shape(ndims=1)] | Shape function for the MatchingFiles op. | Shape function for the MatchingFiles op. | [
"Shape",
"function",
"for",
"the",
"MatchingFiles",
"op",
"."
] | def _MatchingFilesShape(op):
"""Shape function for the MatchingFiles op."""
unused_patern_shape = op.inputs[0].get_shape().merge_with(
tensor_shape.scalar())
return [tensor_shape.unknown_shape(ndims=1)] | [
"def",
"_MatchingFilesShape",
"(",
"op",
")",
":",
"unused_patern_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"return",
"[",
"tensor_shape",
".",
"unknown_shape",
"(",
"ndims",
"=",
"1",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/io_ops.py#L628-L632 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/directtools/DirectSelection.py | python | SelectedNodePaths.select | (self, nodePath, fMultiSelect = 0, fSelectTag = 1) | return dnp | Select the specified node path. Multiselect as required | Select the specified node path. Multiselect as required | [
"Select",
"the",
"specified",
"node",
"path",
".",
"Multiselect",
"as",
"required"
] | def select(self, nodePath, fMultiSelect = 0, fSelectTag = 1):
""" Select the specified node path. Multiselect as required """
# Do nothing if nothing selected
if not nodePath:
print('Nothing selected!!')
return None
# Reset selected objects and highlight if multiSelect is false
if not fMultiSelect:
self.deselectAll()
# Select tagged object if present
if fSelectTag:
for tag in self.tagList:
if nodePath.hasNetTag(tag):
nodePath = nodePath.findNetTag(tag)
break
# Get this pointer
id = nodePath.get_key()
# First see if its already in the selected dictionary
dnp = self.getSelectedDict(id)
# If so, deselect it
if dnp:
self.deselect(nodePath)
return None
else:
# See if it is in the deselected dictionary
dnp = self.getDeselectedDict(id)
if dnp:
# Remove it from the deselected dictionary
del self.deselectedDict[id]
# Show its bounding box
dnp.highlight()
else:
# Didn't find it, create a new selectedNodePath instance
dnp = DirectNodePath(nodePath)
# Show its bounding box
dnp.highlight(fRecompute = 0)
# Add it to the selected dictionary
self.selectedDict[dnp.get_key()] = dnp
self.selectedList.append(dnp) # [gjeon]
# And update last
__builtins__["last"] = self.last = dnp
# Update cluster servers if this is a cluster client
if base.direct.clusterMode == 'client':
cluster.selectNodePath(dnp)
return dnp | [
"def",
"select",
"(",
"self",
",",
"nodePath",
",",
"fMultiSelect",
"=",
"0",
",",
"fSelectTag",
"=",
"1",
")",
":",
"# Do nothing if nothing selected",
"if",
"not",
"nodePath",
":",
"print",
"(",
"'Nothing selected!!'",
")",
"return",
"None",
"# Reset selected objects and highlight if multiSelect is false",
"if",
"not",
"fMultiSelect",
":",
"self",
".",
"deselectAll",
"(",
")",
"# Select tagged object if present",
"if",
"fSelectTag",
":",
"for",
"tag",
"in",
"self",
".",
"tagList",
":",
"if",
"nodePath",
".",
"hasNetTag",
"(",
"tag",
")",
":",
"nodePath",
"=",
"nodePath",
".",
"findNetTag",
"(",
"tag",
")",
"break",
"# Get this pointer",
"id",
"=",
"nodePath",
".",
"get_key",
"(",
")",
"# First see if its already in the selected dictionary",
"dnp",
"=",
"self",
".",
"getSelectedDict",
"(",
"id",
")",
"# If so, deselect it",
"if",
"dnp",
":",
"self",
".",
"deselect",
"(",
"nodePath",
")",
"return",
"None",
"else",
":",
"# See if it is in the deselected dictionary",
"dnp",
"=",
"self",
".",
"getDeselectedDict",
"(",
"id",
")",
"if",
"dnp",
":",
"# Remove it from the deselected dictionary",
"del",
"self",
".",
"deselectedDict",
"[",
"id",
"]",
"# Show its bounding box",
"dnp",
".",
"highlight",
"(",
")",
"else",
":",
"# Didn't find it, create a new selectedNodePath instance",
"dnp",
"=",
"DirectNodePath",
"(",
"nodePath",
")",
"# Show its bounding box",
"dnp",
".",
"highlight",
"(",
"fRecompute",
"=",
"0",
")",
"# Add it to the selected dictionary",
"self",
".",
"selectedDict",
"[",
"dnp",
".",
"get_key",
"(",
")",
"]",
"=",
"dnp",
"self",
".",
"selectedList",
".",
"append",
"(",
"dnp",
")",
"# [gjeon]",
"# And update last",
"__builtins__",
"[",
"\"last\"",
"]",
"=",
"self",
".",
"last",
"=",
"dnp",
"# Update cluster servers if this is a cluster client",
"if",
"base",
".",
"direct",
".",
"clusterMode",
"==",
"'client'",
":",
"cluster",
".",
"selectNodePath",
"(",
"dnp",
")",
"return",
"dnp"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/directtools/DirectSelection.py#L68-L116 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/inspect.py | python | getargs | (co) | return Arguments(args, varargs, varkw) | Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None. | Get information about the arguments accepted by a code object. | [
"Get",
"information",
"about",
"the",
"arguments",
"accepted",
"by",
"a",
"code",
"object",
"."
] | def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None."""
if not iscode(co):
raise TypeError('{!r} is not a code object'.format(co))
nargs = co.co_argcount
names = co.co_varnames
args = list(names[:nargs])
step = 0
# The following acrobatics are for anonymous (tuple) arguments.
for i in range(nargs):
if args[i][:1] in ('', '.'):
stack, remain, count = [], [], []
while step < len(co.co_code):
op = ord(co.co_code[step])
step = step + 1
if op >= dis.HAVE_ARGUMENT:
opname = dis.opname[op]
value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
step = step + 2
if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
remain.append(value)
count.append(value)
elif opname == 'STORE_FAST':
stack.append(names[value])
# Special case for sublists of length 1: def foo((bar))
# doesn't generate the UNPACK_TUPLE bytecode, so if
# `remain` is empty here, we have such a sublist.
if not remain:
stack[0] = [stack[0]]
break
else:
remain[-1] = remain[-1] - 1
while remain[-1] == 0:
remain.pop()
size = count.pop()
stack[-size:] = [stack[-size:]]
if not remain: break
remain[-1] = remain[-1] - 1
if not remain: break
args[i] = stack[0]
varargs = None
if co.co_flags & CO_VARARGS:
varargs = co.co_varnames[nargs]
nargs = nargs + 1
varkw = None
if co.co_flags & CO_VARKEYWORDS:
varkw = co.co_varnames[nargs]
return Arguments(args, varargs, varkw) | [
"def",
"getargs",
"(",
"co",
")",
":",
"if",
"not",
"iscode",
"(",
"co",
")",
":",
"raise",
"TypeError",
"(",
"'{!r} is not a code object'",
".",
"format",
"(",
"co",
")",
")",
"nargs",
"=",
"co",
".",
"co_argcount",
"names",
"=",
"co",
".",
"co_varnames",
"args",
"=",
"list",
"(",
"names",
"[",
":",
"nargs",
"]",
")",
"step",
"=",
"0",
"# The following acrobatics are for anonymous (tuple) arguments.",
"for",
"i",
"in",
"range",
"(",
"nargs",
")",
":",
"if",
"args",
"[",
"i",
"]",
"[",
":",
"1",
"]",
"in",
"(",
"''",
",",
"'.'",
")",
":",
"stack",
",",
"remain",
",",
"count",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"while",
"step",
"<",
"len",
"(",
"co",
".",
"co_code",
")",
":",
"op",
"=",
"ord",
"(",
"co",
".",
"co_code",
"[",
"step",
"]",
")",
"step",
"=",
"step",
"+",
"1",
"if",
"op",
">=",
"dis",
".",
"HAVE_ARGUMENT",
":",
"opname",
"=",
"dis",
".",
"opname",
"[",
"op",
"]",
"value",
"=",
"ord",
"(",
"co",
".",
"co_code",
"[",
"step",
"]",
")",
"+",
"ord",
"(",
"co",
".",
"co_code",
"[",
"step",
"+",
"1",
"]",
")",
"*",
"256",
"step",
"=",
"step",
"+",
"2",
"if",
"opname",
"in",
"(",
"'UNPACK_TUPLE'",
",",
"'UNPACK_SEQUENCE'",
")",
":",
"remain",
".",
"append",
"(",
"value",
")",
"count",
".",
"append",
"(",
"value",
")",
"elif",
"opname",
"==",
"'STORE_FAST'",
":",
"stack",
".",
"append",
"(",
"names",
"[",
"value",
"]",
")",
"# Special case for sublists of length 1: def foo((bar))",
"# doesn't generate the UNPACK_TUPLE bytecode, so if",
"# `remain` is empty here, we have such a sublist.",
"if",
"not",
"remain",
":",
"stack",
"[",
"0",
"]",
"=",
"[",
"stack",
"[",
"0",
"]",
"]",
"break",
"else",
":",
"remain",
"[",
"-",
"1",
"]",
"=",
"remain",
"[",
"-",
"1",
"]",
"-",
"1",
"while",
"remain",
"[",
"-",
"1",
"]",
"==",
"0",
":",
"remain",
".",
"pop",
"(",
")",
"size",
"=",
"count",
".",
"pop",
"(",
")",
"stack",
"[",
"-",
"size",
":",
"]",
"=",
"[",
"stack",
"[",
"-",
"size",
":",
"]",
"]",
"if",
"not",
"remain",
":",
"break",
"remain",
"[",
"-",
"1",
"]",
"=",
"remain",
"[",
"-",
"1",
"]",
"-",
"1",
"if",
"not",
"remain",
":",
"break",
"args",
"[",
"i",
"]",
"=",
"stack",
"[",
"0",
"]",
"varargs",
"=",
"None",
"if",
"co",
".",
"co_flags",
"&",
"CO_VARARGS",
":",
"varargs",
"=",
"co",
".",
"co_varnames",
"[",
"nargs",
"]",
"nargs",
"=",
"nargs",
"+",
"1",
"varkw",
"=",
"None",
"if",
"co",
".",
"co_flags",
"&",
"CO_VARKEYWORDS",
":",
"varkw",
"=",
"co",
".",
"co_varnames",
"[",
"nargs",
"]",
"return",
"Arguments",
"(",
"args",
",",
"varargs",
",",
"varkw",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/inspect.py#L743-L799 | |
potassco/clingo | e0c91d8f95cc28de1c480a871f9c97c30de83d40 | libpyclingo/clingo/solving.py | python | SolveHandle.resume | (self) | Discards the last model and starts searching for the next one.
Notes
-----
If the search has been started asynchronously, this function starts the
search in the background. | Discards the last model and starts searching for the next one. | [
"Discards",
"the",
"last",
"model",
"and",
"starts",
"searching",
"for",
"the",
"next",
"one",
"."
] | def resume(self) -> None:
'''
Discards the last model and starts searching for the next one.
Notes
-----
If the search has been started asynchronously, this function starts the
search in the background.
'''
_handle_error(_lib.clingo_solve_handle_resume(self._rep), self._handler) | [
"def",
"resume",
"(",
"self",
")",
"->",
"None",
":",
"_handle_error",
"(",
"_lib",
".",
"clingo_solve_handle_resume",
"(",
"self",
".",
"_rep",
")",
",",
"self",
".",
"_handler",
")"
] | https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/solving.py#L513-L522 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/symbolic.py | python | is_var | (v) | return isinstance(v,Variable) or isinstance(v,VariableExpression) | Returns True if v is equivalent to a stand-alone variable. | Returns True if v is equivalent to a stand-alone variable. | [
"Returns",
"True",
"if",
"v",
"is",
"equivalent",
"to",
"a",
"stand",
"-",
"alone",
"variable",
"."
] | def is_var(v):
"""Returns True if v is equivalent to a stand-alone variable."""
return isinstance(v,Variable) or isinstance(v,VariableExpression) | [
"def",
"is_var",
"(",
"v",
")",
":",
"return",
"isinstance",
"(",
"v",
",",
"Variable",
")",
"or",
"isinstance",
"(",
"v",
",",
"VariableExpression",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/symbolic.py#L3731-L3733 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_array_ops.py | python | stack_dynamic_partitions | (data, partitions, num_partitions, name=None) | Stacks dynamic partitions of a Tensor or RaggedTensor.
Returns a RaggedTensor `output` with `num_partitions` rows, where the row
`output[i]` is formed by stacking all slices `data[j1...jN]` such that
`partitions[j1...jN] = i`. Slices of `data` are stacked in row-major
order.
If `num_partitions` is an `int` (not a `Tensor`), then this is equivalent to
`tf.ragged.stack(tf.dynamic_partition(data, partitions, num_partitions))`.
####Example:
```python
>>> data = ['a', 'b', 'c', 'd', 'e']
>>> partitions = [ 3, 0, 2, 2, 3]
>>> num_partitions = 5
>>> tf.ragged.stack_dynamic_partitions(data, partitions, num_partitions)
<RaggedTensor [['b'], [], ['c', 'd'], ['a', 'e'], []]>
```
Args:
data: A `Tensor` or `RaggedTensor` containing the values to stack.
partitions: An `int32` or `int64` `Tensor` or `RaggedTensor` specifying the
partition that each slice of `data` should be added to.
`partitions.shape` must be a prefix of `data.shape`. Values must be
greater than or equal to zero, and less than `num_partitions`.
`partitions` is not required to be sorted.
num_partitions: An `int32` or `int64` scalar specifying the number of
partitions to output. This determines the number of rows in `output`.
name: A name prefix for the returned tensor (optional).
Returns:
A `RaggedTensor` containing the stacked partitions. The returned tensor
has the same dtype as `data`, and its shape is
`[num_partitions, (D)] + data.shape[partitions.rank:]`, where `(D)` is a
ragged dimension whose length is the number of data slices stacked for
each `partition`. | Stacks dynamic partitions of a Tensor or RaggedTensor. | [
"Stacks",
"dynamic",
"partitions",
"of",
"a",
"Tensor",
"or",
"RaggedTensor",
"."
] | def stack_dynamic_partitions(data, partitions, num_partitions, name=None):
"""Stacks dynamic partitions of a Tensor or RaggedTensor.
Returns a RaggedTensor `output` with `num_partitions` rows, where the row
`output[i]` is formed by stacking all slices `data[j1...jN]` such that
`partitions[j1...jN] = i`. Slices of `data` are stacked in row-major
order.
If `num_partitions` is an `int` (not a `Tensor`), then this is equivalent to
`tf.ragged.stack(tf.dynamic_partition(data, partitions, num_partitions))`.
####Example:
```python
>>> data = ['a', 'b', 'c', 'd', 'e']
>>> partitions = [ 3, 0, 2, 2, 3]
>>> num_partitions = 5
>>> tf.ragged.stack_dynamic_partitions(data, partitions, num_partitions)
<RaggedTensor [['b'], [], ['c', 'd'], ['a', 'e'], []]>
```
Args:
data: A `Tensor` or `RaggedTensor` containing the values to stack.
partitions: An `int32` or `int64` `Tensor` or `RaggedTensor` specifying the
partition that each slice of `data` should be added to.
`partitions.shape` must be a prefix of `data.shape`. Values must be
greater than or equal to zero, and less than `num_partitions`.
`partitions` is not required to be sorted.
num_partitions: An `int32` or `int64` scalar specifying the number of
partitions to output. This determines the number of rows in `output`.
name: A name prefix for the returned tensor (optional).
Returns:
A `RaggedTensor` containing the stacked partitions. The returned tensor
has the same dtype as `data`, and its shape is
`[num_partitions, (D)] + data.shape[partitions.rank:]`, where `(D)` is a
ragged dimension whose length is the number of data slices stacked for
each `partition`.
"""
with ops.name_scope(name, 'SegmentStack', [data, partitions, num_partitions]):
# Convert inputs to tensors.
data = ragged_tensor.convert_to_tensor_or_ragged_tensor(data, name='data')
row_splits_dtype = (
data.row_splits.dtype
if isinstance(data, ragged_tensor.RaggedTensor) else None)
partitions = ragged_tensor.convert_to_tensor_or_ragged_tensor(
partitions, name='partitions', preferred_dtype=row_splits_dtype)
num_partitions = ops.convert_to_tensor(
num_partitions, name='num_partitions', preferred_dtype=partitions.dtype)
if row_splits_dtype is not None:
partitions = math_ops.cast(partitions, row_splits_dtype)
num_partitions = math_ops.cast(num_partitions, partitions.dtype)
# Sanity-checks for shapes.
partitions_rank = partitions.shape.ndims
if partitions_rank is None:
raise ValueError('partitions must have known rank.')
num_partitions.shape.assert_has_rank(0)
partitions.shape.assert_is_compatible_with(data.shape[:partitions_rank])
if partitions_rank == 0:
# If partitions is a scalar, then just create a RaggedTensor containing
# that single the complete `data` value in the specified row.
return ragged_tensor.RaggedTensor.from_value_rowids(
values=array_ops.stack([data]),
value_rowids=array_ops.stack([partitions]),
nrows=num_partitions,
validate=False)
elif partitions_rank == 1:
# If partitions is a vector (the typical case): we can just use data and
# partitions as the `values` and `value_rowids` for `from_value_rowids`,
# as long as we sort them first.
permutation = sort_ops.argsort(partitions, stable=True)
value_rowids = array_ops.gather(partitions, permutation)
values = array_ops.gather(data, permutation)
check = check_ops.assert_less(
value_rowids[-1:],
num_partitions,
message='partitions must be less than num_partitions')
with ops.control_dependencies([check]):
return ragged_tensor.RaggedTensor.from_value_rowids(
values, value_rowids, nrows=num_partitions, validate=False)
else:
# Handle higher-dimensional partitions via recursion.
if not isinstance(data, ragged_tensor.RaggedTensor):
data = ragged_tensor.RaggedTensor.from_tensor(
data, row_splits_dtype=partitions.dtype, ragged_rank=1)
if not isinstance(partitions, ragged_tensor.RaggedTensor):
partitions = ragged_tensor.RaggedTensor.from_tensor(
partitions,
row_splits_dtype=partitions.dtype,
ragged_rank=max(data.ragged_rank, partitions_rank - 1))
check = check_ops.assert_equal(
data.row_splits,
partitions.row_splits,
message='data and partitions have incompatible ragged shapes')
with ops.control_dependencies([check]):
return stack_dynamic_partitions(data.values, partitions.values,
num_partitions) | [
"def",
"stack_dynamic_partitions",
"(",
"data",
",",
"partitions",
",",
"num_partitions",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'SegmentStack'",
",",
"[",
"data",
",",
"partitions",
",",
"num_partitions",
"]",
")",
":",
"# Convert inputs to tensors.",
"data",
"=",
"ragged_tensor",
".",
"convert_to_tensor_or_ragged_tensor",
"(",
"data",
",",
"name",
"=",
"'data'",
")",
"row_splits_dtype",
"=",
"(",
"data",
".",
"row_splits",
".",
"dtype",
"if",
"isinstance",
"(",
"data",
",",
"ragged_tensor",
".",
"RaggedTensor",
")",
"else",
"None",
")",
"partitions",
"=",
"ragged_tensor",
".",
"convert_to_tensor_or_ragged_tensor",
"(",
"partitions",
",",
"name",
"=",
"'partitions'",
",",
"preferred_dtype",
"=",
"row_splits_dtype",
")",
"num_partitions",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"num_partitions",
",",
"name",
"=",
"'num_partitions'",
",",
"preferred_dtype",
"=",
"partitions",
".",
"dtype",
")",
"if",
"row_splits_dtype",
"is",
"not",
"None",
":",
"partitions",
"=",
"math_ops",
".",
"cast",
"(",
"partitions",
",",
"row_splits_dtype",
")",
"num_partitions",
"=",
"math_ops",
".",
"cast",
"(",
"num_partitions",
",",
"partitions",
".",
"dtype",
")",
"# Sanity-checks for shapes.",
"partitions_rank",
"=",
"partitions",
".",
"shape",
".",
"ndims",
"if",
"partitions_rank",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'partitions must have known rank.'",
")",
"num_partitions",
".",
"shape",
".",
"assert_has_rank",
"(",
"0",
")",
"partitions",
".",
"shape",
".",
"assert_is_compatible_with",
"(",
"data",
".",
"shape",
"[",
":",
"partitions_rank",
"]",
")",
"if",
"partitions_rank",
"==",
"0",
":",
"# If partitions is a scalar, then just create a RaggedTensor containing",
"# that single the complete `data` value in the specified row.",
"return",
"ragged_tensor",
".",
"RaggedTensor",
".",
"from_value_rowids",
"(",
"values",
"=",
"array_ops",
".",
"stack",
"(",
"[",
"data",
"]",
")",
",",
"value_rowids",
"=",
"array_ops",
".",
"stack",
"(",
"[",
"partitions",
"]",
")",
",",
"nrows",
"=",
"num_partitions",
",",
"validate",
"=",
"False",
")",
"elif",
"partitions_rank",
"==",
"1",
":",
"# If partitions is a vector (the typical case): we can just use data and",
"# partitions as the `values` and `value_rowids` for `from_value_rowids`,",
"# as long as we sort them first.",
"permutation",
"=",
"sort_ops",
".",
"argsort",
"(",
"partitions",
",",
"stable",
"=",
"True",
")",
"value_rowids",
"=",
"array_ops",
".",
"gather",
"(",
"partitions",
",",
"permutation",
")",
"values",
"=",
"array_ops",
".",
"gather",
"(",
"data",
",",
"permutation",
")",
"check",
"=",
"check_ops",
".",
"assert_less",
"(",
"value_rowids",
"[",
"-",
"1",
":",
"]",
",",
"num_partitions",
",",
"message",
"=",
"'partitions must be less than num_partitions'",
")",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"check",
"]",
")",
":",
"return",
"ragged_tensor",
".",
"RaggedTensor",
".",
"from_value_rowids",
"(",
"values",
",",
"value_rowids",
",",
"nrows",
"=",
"num_partitions",
",",
"validate",
"=",
"False",
")",
"else",
":",
"# Handle higher-dimensional partitions via recursion.",
"if",
"not",
"isinstance",
"(",
"data",
",",
"ragged_tensor",
".",
"RaggedTensor",
")",
":",
"data",
"=",
"ragged_tensor",
".",
"RaggedTensor",
".",
"from_tensor",
"(",
"data",
",",
"row_splits_dtype",
"=",
"partitions",
".",
"dtype",
",",
"ragged_rank",
"=",
"1",
")",
"if",
"not",
"isinstance",
"(",
"partitions",
",",
"ragged_tensor",
".",
"RaggedTensor",
")",
":",
"partitions",
"=",
"ragged_tensor",
".",
"RaggedTensor",
".",
"from_tensor",
"(",
"partitions",
",",
"row_splits_dtype",
"=",
"partitions",
".",
"dtype",
",",
"ragged_rank",
"=",
"max",
"(",
"data",
".",
"ragged_rank",
",",
"partitions_rank",
"-",
"1",
")",
")",
"check",
"=",
"check_ops",
".",
"assert_equal",
"(",
"data",
".",
"row_splits",
",",
"partitions",
".",
"row_splits",
",",
"message",
"=",
"'data and partitions have incompatible ragged shapes'",
")",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"check",
"]",
")",
":",
"return",
"stack_dynamic_partitions",
"(",
"data",
".",
"values",
",",
"partitions",
".",
"values",
",",
"num_partitions",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_array_ops.py#L554-L653 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/json_schema_compiler/memoize.py | python | memoize | (fn) | return impl | Decorates |fn| to memoize. | Decorates |fn| to memoize. | [
"Decorates",
"|fn|",
"to",
"memoize",
"."
] | def memoize(fn):
'''Decorates |fn| to memoize.
'''
memory = {}
def impl(*args, **optargs):
full_args = args + tuple(optargs.iteritems())
if full_args not in memory:
memory[full_args] = fn(*args, **optargs)
return memory[full_args]
return impl | [
"def",
"memoize",
"(",
"fn",
")",
":",
"memory",
"=",
"{",
"}",
"def",
"impl",
"(",
"*",
"args",
",",
"*",
"*",
"optargs",
")",
":",
"full_args",
"=",
"args",
"+",
"tuple",
"(",
"optargs",
".",
"iteritems",
"(",
")",
")",
"if",
"full_args",
"not",
"in",
"memory",
":",
"memory",
"[",
"full_args",
"]",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"optargs",
")",
"return",
"memory",
"[",
"full_args",
"]",
"return",
"impl"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/json_schema_compiler/memoize.py#L5-L14 | |
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/GUICommonWindows.py | python | ActionBardSongPressed | () | return | Toggles the battle song. | Toggles the battle song. | [
"Toggles",
"the",
"battle",
"song",
"."
] | def ActionBardSongPressed ():
"""Toggles the battle song."""
#get the global ID
pc = GemRB.GameGetFirstSelectedActor ()
GemRB.SetModalState (pc, MS_BATTLESONG)
GemRB.PlaySound ("act_01")
GemRB.SetVar ("ActionLevel", UAW_STANDARD)
UpdateActionsWindow ()
return | [
"def",
"ActionBardSongPressed",
"(",
")",
":",
"#get the global ID",
"pc",
"=",
"GemRB",
".",
"GameGetFirstSelectedActor",
"(",
")",
"GemRB",
".",
"SetModalState",
"(",
"pc",
",",
"MS_BATTLESONG",
")",
"GemRB",
".",
"PlaySound",
"(",
"\"act_01\"",
")",
"GemRB",
".",
"SetVar",
"(",
"\"ActionLevel\"",
",",
"UAW_STANDARD",
")",
"UpdateActionsWindow",
"(",
")",
"return"
] | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/GUICommonWindows.py#L887-L896 | |
eclipse/omr | 056e7c9ce9d503649190bc5bd9931fac30b4e4bc | jitbuilder/apigen/cppgen.py | python | CppGenerator.generate_callback_arg_list | (self, parm_descs) | return ", ".join(args) | Generates a list of the arguments of a client API callback
from a list of parameter descriptions.
The generated list is usable in the callback thunk to
forwarding the arguments to function implementing the
callback body. | Generates a list of the arguments of a client API callback
from a list of parameter descriptions. | [
"Generates",
"a",
"list",
"of",
"the",
"arguments",
"of",
"a",
"client",
"API",
"callback",
"from",
"a",
"list",
"of",
"parameter",
"descriptions",
"."
] | def generate_callback_arg_list(self, parm_descs):
"""
Generates a list of the arguments of a client API callback
from a list of parameter descriptions.
The generated list is usable in the callback thunk to
forwarding the arguments to function implementing the
callback body.
"""
cast_fmt = "static_cast<{t}>({n})"
args= [self.generate_arg(p) if p.type().is_builtin() else cast_fmt.format(t=self.get_client_type(p.type()),n=p.name()) for p in parm_descs]
return ", ".join(args) | [
"def",
"generate_callback_arg_list",
"(",
"self",
",",
"parm_descs",
")",
":",
"cast_fmt",
"=",
"\"static_cast<{t}>({n})\"",
"args",
"=",
"[",
"self",
".",
"generate_arg",
"(",
"p",
")",
"if",
"p",
".",
"type",
"(",
")",
".",
"is_builtin",
"(",
")",
"else",
"cast_fmt",
".",
"format",
"(",
"t",
"=",
"self",
".",
"get_client_type",
"(",
"p",
".",
"type",
"(",
")",
")",
",",
"n",
"=",
"p",
".",
"name",
"(",
")",
")",
"for",
"p",
"in",
"parm_descs",
"]",
"return",
"\", \"",
".",
"join",
"(",
"args",
")"
] | https://github.com/eclipse/omr/blob/056e7c9ce9d503649190bc5bd9931fac30b4e4bc/jitbuilder/apigen/cppgen.py#L632-L643 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/generator.py | python | _CppSourceFileWriter.gen_field_validators | (self, struct) | Generate non-trivial field validators. | Generate non-trivial field validators. | [
"Generate",
"non",
"-",
"trivial",
"field",
"validators",
"."
] | def gen_field_validators(self, struct):
# type: (ast.Struct) -> None
"""Generate non-trivial field validators."""
for field in struct.fields:
if field.validator is None:
# Fields without validators are implemented in the header.
continue
for optional_params in [('IDLParserErrorContext& ctxt, ', 'ctxt, '), ('', '')]:
self._gen_field_validator(struct, field, optional_params) | [
"def",
"gen_field_validators",
"(",
"self",
",",
"struct",
")",
":",
"# type: (ast.Struct) -> None",
"for",
"field",
"in",
"struct",
".",
"fields",
":",
"if",
"field",
".",
"validator",
"is",
"None",
":",
"# Fields without validators are implemented in the header.",
"continue",
"for",
"optional_params",
"in",
"[",
"(",
"'IDLParserErrorContext& ctxt, '",
",",
"'ctxt, '",
")",
",",
"(",
"''",
",",
"''",
")",
"]",
":",
"self",
".",
"_gen_field_validator",
"(",
"struct",
",",
"field",
",",
"optional_params",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/generator.py#L1753-L1762 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/serialization.py | python | save | (obj, f, pickle_module=pickle, pickle_protocol=pickle.DEFAULT_PROTOCOL) | r"""Save an object to disk file.
Args:
obj: object to save. Only ``module`` or ``state_dict`` are allowed.
f: a string of file name or a text file object to which ``obj`` is saved to.
pickle_module: Default: ``pickle``.
pickle_protocol: Default: ``pickle.DEFAULT_PROTOCOL``. | r"""Save an object to disk file. | [
"r",
"Save",
"an",
"object",
"to",
"disk",
"file",
"."
] | def save(obj, f, pickle_module=pickle, pickle_protocol=pickle.DEFAULT_PROTOCOL):
r"""Save an object to disk file.
Args:
obj: object to save. Only ``module`` or ``state_dict`` are allowed.
f: a string of file name or a text file object to which ``obj`` is saved to.
pickle_module: Default: ``pickle``.
pickle_protocol: Default: ``pickle.DEFAULT_PROTOCOL``.
"""
if isinstance(f, str):
with open(f, "wb") as fout:
save(
obj, fout, pickle_module=pickle_module, pickle_protocol=pickle_protocol
)
return
with max_recursion_limit():
assert hasattr(f, "write"), "{} does not support write".format(f)
pickle_module.dump(obj, f, pickle_protocol) | [
"def",
"save",
"(",
"obj",
",",
"f",
",",
"pickle_module",
"=",
"pickle",
",",
"pickle_protocol",
"=",
"pickle",
".",
"DEFAULT_PROTOCOL",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"str",
")",
":",
"with",
"open",
"(",
"f",
",",
"\"wb\"",
")",
"as",
"fout",
":",
"save",
"(",
"obj",
",",
"fout",
",",
"pickle_module",
"=",
"pickle_module",
",",
"pickle_protocol",
"=",
"pickle_protocol",
")",
"return",
"with",
"max_recursion_limit",
"(",
")",
":",
"assert",
"hasattr",
"(",
"f",
",",
"\"write\"",
")",
",",
"\"{} does not support write\"",
".",
"format",
"(",
"f",
")",
"pickle_module",
".",
"dump",
"(",
"obj",
",",
"f",
",",
"pickle_protocol",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/serialization.py#L16-L34 | ||
google/shaka-player-embedded | dabbeb5b47cc257b37b9a254661546352aaf0afe | shaka/tools/gen_info_plist.py | python | _GenInfoPlist | (output) | Writes the Info.plist file to the given file object. | Writes the Info.plist file to the given file object. | [
"Writes",
"the",
"Info",
".",
"plist",
"file",
"to",
"the",
"given",
"file",
"object",
"."
] | def _GenInfoPlist(output):
"""Writes the Info.plist file to the given file object."""
version_str = version.GetVersionStr()
major, minor, revision, tag = version.ParseVersion(version_str)
body = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleVersion</key>
<string>%s</string>
<key>CFBundleShortVersionString</key>
<string>%s</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleIdentifier</key>
<string>${IOS_BUNDLE_ID_PREFIX}.${EXECUTABLE_NAME:rfc1034identifier}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
</dict>
</plist>
"""
# Note that only the first three values are used by the OS, the tag is
# ignored.
version_out = '%s.%s.%s.%s' % (major, minor, revision, tag)
output.write(body % (version_out, version_out.rsplit('.', 1)[0])) | [
"def",
"_GenInfoPlist",
"(",
"output",
")",
":",
"version_str",
"=",
"version",
".",
"GetVersionStr",
"(",
")",
"major",
",",
"minor",
",",
"revision",
",",
"tag",
"=",
"version",
".",
"ParseVersion",
"(",
"version_str",
")",
"body",
"=",
"\"\"\"\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>CFBundleVersion</key>\n <string>%s</string>\n <key>CFBundleShortVersionString</key>\n <string>%s</string>\n <key>CFBundleSignature</key>\n <string>????</string>\n <key>CFBundlePackageType</key>\n <string>FMWK</string>\n <key>CFBundleInfoDictionaryVersion</key>\n <string>6.0</string>\n <key>CFBundleIdentifier</key>\n <string>${IOS_BUNDLE_ID_PREFIX}.${EXECUTABLE_NAME:rfc1034identifier}</string>\n <key>CFBundleExecutable</key>\n <string>${EXECUTABLE_NAME}</string>\n <key>CFBundleDevelopmentRegion</key>\n <string>English</string>\n</dict>\n</plist>\n \"\"\"",
"# Note that only the first three values are used by the OS, the tag is",
"# ignored.",
"version_out",
"=",
"'%s.%s.%s.%s'",
"%",
"(",
"major",
",",
"minor",
",",
"revision",
",",
"tag",
")",
"output",
".",
"write",
"(",
"body",
"%",
"(",
"version_out",
",",
"version_out",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
")",
")"
] | https://github.com/google/shaka-player-embedded/blob/dabbeb5b47cc257b37b9a254661546352aaf0afe/shaka/tools/gen_info_plist.py#L24-L57 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/tracing.py | python | TracingTrack.GetMatchingEvents | (self, category, name) | return [e for e in self.GetEvents() if e.Matches(category, name)] | Gets events matching |category| and |name|. | Gets events matching |category| and |name|. | [
"Gets",
"events",
"matching",
"|category|",
"and",
"|name|",
"."
] | def GetMatchingEvents(self, category, name):
"""Gets events matching |category| and |name|."""
return [e for e in self.GetEvents() if e.Matches(category, name)] | [
"def",
"GetMatchingEvents",
"(",
"self",
",",
"category",
",",
"name",
")",
":",
"return",
"[",
"e",
"for",
"e",
"in",
"self",
".",
"GetEvents",
"(",
")",
"if",
"e",
".",
"Matches",
"(",
"category",
",",
"name",
")",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/tracing.py#L76-L78 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/discriminant_analysis.py | python | LinearDiscriminantAnalysis.predict_proba | (self, X) | Estimate probability.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data.
Returns
-------
C : array, shape (n_samples, n_classes)
Estimated probabilities. | Estimate probability. | [
"Estimate",
"probability",
"."
] | def predict_proba(self, X):
"""Estimate probability.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data.
Returns
-------
C : array, shape (n_samples, n_classes)
Estimated probabilities.
"""
check_is_fitted(self)
decision = self.decision_function(X)
if self.classes_.size == 2:
proba = expit(decision)
return np.vstack([1-proba, proba]).T
else:
return softmax(decision) | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
")",
"decision",
"=",
"self",
".",
"decision_function",
"(",
"X",
")",
"if",
"self",
".",
"classes_",
".",
"size",
"==",
"2",
":",
"proba",
"=",
"expit",
"(",
"decision",
")",
"return",
"np",
".",
"vstack",
"(",
"[",
"1",
"-",
"proba",
",",
"proba",
"]",
")",
".",
"T",
"else",
":",
"return",
"softmax",
"(",
"decision",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/discriminant_analysis.py#L518-L538 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/InputFileEditorWithMesh.py | python | InputFileEditorWithMesh.addToMainMenu | (self, menubar) | Register the menus specific to the InputTab.
Input:
menubar: The menu bar to add the menus to. | Register the menus specific to the InputTab.
Input:
menubar: The menu bar to add the menus to. | [
"Register",
"the",
"menus",
"specific",
"to",
"the",
"InputTab",
".",
"Input",
":",
"menubar",
":",
"The",
"menu",
"bar",
"to",
"add",
"the",
"menus",
"to",
"."
] | def addToMainMenu(self, menubar):
"""
Register the menus specific to the InputTab.
Input:
menubar: The menu bar to add the menus to.
"""
inputMenu = menubar.addMenu("Input File")
self.InputFileEditorPlugin.addToMenu(inputMenu)
self.BackgroundPlugin.addToMenu(inputMenu) | [
"def",
"addToMainMenu",
"(",
"self",
",",
"menubar",
")",
":",
"inputMenu",
"=",
"menubar",
".",
"addMenu",
"(",
"\"Input File\"",
")",
"self",
".",
"InputFileEditorPlugin",
".",
"addToMenu",
"(",
"inputMenu",
")",
"self",
".",
"BackgroundPlugin",
".",
"addToMenu",
"(",
"inputMenu",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/InputFileEditorWithMesh.py#L217-L225 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/util/url.py | python | Url.request_uri | (self) | return uri | Absolute path including the query string. | Absolute path including the query string. | [
"Absolute",
"path",
"including",
"the",
"query",
"string",
"."
] | def request_uri(self):
"""Absolute path including the query string."""
uri = self.path or "/"
if self.query is not None:
uri += "?" + self.query
return uri | [
"def",
"request_uri",
"(",
"self",
")",
":",
"uri",
"=",
"self",
".",
"path",
"or",
"\"/\"",
"if",
"self",
".",
"query",
"is",
"not",
"None",
":",
"uri",
"+=",
"\"?\"",
"+",
"self",
".",
"query",
"return",
"uri"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/util/url.py#L115-L122 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/filedialog.py | python | test | () | Simple test program. | Simple test program. | [
"Simple",
"test",
"program",
"."
] | def test():
"""Simple test program."""
root = Tk()
root.withdraw()
fd = LoadFileDialog(root)
loadfile = fd.go(key="test")
fd = SaveFileDialog(root)
savefile = fd.go(key="test")
print(loadfile, savefile)
# Since the file name may contain non-ASCII characters, we need
# to find an encoding that likely supports the file name, and
# displays correctly on the terminal.
# Start off with UTF-8
enc = "utf-8"
import sys
# See whether CODESET is defined
try:
import locale
locale.setlocale(locale.LC_ALL,'')
enc = locale.nl_langinfo(locale.CODESET)
except (ImportError, AttributeError):
pass
# dialog for openening files
openfilename=askopenfilename(filetypes=[("all files", "*")])
try:
fp=open(openfilename,"r")
fp.close()
except:
print("Could not open File: ")
print(sys.exc_info()[1])
print("open", openfilename.encode(enc))
# dialog for saving files
saveasfilename=asksaveasfilename()
print("saveas", saveasfilename.encode(enc)) | [
"def",
"test",
"(",
")",
":",
"root",
"=",
"Tk",
"(",
")",
"root",
".",
"withdraw",
"(",
")",
"fd",
"=",
"LoadFileDialog",
"(",
"root",
")",
"loadfile",
"=",
"fd",
".",
"go",
"(",
"key",
"=",
"\"test\"",
")",
"fd",
"=",
"SaveFileDialog",
"(",
"root",
")",
"savefile",
"=",
"fd",
".",
"go",
"(",
"key",
"=",
"\"test\"",
")",
"print",
"(",
"loadfile",
",",
"savefile",
")",
"# Since the file name may contain non-ASCII characters, we need",
"# to find an encoding that likely supports the file name, and",
"# displays correctly on the terminal.",
"# Start off with UTF-8",
"enc",
"=",
"\"utf-8\"",
"import",
"sys",
"# See whether CODESET is defined",
"try",
":",
"import",
"locale",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_ALL",
",",
"''",
")",
"enc",
"=",
"locale",
".",
"nl_langinfo",
"(",
"locale",
".",
"CODESET",
")",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
":",
"pass",
"# dialog for openening files",
"openfilename",
"=",
"askopenfilename",
"(",
"filetypes",
"=",
"[",
"(",
"\"all files\"",
",",
"\"*\"",
")",
"]",
")",
"try",
":",
"fp",
"=",
"open",
"(",
"openfilename",
",",
"\"r\"",
")",
"fp",
".",
"close",
"(",
")",
"except",
":",
"print",
"(",
"\"Could not open File: \"",
")",
"print",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
")",
"print",
"(",
"\"open\"",
",",
"openfilename",
".",
"encode",
"(",
"enc",
")",
")",
"# dialog for saving files",
"saveasfilename",
"=",
"asksaveasfilename",
"(",
")",
"print",
"(",
"\"saveas\"",
",",
"saveasfilename",
".",
"encode",
"(",
"enc",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/filedialog.py#L435-L476 | ||
OpenLightingProject/ola | d1433a1bed73276fbe55ce18c03b1c208237decc | python/ola/RDMAPI.py | python | RDMAPI._SendRawRequest | (self, universe, uid, sub_device, pid, callback, data,
request_type, include_frames) | return method(
universe,
uid,
sub_device,
pid.value,
lambda response: self._GenericHandler(callback, uid, response),
data,
include_frames) | Send a RDM Request.
Args:
universe: The universe to send the request on.
uid: The UID to address the request to.
sub_device: The Sub Device to send the request to.
pid: A PID object that describes the format of the request.
callback: The callback to run when the request completes.
data: The param data.
request_type: PidStore.RDM_GET or PidStore.RDM_SET
include_frames: True if the response should include the raw frame data.
Return:
True if sent ok, False otherwise. | Send a RDM Request. | [
"Send",
"a",
"RDM",
"Request",
"."
] | def _SendRawRequest(self, universe, uid, sub_device, pid, callback, data,
request_type, include_frames):
"""Send a RDM Request.
Args:
universe: The universe to send the request on.
uid: The UID to address the request to.
sub_device: The Sub Device to send the request to.
pid: A PID object that describes the format of the request.
callback: The callback to run when the request completes.
data: The param data.
request_type: PidStore.RDM_GET or PidStore.RDM_SET
include_frames: True if the response should include the raw frame data.
Return:
True if sent ok, False otherwise.
"""
if self._strict_checks:
request_params = {
'uid': uid,
'sub_device': sub_device,
}
if not pid.ValidateAddressing(request_params, request_type):
return False
if request_type == PidStore.RDM_SET:
method = self._client.RDMSet
elif request_type == PidStore.RDM_DISCOVERY:
method = self._client.SendRawRDMDiscovery
else:
method = self._client.RDMGet
return method(
universe,
uid,
sub_device,
pid.value,
lambda response: self._GenericHandler(callback, uid, response),
data,
include_frames) | [
"def",
"_SendRawRequest",
"(",
"self",
",",
"universe",
",",
"uid",
",",
"sub_device",
",",
"pid",
",",
"callback",
",",
"data",
",",
"request_type",
",",
"include_frames",
")",
":",
"if",
"self",
".",
"_strict_checks",
":",
"request_params",
"=",
"{",
"'uid'",
":",
"uid",
",",
"'sub_device'",
":",
"sub_device",
",",
"}",
"if",
"not",
"pid",
".",
"ValidateAddressing",
"(",
"request_params",
",",
"request_type",
")",
":",
"return",
"False",
"if",
"request_type",
"==",
"PidStore",
".",
"RDM_SET",
":",
"method",
"=",
"self",
".",
"_client",
".",
"RDMSet",
"elif",
"request_type",
"==",
"PidStore",
".",
"RDM_DISCOVERY",
":",
"method",
"=",
"self",
".",
"_client",
".",
"SendRawRDMDiscovery",
"else",
":",
"method",
"=",
"self",
".",
"_client",
".",
"RDMGet",
"return",
"method",
"(",
"universe",
",",
"uid",
",",
"sub_device",
",",
"pid",
".",
"value",
",",
"lambda",
"response",
":",
"self",
".",
"_GenericHandler",
"(",
"callback",
",",
"uid",
",",
"response",
")",
",",
"data",
",",
"include_frames",
")"
] | https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/RDMAPI.py#L201-L240 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | DeleteHandler.WriteServiceImplementation | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteServiceImplementation(self, func, file):
"""Overrriden from TypeHandler."""
pass | [
"def",
"WriteServiceImplementation",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"pass"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L3070-L3072 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/layers/python/layers/optimizers.py | python | _add_scaled_noise_to_gradients | (grads_and_vars, gradient_noise_scale) | return list(zip(noisy_gradients, variables)) | Adds scaled noise from a 0-mean normal distribution to gradients. | Adds scaled noise from a 0-mean normal distribution to gradients. | [
"Adds",
"scaled",
"noise",
"from",
"a",
"0",
"-",
"mean",
"normal",
"distribution",
"to",
"gradients",
"."
] | def _add_scaled_noise_to_gradients(grads_and_vars, gradient_noise_scale):
"""Adds scaled noise from a 0-mean normal distribution to gradients."""
gradients, variables = zip(*grads_and_vars)
noisy_gradients = []
for gradient in gradients:
if gradient is None:
noisy_gradients.append(None)
continue
if isinstance(gradient, ops.IndexedSlices):
gradient_shape = gradient.dense_shape
else:
gradient_shape = gradient.get_shape()
noise = random_ops.truncated_normal(gradient_shape) * gradient_noise_scale
noisy_gradients.append(gradient + noise)
return list(zip(noisy_gradients, variables)) | [
"def",
"_add_scaled_noise_to_gradients",
"(",
"grads_and_vars",
",",
"gradient_noise_scale",
")",
":",
"gradients",
",",
"variables",
"=",
"zip",
"(",
"*",
"grads_and_vars",
")",
"noisy_gradients",
"=",
"[",
"]",
"for",
"gradient",
"in",
"gradients",
":",
"if",
"gradient",
"is",
"None",
":",
"noisy_gradients",
".",
"append",
"(",
"None",
")",
"continue",
"if",
"isinstance",
"(",
"gradient",
",",
"ops",
".",
"IndexedSlices",
")",
":",
"gradient_shape",
"=",
"gradient",
".",
"dense_shape",
"else",
":",
"gradient_shape",
"=",
"gradient",
".",
"get_shape",
"(",
")",
"noise",
"=",
"random_ops",
".",
"truncated_normal",
"(",
"gradient_shape",
")",
"*",
"gradient_noise_scale",
"noisy_gradients",
".",
"append",
"(",
"gradient",
"+",
"noise",
")",
"return",
"list",
"(",
"zip",
"(",
"noisy_gradients",
",",
"variables",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/layers/python/layers/optimizers.py#L228-L242 | |
mysql/mysql-router | cc0179f982bb9739a834eb6fd205a56224616133 | ext/gmock/scripts/gmock_doctor.py | python | _OverloadedMethodActionDiagnoser | (msg) | return _GenericDiagnoser('OMA', 'Overloaded Method Action',
[(gcc_regex, diagnosis),
(clang_regex, diagnosis)],
msg) | Diagnoses the OMA disease, given the error messages by the compiler. | Diagnoses the OMA disease, given the error messages by the compiler. | [
"Diagnoses",
"the",
"OMA",
"disease",
"given",
"the",
"error",
"messages",
"by",
"the",
"compiler",
"."
] | def _OverloadedMethodActionDiagnoser(msg):
"""Diagnoses the OMA disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
r'call to \'Invoke\(.+, <unresolved overloaded function '
r'type>\)')
clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function '
r'for call to \'Invoke\'\r?\n'
r'(.*\n)*?'
r'.*\bgmock-\w+-actions\.h:\d+:\d+: '
r'note: candidate function template not viable: '
r'requires .*, but 2 (arguments )?were provided')
diagnosis = """
The second argument you gave to Invoke() is an overloaded method. Please
tell your compiler which overloaded version you want to use.
For example, if you want to use the version whose signature is
class Foo {
...
bool Bar(int n, double x);
};
you should write something like
Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
return _GenericDiagnoser('OMA', 'Overloaded Method Action',
[(gcc_regex, diagnosis),
(clang_regex, diagnosis)],
msg) | [
"def",
"_OverloadedMethodActionDiagnoser",
"(",
"msg",
")",
":",
"gcc_regex",
"=",
"(",
"_GCC_FILE_LINE_RE",
"+",
"r'error: no matching function for '",
"r'call to \\'Invoke\\(.+, <unresolved overloaded function '",
"r'type>\\)'",
")",
"clang_regex",
"=",
"(",
"_CLANG_FILE_LINE_RE",
"+",
"r'error: no matching function '",
"r'for call to \\'Invoke\\'\\r?\\n'",
"r'(.*\\n)*?'",
"r'.*\\bgmock-\\w+-actions\\.h:\\d+:\\d+: '",
"r'note: candidate function template not viable: '",
"r'requires .*, but 2 (arguments )?were provided'",
")",
"diagnosis",
"=",
"\"\"\"\nThe second argument you gave to Invoke() is an overloaded method. Please\ntell your compiler which overloaded version you want to use.\n\nFor example, if you want to use the version whose signature is\n class Foo {\n ...\n bool Bar(int n, double x);\n };\nyou should write something like\n Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))\"\"\"",
"return",
"_GenericDiagnoser",
"(",
"'OMA'",
",",
"'Overloaded Method Action'",
",",
"[",
"(",
"gcc_regex",
",",
"diagnosis",
")",
",",
"(",
"clang_regex",
",",
"diagnosis",
")",
"]",
",",
"msg",
")"
] | https://github.com/mysql/mysql-router/blob/cc0179f982bb9739a834eb6fd205a56224616133/ext/gmock/scripts/gmock_doctor.py#L324-L350 | |
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/302.smallest-rectangle-enclosing-black-pixels.py | python | Solution.minArea | (self, image, x, y) | return (bottom - top + 1) * (right - left + 1) | :type image: List[List[str]]
:type x: int
:type y: int
:rtype: int | :type image: List[List[str]]
:type x: int
:type y: int
:rtype: int | [
":",
"type",
"image",
":",
"List",
"[",
"List",
"[",
"str",
"]]",
":",
"type",
"x",
":",
"int",
":",
"type",
"y",
":",
"int",
":",
"rtype",
":",
"int"
] | def minArea(self, image, x, y):
"""
:type image: List[List[str]]
:type x: int
:type y: int
:rtype: int
"""
top = self.searchTop(image, x, y)
bottom = self.searchBottom(image, x, y)
left = self.searchLeft(image, x, y, top, bottom)
right = self.searchRight(image, x, y, top, bottom)
return (bottom - top + 1) * (right - left + 1) | [
"def",
"minArea",
"(",
"self",
",",
"image",
",",
"x",
",",
"y",
")",
":",
"top",
"=",
"self",
".",
"searchTop",
"(",
"image",
",",
"x",
",",
"y",
")",
"bottom",
"=",
"self",
".",
"searchBottom",
"(",
"image",
",",
"x",
",",
"y",
")",
"left",
"=",
"self",
".",
"searchLeft",
"(",
"image",
",",
"x",
",",
"y",
",",
"top",
",",
"bottom",
")",
"right",
"=",
"self",
".",
"searchRight",
"(",
"image",
",",
"x",
",",
"y",
",",
"top",
",",
"bottom",
")",
"return",
"(",
"bottom",
"-",
"top",
"+",
"1",
")",
"*",
"(",
"right",
"-",
"left",
"+",
"1",
")"
] | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/302.smallest-rectangle-enclosing-black-pixels.py#L2-L14 | |
lballabio/quantlib-old | 136336947ed4fea9ecc1da6edad188700e821739 | gensrc/gensrc/utilities/buffer.py | python | Buffer.set | (self, dict) | return self.buffer_ | Set and return the text of this buffer. | Set and return the text of this buffer. | [
"Set",
"and",
"return",
"the",
"text",
"of",
"this",
"buffer",
"."
] | def set(self, dict):
"""Set and return the text of this buffer."""
self.buffer_ = self.text_ % dict
return self.buffer_ | [
"def",
"set",
"(",
"self",
",",
"dict",
")",
":",
"self",
".",
"buffer_",
"=",
"self",
".",
"text_",
"%",
"dict",
"return",
"self",
".",
"buffer_"
] | https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/utilities/buffer.py#L46-L49 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/sping/PDF/pidPDF.py | python | PDFCanvas.save | (self, file=None, format=None) | Saves the file. If holding data, do
a showPage() to save them having to. | Saves the file. If holding data, do
a showPage() to save them having to. | [
"Saves",
"the",
"file",
".",
"If",
"holding",
"data",
"do",
"a",
"showPage",
"()",
"to",
"save",
"them",
"having",
"to",
"."
] | def save(self, file=None, format=None):
"""Saves the file. If holding data, do
a showPage() to save them having to."""
if self.pdf.pageHasData():
self.pdf.showPage()
if hasattr(file, 'write'):
self.pdf.save(fileobj=file)
elif isinstance(file, str):
self.pdf.save(filename=file)
else:
self.pdf.save() | [
"def",
"save",
"(",
"self",
",",
"file",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"if",
"self",
".",
"pdf",
".",
"pageHasData",
"(",
")",
":",
"self",
".",
"pdf",
".",
"showPage",
"(",
")",
"if",
"hasattr",
"(",
"file",
",",
"'write'",
")",
":",
"self",
".",
"pdf",
".",
"save",
"(",
"fileobj",
"=",
"file",
")",
"elif",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"self",
".",
"pdf",
".",
"save",
"(",
"filename",
"=",
"file",
")",
"else",
":",
"self",
".",
"pdf",
".",
"save",
"(",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/PDF/pidPDF.py#L166-L178 | ||
shoaibrayeen/Programmers-Community | 1d352fb3e6ac5e2e7d9472d90527bdcc8d5ec355 | Basic/Calculate Factorial of A Number/SolutionByTanmay.py | python | fact_num | (num) | Objective : To Find The Factorial Of A Number
Input : Number ( num ) - Numeric Value
Return : Factorial Of A Number - Numeric Value | Objective : To Find The Factorial Of A Number
Input : Number ( num ) - Numeric Value
Return : Factorial Of A Number - Numeric Value | [
"Objective",
":",
"To",
"Find",
"The",
"Factorial",
"Of",
"A",
"Number",
"Input",
":",
"Number",
"(",
"num",
")",
"-",
"Numeric",
"Value",
"Return",
":",
"Factorial",
"Of",
"A",
"Number",
"-",
"Numeric",
"Value"
] | def fact_num(num):
'''
Objective : To Find The Factorial Of A Number
Input : Number ( num ) - Numeric Value
Return : Factorial Of A Number - Numeric Value
'''
if num==0:
return 1
else:
return num*fact_num(num-1) | [
"def",
"fact_num",
"(",
"num",
")",
":",
"if",
"num",
"==",
"0",
":",
"return",
"1",
"else",
":",
"return",
"num",
"*",
"fact_num",
"(",
"num",
"-",
"1",
")"
] | https://github.com/shoaibrayeen/Programmers-Community/blob/1d352fb3e6ac5e2e7d9472d90527bdcc8d5ec355/Basic/Calculate Factorial of A Number/SolutionByTanmay.py#L1-L13 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageFont.py | python | TransposedFont.__init__ | (self, font, orientation=None) | Wrapper that creates a transposed font from any existing font
object.
:param font: A font object.
:param orientation: An optional orientation. If given, this should
be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM,
Image.ROTATE_90, Image.ROTATE_180, or Image.ROTATE_270. | Wrapper that creates a transposed font from any existing font
object. | [
"Wrapper",
"that",
"creates",
"a",
"transposed",
"font",
"from",
"any",
"existing",
"font",
"object",
"."
] | def __init__(self, font, orientation=None):
"""
Wrapper that creates a transposed font from any existing font
object.
:param font: A font object.
:param orientation: An optional orientation. If given, this should
be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM,
Image.ROTATE_90, Image.ROTATE_180, or Image.ROTATE_270.
"""
self.font = font
self.orientation = orientation | [
"def",
"__init__",
"(",
"self",
",",
"font",
",",
"orientation",
"=",
"None",
")",
":",
"self",
".",
"font",
"=",
"font",
"self",
".",
"orientation",
"=",
"orientation"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageFont.py#L556-L567 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_view.py | python | TFAsymmetryFittingView.set_slot_for_normalisation_changed | (self, slot) | Sets the slot for handling when a normalisation value is changed by the user. | Sets the slot for handling when a normalisation value is changed by the user. | [
"Sets",
"the",
"slot",
"for",
"handling",
"when",
"a",
"normalisation",
"value",
"is",
"changed",
"by",
"the",
"user",
"."
] | def set_slot_for_normalisation_changed(self, slot) -> None:
"""Sets the slot for handling when a normalisation value is changed by the user."""
self.tf_asymmetry_fitting_options.set_slot_for_normalisation_changed(slot) | [
"def",
"set_slot_for_normalisation_changed",
"(",
"self",
",",
"slot",
")",
"->",
"None",
":",
"self",
".",
"tf_asymmetry_fitting_options",
".",
"set_slot_for_normalisation_changed",
"(",
"slot",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_view.py#L38-L40 | ||
NVIDIA/MDL-SDK | aa9642b2546ad7b6236b5627385d882c2ed83c5d | src/mdl/jit/generator_jit/gen_intrinsic_func.py | python | SignatureParser.create_type_sig_tuple | (self, params) | return "(" + ", ".join(res) + ")" | Create a type signature tuple (a, b) for a signature a_b. | Create a type signature tuple (a, b) for a signature a_b. | [
"Create",
"a",
"type",
"signature",
"tuple",
"(",
"a",
"b",
")",
"for",
"a",
"signature",
"a_b",
"."
] | def create_type_sig_tuple(self, params):
"""Create a type signature tuple (a, b) for a signature a_b."""
res = []
comma = ""
for param in params:
try:
type_name = self.m_inv_types[param]
except KeyError:
error("Unknown type_code '%s' found" % param)
sys.exit(1)
res.append(type_name)
return "(" + ", ".join(res) + ")" | [
"def",
"create_type_sig_tuple",
"(",
"self",
",",
"params",
")",
":",
"res",
"=",
"[",
"]",
"comma",
"=",
"\"\"",
"for",
"param",
"in",
"params",
":",
"try",
":",
"type_name",
"=",
"self",
".",
"m_inv_types",
"[",
"param",
"]",
"except",
"KeyError",
":",
"error",
"(",
"\"Unknown type_code '%s' found\"",
"%",
"param",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"res",
".",
"append",
"(",
"type_name",
")",
"return",
"\"(\"",
"+",
"\", \"",
".",
"join",
"(",
"res",
")",
"+",
"\")\""
] | https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/generator_jit/gen_intrinsic_func.py#L5488-L5499 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/saved_model/signature_def_utils_impl.py | python | build_signature_def | (inputs=None, outputs=None, method_name=None) | return signature_def | Utility function to build a SignatureDef protocol buffer.
Args:
inputs: Inputs of the SignatureDef defined as a proto map of string to
tensor info.
outputs: Outputs of the SignatureDef defined as a proto map of string to
tensor info.
method_name: Method name of the SignatureDef as a string.
Returns:
A SignatureDef protocol buffer constructed based on the supplied arguments. | Utility function to build a SignatureDef protocol buffer. | [
"Utility",
"function",
"to",
"build",
"a",
"SignatureDef",
"protocol",
"buffer",
"."
] | def build_signature_def(inputs=None, outputs=None, method_name=None):
"""Utility function to build a SignatureDef protocol buffer.
Args:
inputs: Inputs of the SignatureDef defined as a proto map of string to
tensor info.
outputs: Outputs of the SignatureDef defined as a proto map of string to
tensor info.
method_name: Method name of the SignatureDef as a string.
Returns:
A SignatureDef protocol buffer constructed based on the supplied arguments.
"""
signature_def = meta_graph_pb2.SignatureDef()
if inputs is not None:
for item in inputs:
signature_def.inputs[item].CopyFrom(inputs[item])
if outputs is not None:
for item in outputs:
signature_def.outputs[item].CopyFrom(outputs[item])
if method_name is not None:
signature_def.method_name = method_name
return signature_def | [
"def",
"build_signature_def",
"(",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"method_name",
"=",
"None",
")",
":",
"signature_def",
"=",
"meta_graph_pb2",
".",
"SignatureDef",
"(",
")",
"if",
"inputs",
"is",
"not",
"None",
":",
"for",
"item",
"in",
"inputs",
":",
"signature_def",
".",
"inputs",
"[",
"item",
"]",
".",
"CopyFrom",
"(",
"inputs",
"[",
"item",
"]",
")",
"if",
"outputs",
"is",
"not",
"None",
":",
"for",
"item",
"in",
"outputs",
":",
"signature_def",
".",
"outputs",
"[",
"item",
"]",
".",
"CopyFrom",
"(",
"outputs",
"[",
"item",
"]",
")",
"if",
"method_name",
"is",
"not",
"None",
":",
"signature_def",
".",
"method_name",
"=",
"method_name",
"return",
"signature_def"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/saved_model/signature_def_utils_impl.py#L31-L53 | |
Sigil-Ebook/Sigil | 0d145d3a4874b4a26f7aabd68dbd9d18a2402e52 | src/Resource_Files/plugin_launchers/python/sigil_bs4/__init__.py | python | BeautifulSoup.new_tag | (self, name, namespace=None, nsprefix=None, **attrs) | return Tag(None, self.builder, name, namespace, nsprefix, attrs) | Create a new tag associated with this soup. | Create a new tag associated with this soup. | [
"Create",
"a",
"new",
"tag",
"associated",
"with",
"this",
"soup",
"."
] | def new_tag(self, name, namespace=None, nsprefix=None, **attrs):
"""Create a new tag associated with this soup."""
return Tag(None, self.builder, name, namespace, nsprefix, attrs) | [
"def",
"new_tag",
"(",
"self",
",",
"name",
",",
"namespace",
"=",
"None",
",",
"nsprefix",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"Tag",
"(",
"None",
",",
"self",
".",
"builder",
",",
"name",
",",
"namespace",
",",
"nsprefix",
",",
"attrs",
")"
] | https://github.com/Sigil-Ebook/Sigil/blob/0d145d3a4874b4a26f7aabd68dbd9d18a2402e52/src/Resource_Files/plugin_launchers/python/sigil_bs4/__init__.py#L265-L267 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/http/client.py | python | HTTPConnection.endheaders | (self, message_body=None, *, encode_chunked=False) | Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional message_body
argument can be used to pass a message body associated with the
request. | Indicate that the last header line has been sent to the server. | [
"Indicate",
"that",
"the",
"last",
"header",
"line",
"has",
"been",
"sent",
"to",
"the",
"server",
"."
] | def endheaders(self, message_body=None, *, encode_chunked=False):
"""Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional message_body
argument can be used to pass a message body associated with the
request.
"""
if self.__state == _CS_REQ_STARTED:
self.__state = _CS_REQ_SENT
else:
raise CannotSendHeader()
self._send_output(message_body, encode_chunked=encode_chunked) | [
"def",
"endheaders",
"(",
"self",
",",
"message_body",
"=",
"None",
",",
"*",
",",
"encode_chunked",
"=",
"False",
")",
":",
"if",
"self",
".",
"__state",
"==",
"_CS_REQ_STARTED",
":",
"self",
".",
"__state",
"=",
"_CS_REQ_SENT",
"else",
":",
"raise",
"CannotSendHeader",
"(",
")",
"self",
".",
"_send_output",
"(",
"message_body",
",",
"encode_chunked",
"=",
"encode_chunked",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/client.py#L1261-L1272 | ||
sandialabs/Albany | e7e05599c47f65dee6f1916b26f49a5b80d39416 | PyAlbany/python/Utils.py | python | norm | (distributedVector, comm) | return norm | @brief Computes the norm-2 of a distributed vector using Python and Teuchos MPI communicator. | [] | def norm(distributedVector, comm):
"""@brief Computes the norm-2 of a distributed vector using Python and Teuchos MPI communicator."""
norm = np.sqrt(inner(distributedVector, distributedVector, comm))
return norm | [
"def",
"norm",
"(",
"distributedVector",
",",
"comm",
")",
":",
"norm",
"=",
"np",
".",
"sqrt",
"(",
"inner",
"(",
"distributedVector",
",",
"distributedVector",
",",
"comm",
")",
")",
"return",
"norm"
] | https://github.com/sandialabs/Albany/blob/e7e05599c47f65dee6f1916b26f49a5b80d39416/PyAlbany/python/Utils.py#L17-L20 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | withClass | (classname, namespace='') | return withAttribute(**{classattr: classname}) | Simplified version of :class:`withAttribute` when
matching on a div class - made difficult because ``class`` is
a reserved word in Python.
Example::
html = '''
<div>
Some text
<div class="grid">1 4 0 1 0</div>
<div class="graph">1,3 2,3 1,1</div>
<div>this <div> has no class</div>
</div>
'''
div,div_end = makeHTMLTags("div")
div_grid = div().setParseAction(withClass("grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1 | Simplified version of :class:`withAttribute` when | [
"Simplified",
"version",
"of",
":",
"class",
":",
"withAttribute",
"when"
] | def withClass(classname, namespace=''):
"""Simplified version of :class:`withAttribute` when
matching on a div class - made difficult because ``class`` is
a reserved word in Python.
Example::
html = '''
<div>
Some text
<div class="grid">1 4 0 1 0</div>
<div class="graph">1,3 2,3 1,1</div>
<div>this <div> has no class</div>
</div>
'''
div,div_end = makeHTMLTags("div")
div_grid = div().setParseAction(withClass("grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
"""
classattr = "%s:class" % namespace if namespace else "class"
return withAttribute(**{classattr: classname}) | [
"def",
"withClass",
"(",
"classname",
",",
"namespace",
"=",
"''",
")",
":",
"classattr",
"=",
"\"%s:class\"",
"%",
"namespace",
"if",
"namespace",
"else",
"\"class\"",
"return",
"withAttribute",
"(",
"*",
"*",
"{",
"classattr",
":",
"classname",
"}",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L11891-L11963 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/ensemble/_voting.py | python | VotingClassifier.fit | (self, X, y, sample_weight=None) | return super().fit(X, transformed_y, sample_weight) | Fit the estimators.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape (n_samples,)
Target values.
sample_weight : array-like, shape (n_samples,) or None
Sample weights. If None, then samples are equally weighted.
Note that this is supported only if all underlying estimators
support sample weights.
Returns
-------
self : object | Fit the estimators. | [
"Fit",
"the",
"estimators",
"."
] | def fit(self, X, y, sample_weight=None):
"""Fit the estimators.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape (n_samples,)
Target values.
sample_weight : array-like, shape (n_samples,) or None
Sample weights. If None, then samples are equally weighted.
Note that this is supported only if all underlying estimators
support sample weights.
Returns
-------
self : object
"""
check_classification_targets(y)
if isinstance(y, np.ndarray) and len(y.shape) > 1 and y.shape[1] > 1:
raise NotImplementedError('Multilabel and multi-output'
' classification is not supported.')
if self.voting not in ('soft', 'hard'):
raise ValueError("Voting must be 'soft' or 'hard'; got (voting=%r)"
% self.voting)
self.le_ = LabelEncoder().fit(y)
self.classes_ = self.le_.classes_
transformed_y = self.le_.transform(y)
return super().fit(X, transformed_y, sample_weight) | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"sample_weight",
"=",
"None",
")",
":",
"check_classification_targets",
"(",
"y",
")",
"if",
"isinstance",
"(",
"y",
",",
"np",
".",
"ndarray",
")",
"and",
"len",
"(",
"y",
".",
"shape",
")",
">",
"1",
"and",
"y",
".",
"shape",
"[",
"1",
"]",
">",
"1",
":",
"raise",
"NotImplementedError",
"(",
"'Multilabel and multi-output'",
"' classification is not supported.'",
")",
"if",
"self",
".",
"voting",
"not",
"in",
"(",
"'soft'",
",",
"'hard'",
")",
":",
"raise",
"ValueError",
"(",
"\"Voting must be 'soft' or 'hard'; got (voting=%r)\"",
"%",
"self",
".",
"voting",
")",
"self",
".",
"le_",
"=",
"LabelEncoder",
"(",
")",
".",
"fit",
"(",
"y",
")",
"self",
".",
"classes_",
"=",
"self",
".",
"le_",
".",
"classes_",
"transformed_y",
"=",
"self",
".",
"le_",
".",
"transform",
"(",
"y",
")",
"return",
"super",
"(",
")",
".",
"fit",
"(",
"X",
",",
"transformed_y",
",",
"sample_weight",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_voting.py#L187-L222 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distribution/normal.py | python | Normal.probs | (self, value) | return elementwise_div(
ops.exp(-1. * ((value - self.loc) * (value - self.loc)) /
(2. * var)), (math.sqrt(2 * math.pi) * self.scale),
name=name) | Probability density/mass function.
Args:
value (Tensor): The input tensor.
Returns:
Tensor: probability.The data type is same with value. | Probability density/mass function. | [
"Probability",
"density",
"/",
"mass",
"function",
"."
] | def probs(self, value):
"""Probability density/mass function.
Args:
value (Tensor): The input tensor.
Returns:
Tensor: probability.The data type is same with value.
"""
name = self.name + '_probs'
value = self._check_values_dtype_in_probs(self.loc, value)
var = self.scale * self.scale
return elementwise_div(
ops.exp(-1. * ((value - self.loc) * (value - self.loc)) /
(2. * var)), (math.sqrt(2 * math.pi) * self.scale),
name=name) | [
"def",
"probs",
"(",
"self",
",",
"value",
")",
":",
"name",
"=",
"self",
".",
"name",
"+",
"'_probs'",
"value",
"=",
"self",
".",
"_check_values_dtype_in_probs",
"(",
"self",
".",
"loc",
",",
"value",
")",
"var",
"=",
"self",
".",
"scale",
"*",
"self",
".",
"scale",
"return",
"elementwise_div",
"(",
"ops",
".",
"exp",
"(",
"-",
"1.",
"*",
"(",
"(",
"value",
"-",
"self",
".",
"loc",
")",
"*",
"(",
"value",
"-",
"self",
".",
"loc",
")",
")",
"/",
"(",
"2.",
"*",
"var",
")",
")",
",",
"(",
"math",
".",
"sqrt",
"(",
"2",
"*",
"math",
".",
"pi",
")",
"*",
"self",
".",
"scale",
")",
",",
"name",
"=",
"name",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distribution/normal.py#L218-L235 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/ops.py | python | Graph._set_control_flow_context | (self, context) | Sets the current control flow context.
Args:
context: a context object. | Sets the current control flow context. | [
"Sets",
"the",
"current",
"control",
"flow",
"context",
"."
] | def _set_control_flow_context(self, context):
"""Sets the current control flow context.
Args:
context: a context object.
"""
self._control_flow_context = context | [
"def",
"_set_control_flow_context",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"_control_flow_context",
"=",
"context"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/ops.py#L2090-L2096 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/distribution_util.py | python | assert_integer_form | (
x, data=None, summarize=None, message=None, name="assert_integer_form") | return check_ops.assert_equal(
x, math_ops.cast(math_ops.round(casted_x), x.dtype),
data=data, summarize=summarize, message=message, name=name) | Assert that x has integer components (or floats equal to integers).
Args:
x: Numeric `Tensor`
data: The tensors to print out if the condition is `False`. Defaults to
error message and first few entries of `x` and `y`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name: A name for this operation (optional).
Returns:
Op raising `InvalidArgumentError` if round(x) != x. | Assert that x has integer components (or floats equal to integers). | [
"Assert",
"that",
"x",
"has",
"integer",
"components",
"(",
"or",
"floats",
"equal",
"to",
"integers",
")",
"."
] | def assert_integer_form(
x, data=None, summarize=None, message=None, name="assert_integer_form"):
"""Assert that x has integer components (or floats equal to integers).
Args:
x: Numeric `Tensor`
data: The tensors to print out if the condition is `False`. Defaults to
error message and first few entries of `x` and `y`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name: A name for this operation (optional).
Returns:
Op raising `InvalidArgumentError` if round(x) != x.
"""
message = message or "x has non-integer components"
x = ops.convert_to_tensor(x, name="x")
casted_x = math_ops.to_int64(x)
return check_ops.assert_equal(
x, math_ops.cast(math_ops.round(casted_x), x.dtype),
data=data, summarize=summarize, message=message, name=name) | [
"def",
"assert_integer_form",
"(",
"x",
",",
"data",
"=",
"None",
",",
"summarize",
"=",
"None",
",",
"message",
"=",
"None",
",",
"name",
"=",
"\"assert_integer_form\"",
")",
":",
"message",
"=",
"message",
"or",
"\"x has non-integer components\"",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
",",
"name",
"=",
"\"x\"",
")",
"casted_x",
"=",
"math_ops",
".",
"to_int64",
"(",
"x",
")",
"return",
"check_ops",
".",
"assert_equal",
"(",
"x",
",",
"math_ops",
".",
"cast",
"(",
"math_ops",
".",
"round",
"(",
"casted_x",
")",
",",
"x",
".",
"dtype",
")",
",",
"data",
"=",
"data",
",",
"summarize",
"=",
"summarize",
",",
"message",
"=",
"message",
",",
"name",
"=",
"name",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/distribution_util.py#L69-L90 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/tensor/attribute.py | python | is_complex | (x) | return is_complex_dtype | Return whether x is a tensor of complex data type(complex64 or complex128).
Args:
x (Tensor): The input tensor.
Returns:
bool: True if the data type of the input is complex data type, otherwise false.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor([1 + 2j, 3 + 4j])
print(paddle.is_complex(x))
# True
x = paddle.to_tensor([1.1, 1.2])
print(paddle.is_complex(x))
# False
x = paddle.to_tensor([1, 2, 3])
print(paddle.is_complex(x))
# False | Return whether x is a tensor of complex data type(complex64 or complex128). | [
"Return",
"whether",
"x",
"is",
"a",
"tensor",
"of",
"complex",
"data",
"type",
"(",
"complex64",
"or",
"complex128",
")",
"."
] | def is_complex(x):
"""Return whether x is a tensor of complex data type(complex64 or complex128).
Args:
x (Tensor): The input tensor.
Returns:
bool: True if the data type of the input is complex data type, otherwise false.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor([1 + 2j, 3 + 4j])
print(paddle.is_complex(x))
# True
x = paddle.to_tensor([1.1, 1.2])
print(paddle.is_complex(x))
# False
x = paddle.to_tensor([1, 2, 3])
print(paddle.is_complex(x))
# False
"""
if not isinstance(x, (paddle.Tensor, paddle.static.Variable)):
raise TypeError("Expected Tensor, but received type of x: {}".format(
type(x)))
dtype = x.dtype
is_complex_dtype = (dtype == core.VarDesc.VarType.COMPLEX64 or
dtype == core.VarDesc.VarType.COMPLEX128)
return is_complex_dtype | [
"def",
"is_complex",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"paddle",
".",
"Tensor",
",",
"paddle",
".",
"static",
".",
"Variable",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected Tensor, but received type of x: {}\"",
".",
"format",
"(",
"type",
"(",
"x",
")",
")",
")",
"dtype",
"=",
"x",
".",
"dtype",
"is_complex_dtype",
"=",
"(",
"dtype",
"==",
"core",
".",
"VarDesc",
".",
"VarType",
".",
"COMPLEX64",
"or",
"dtype",
"==",
"core",
".",
"VarDesc",
".",
"VarType",
".",
"COMPLEX128",
")",
"return",
"is_complex_dtype"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/attribute.py#L48-L80 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGridManager.GetPage | (*args) | return _propgrid.PropertyGridManager_GetPage(*args) | GetPage(self, int ind) -> PropertyGridPage
GetPage(self, String name) -> PropertyGridPage | GetPage(self, int ind) -> PropertyGridPage
GetPage(self, String name) -> PropertyGridPage | [
"GetPage",
"(",
"self",
"int",
"ind",
")",
"-",
">",
"PropertyGridPage",
"GetPage",
"(",
"self",
"String",
"name",
")",
"-",
">",
"PropertyGridPage"
] | def GetPage(*args):
"""
GetPage(self, int ind) -> PropertyGridPage
GetPage(self, String name) -> PropertyGridPage
"""
return _propgrid.PropertyGridManager_GetPage(*args) | [
"def",
"GetPage",
"(",
"*",
"args",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridManager_GetPage",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3481-L3486 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/rnn/python/ops/rnn_cell.py | python | NASCell.__init__ | (self, num_units, num_proj=None,
use_biases=False, reuse=None) | Initialize the parameters for a NAS cell.
Args:
num_units: int, The number of units in the NAS cell
num_proj: (optional) int, The output dimensionality for the projection
matrices. If None, no projection is performed.
use_biases: (optional) bool, If True then use biases within the cell. This
is False by default.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised. | Initialize the parameters for a NAS cell. | [
"Initialize",
"the",
"parameters",
"for",
"a",
"NAS",
"cell",
"."
] | def __init__(self, num_units, num_proj=None,
use_biases=False, reuse=None):
"""Initialize the parameters for a NAS cell.
Args:
num_units: int, The number of units in the NAS cell
num_proj: (optional) int, The output dimensionality for the projection
matrices. If None, no projection is performed.
use_biases: (optional) bool, If True then use biases within the cell. This
is False by default.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
"""
super(NASCell, self).__init__(_reuse=reuse)
self._num_units = num_units
self._num_proj = num_proj
self._use_biases = use_biases
self._reuse = reuse
if num_proj is not None:
self._state_size = rnn_cell_impl.LSTMStateTuple(num_units, num_proj)
self._output_size = num_proj
else:
self._state_size = rnn_cell_impl.LSTMStateTuple(num_units, num_units)
self._output_size = num_units | [
"def",
"__init__",
"(",
"self",
",",
"num_units",
",",
"num_proj",
"=",
"None",
",",
"use_biases",
"=",
"False",
",",
"reuse",
"=",
"None",
")",
":",
"super",
"(",
"NASCell",
",",
"self",
")",
".",
"__init__",
"(",
"_reuse",
"=",
"reuse",
")",
"self",
".",
"_num_units",
"=",
"num_units",
"self",
".",
"_num_proj",
"=",
"num_proj",
"self",
".",
"_use_biases",
"=",
"use_biases",
"self",
".",
"_reuse",
"=",
"reuse",
"if",
"num_proj",
"is",
"not",
"None",
":",
"self",
".",
"_state_size",
"=",
"rnn_cell_impl",
".",
"LSTMStateTuple",
"(",
"num_units",
",",
"num_proj",
")",
"self",
".",
"_output_size",
"=",
"num_proj",
"else",
":",
"self",
".",
"_state_size",
"=",
"rnn_cell_impl",
".",
"LSTMStateTuple",
"(",
"num_units",
",",
"num_units",
")",
"self",
".",
"_output_size",
"=",
"num_units"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1366-L1391 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/filters.py | python | do_lower | (s) | return soft_unicode(s).lower() | Convert a value to lowercase. | Convert a value to lowercase. | [
"Convert",
"a",
"value",
"to",
"lowercase",
"."
] | def do_lower(s):
"""Convert a value to lowercase."""
return soft_unicode(s).lower() | [
"def",
"do_lower",
"(",
"s",
")",
":",
"return",
"soft_unicode",
"(",
"s",
")",
".",
"lower",
"(",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/filters.py#L148-L150 | |
zhaoweicai/hwgq | ebc706bee3e2d145de1da4be446ce8de8740738f | scripts/cpp_lint.py | python | CheckBraces | (filename, clean_lines, linenum, error) | Looks for misplaced braces (e.g. at the end of line).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Looks for misplaced braces (e.g. at the end of line). | [
"Looks",
"for",
"misplaced",
"braces",
"(",
"e",
".",
"g",
".",
"at",
"the",
"end",
"of",
"line",
")",
"."
] | def CheckBraces(filename, clean_lines, linenum, error):
"""Looks for misplaced braces (e.g. at the end of line).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
if Match(r'\s*{\s*$', line):
# We allow an open brace to start a line in the case where someone is using
# braces in a block to explicitly create a new scope, which is commonly used
# to control the lifetime of stack-allocated variables. Braces are also
# used for brace initializers inside function calls. We don't detect this
# perfectly: we just don't complain if the last non-whitespace character on
# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
# previous line starts a preprocessor block.
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if (not Search(r'[,;:}{(]\s*$', prevline) and
not Match(r'\s*#', prevline)):
error(filename, linenum, 'whitespace/braces', 4,
'{ should almost always be at the end of the previous line')
# An else clause should be on the same line as the preceding closing brace.
if Match(r'\s*else\s*', line):
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if Match(r'\s*}\s*$', prevline):
error(filename, linenum, 'whitespace/newline', 4,
'An else should appear on the same line as the preceding }')
# If braces come on one side of an else, they should be on both.
# However, we have to worry about "else if" that spans multiple lines!
if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
# find the ( after the if
pos = line.find('else if')
pos = line.find('(', pos)
if pos > 0:
(endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
if endline[endpos:].find('{') == -1: # must be brace after if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
else: # common case: else not followed by a multi-line if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
# Likewise, an else should never have the else clause on the same line
if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
error(filename, linenum, 'whitespace/newline', 4,
'Else clause should never be on same line as else (use 2 lines)')
# In the same way, a do/while should never be on one line
if Match(r'\s*do [^\s{]', line):
error(filename, linenum, 'whitespace/newline', 4,
'do/while clauses should not be on a single line')
# Block bodies should not be followed by a semicolon. Due to C++11
# brace initialization, there are more places where semicolons are
# required than not, so we use a whitelist approach to check these
# rather than a blacklist. These are the places where "};" should
# be replaced by just "}":
# 1. Some flavor of block following closing parenthesis:
# for (;;) {};
# while (...) {};
# switch (...) {};
# Function(...) {};
# if (...) {};
# if (...) else if (...) {};
#
# 2. else block:
# if (...) else {};
#
# 3. const member function:
# Function(...) const {};
#
# 4. Block following some statement:
# x = 42;
# {};
#
# 5. Block at the beginning of a function:
# Function(...) {
# {};
# }
#
# Note that naively checking for the preceding "{" will also match
# braces inside multi-dimensional arrays, but this is fine since
# that expression will not contain semicolons.
#
# 6. Block following another block:
# while (true) {}
# {};
#
# 7. End of namespaces:
# namespace {};
#
# These semicolons seems far more common than other kinds of
# redundant semicolons, possibly due to people converting classes
# to namespaces. For now we do not warn for this case.
#
# Try matching case 1 first.
match = Match(r'^(.*\)\s*)\{', line)
if match:
# Matched closing parenthesis (case 1). Check the token before the
# matching opening parenthesis, and don't warn if it looks like a
# macro. This avoids these false positives:
# - macro that defines a base class
# - multi-line macro that defines a base class
# - macro that defines the whole class-head
#
# But we still issue warnings for macros that we know are safe to
# warn, specifically:
# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
# - TYPED_TEST
# - INTERFACE_DEF
# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
#
# We implement a whitelist of safe macros instead of a blacklist of
# unsafe macros, even though the latter appears less frequently in
# google code and would have been easier to implement. This is because
# the downside for getting the whitelist wrong means some extra
# semicolons, while the downside for getting the blacklist wrong
# would result in compile errors.
#
# In addition to macros, we also don't want to warn on compound
# literals.
closing_brace_pos = match.group(1).rfind(')')
opening_parenthesis = ReverseCloseExpression(
clean_lines, linenum, closing_brace_pos)
if opening_parenthesis[2] > -1:
line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
macro = Search(r'\b([A-Z_]+)\s*$', line_prefix)
if ((macro and
macro.group(1) not in (
'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
Search(r'\s+=\s*$', line_prefix)):
match = None
else:
# Try matching cases 2-3.
match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
if not match:
# Try matching cases 4-6. These are always matched on separate lines.
#
# Note that we can't simply concatenate the previous line to the
# current line and do a single match, otherwise we may output
# duplicate warnings for the blank line case:
# if (cond) {
# // blank line
# }
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if prevline and Search(r'[;{}]\s*$', prevline):
match = Match(r'^(\s*)\{', line)
# Check matching closing brace
if match:
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
# Current {} pair is eligible for semicolon check, and we have found
# the redundant semicolon, output warning here.
#
# Note: because we are scanning forward for opening braces, and
# outputting warnings for the matching closing brace, if there are
# nested blocks with trailing semicolons, we will get the error
# messages in reversed order.
error(filename, endlinenum, 'readability/braces', 4,
"You don't need a ; after a }") | [
"def",
"CheckBraces",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# get rid of comments and strings",
"if",
"Match",
"(",
"r'\\s*{\\s*$'",
",",
"line",
")",
":",
"# We allow an open brace to start a line in the case where someone is using",
"# braces in a block to explicitly create a new scope, which is commonly used",
"# to control the lifetime of stack-allocated variables. Braces are also",
"# used for brace initializers inside function calls. We don't detect this",
"# perfectly: we just don't complain if the last non-whitespace character on",
"# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the",
"# previous line starts a preprocessor block.",
"prevline",
"=",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
"[",
"0",
"]",
"if",
"(",
"not",
"Search",
"(",
"r'[,;:}{(]\\s*$'",
",",
"prevline",
")",
"and",
"not",
"Match",
"(",
"r'\\s*#'",
",",
"prevline",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/braces'",
",",
"4",
",",
"'{ should almost always be at the end of the previous line'",
")",
"# An else clause should be on the same line as the preceding closing brace.",
"if",
"Match",
"(",
"r'\\s*else\\s*'",
",",
"line",
")",
":",
"prevline",
"=",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
"[",
"0",
"]",
"if",
"Match",
"(",
"r'\\s*}\\s*$'",
",",
"prevline",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/newline'",
",",
"4",
",",
"'An else should appear on the same line as the preceding }'",
")",
"# If braces come on one side of an else, they should be on both.",
"# However, we have to worry about \"else if\" that spans multiple lines!",
"if",
"Search",
"(",
"r'}\\s*else[^{]*$'",
",",
"line",
")",
"or",
"Match",
"(",
"r'[^}]*else\\s*{'",
",",
"line",
")",
":",
"if",
"Search",
"(",
"r'}\\s*else if([^{]*)$'",
",",
"line",
")",
":",
"# could be multi-line if",
"# find the ( after the if",
"pos",
"=",
"line",
".",
"find",
"(",
"'else if'",
")",
"pos",
"=",
"line",
".",
"find",
"(",
"'('",
",",
"pos",
")",
"if",
"pos",
">",
"0",
":",
"(",
"endline",
",",
"_",
",",
"endpos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
"if",
"endline",
"[",
"endpos",
":",
"]",
".",
"find",
"(",
"'{'",
")",
"==",
"-",
"1",
":",
"# must be brace after if",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/braces'",
",",
"5",
",",
"'If an else has a brace on one side, it should have it on both'",
")",
"else",
":",
"# common case: else not followed by a multi-line if",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/braces'",
",",
"5",
",",
"'If an else has a brace on one side, it should have it on both'",
")",
"# Likewise, an else should never have the else clause on the same line",
"if",
"Search",
"(",
"r'\\belse [^\\s{]'",
",",
"line",
")",
"and",
"not",
"Search",
"(",
"r'\\belse if\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/newline'",
",",
"4",
",",
"'Else clause should never be on same line as else (use 2 lines)'",
")",
"# In the same way, a do/while should never be on one line",
"if",
"Match",
"(",
"r'\\s*do [^\\s{]'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/newline'",
",",
"4",
",",
"'do/while clauses should not be on a single line'",
")",
"# Block bodies should not be followed by a semicolon. Due to C++11",
"# brace initialization, there are more places where semicolons are",
"# required than not, so we use a whitelist approach to check these",
"# rather than a blacklist. These are the places where \"};\" should",
"# be replaced by just \"}\":",
"# 1. Some flavor of block following closing parenthesis:",
"# for (;;) {};",
"# while (...) {};",
"# switch (...) {};",
"# Function(...) {};",
"# if (...) {};",
"# if (...) else if (...) {};",
"#",
"# 2. else block:",
"# if (...) else {};",
"#",
"# 3. const member function:",
"# Function(...) const {};",
"#",
"# 4. Block following some statement:",
"# x = 42;",
"# {};",
"#",
"# 5. Block at the beginning of a function:",
"# Function(...) {",
"# {};",
"# }",
"#",
"# Note that naively checking for the preceding \"{\" will also match",
"# braces inside multi-dimensional arrays, but this is fine since",
"# that expression will not contain semicolons.",
"#",
"# 6. Block following another block:",
"# while (true) {}",
"# {};",
"#",
"# 7. End of namespaces:",
"# namespace {};",
"#",
"# These semicolons seems far more common than other kinds of",
"# redundant semicolons, possibly due to people converting classes",
"# to namespaces. For now we do not warn for this case.",
"#",
"# Try matching case 1 first.",
"match",
"=",
"Match",
"(",
"r'^(.*\\)\\s*)\\{'",
",",
"line",
")",
"if",
"match",
":",
"# Matched closing parenthesis (case 1). Check the token before the",
"# matching opening parenthesis, and don't warn if it looks like a",
"# macro. This avoids these false positives:",
"# - macro that defines a base class",
"# - multi-line macro that defines a base class",
"# - macro that defines the whole class-head",
"#",
"# But we still issue warnings for macros that we know are safe to",
"# warn, specifically:",
"# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P",
"# - TYPED_TEST",
"# - INTERFACE_DEF",
"# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:",
"#",
"# We implement a whitelist of safe macros instead of a blacklist of",
"# unsafe macros, even though the latter appears less frequently in",
"# google code and would have been easier to implement. This is because",
"# the downside for getting the whitelist wrong means some extra",
"# semicolons, while the downside for getting the blacklist wrong",
"# would result in compile errors.",
"#",
"# In addition to macros, we also don't want to warn on compound",
"# literals.",
"closing_brace_pos",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"rfind",
"(",
"')'",
")",
"opening_parenthesis",
"=",
"ReverseCloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"closing_brace_pos",
")",
"if",
"opening_parenthesis",
"[",
"2",
"]",
">",
"-",
"1",
":",
"line_prefix",
"=",
"opening_parenthesis",
"[",
"0",
"]",
"[",
"0",
":",
"opening_parenthesis",
"[",
"2",
"]",
"]",
"macro",
"=",
"Search",
"(",
"r'\\b([A-Z_]+)\\s*$'",
",",
"line_prefix",
")",
"if",
"(",
"(",
"macro",
"and",
"macro",
".",
"group",
"(",
"1",
")",
"not",
"in",
"(",
"'TEST'",
",",
"'TEST_F'",
",",
"'MATCHER'",
",",
"'MATCHER_P'",
",",
"'TYPED_TEST'",
",",
"'EXCLUSIVE_LOCKS_REQUIRED'",
",",
"'SHARED_LOCKS_REQUIRED'",
",",
"'LOCKS_EXCLUDED'",
",",
"'INTERFACE_DEF'",
")",
")",
"or",
"Search",
"(",
"r'\\s+=\\s*$'",
",",
"line_prefix",
")",
")",
":",
"match",
"=",
"None",
"else",
":",
"# Try matching cases 2-3.",
"match",
"=",
"Match",
"(",
"r'^(.*(?:else|\\)\\s*const)\\s*)\\{'",
",",
"line",
")",
"if",
"not",
"match",
":",
"# Try matching cases 4-6. These are always matched on separate lines.",
"#",
"# Note that we can't simply concatenate the previous line to the",
"# current line and do a single match, otherwise we may output",
"# duplicate warnings for the blank line case:",
"# if (cond) {",
"# // blank line",
"# }",
"prevline",
"=",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
"[",
"0",
"]",
"if",
"prevline",
"and",
"Search",
"(",
"r'[;{}]\\s*$'",
",",
"prevline",
")",
":",
"match",
"=",
"Match",
"(",
"r'^(\\s*)\\{'",
",",
"line",
")",
"# Check matching closing brace",
"if",
"match",
":",
"(",
"endline",
",",
"endlinenum",
",",
"endpos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"len",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"if",
"endpos",
">",
"-",
"1",
"and",
"Match",
"(",
"r'^\\s*;'",
",",
"endline",
"[",
"endpos",
":",
"]",
")",
":",
"# Current {} pair is eligible for semicolon check, and we have found",
"# the redundant semicolon, output warning here.",
"#",
"# Note: because we are scanning forward for opening braces, and",
"# outputting warnings for the matching closing brace, if there are",
"# nested blocks with trailing semicolons, we will get the error",
"# messages in reversed order.",
"error",
"(",
"filename",
",",
"endlinenum",
",",
"'readability/braces'",
",",
"4",
",",
"\"You don't need a ; after a }\"",
")"
] | https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/scripts/cpp_lint.py#L3069-L3240 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_ops.py | python | conv_transpose | (input, # pylint: disable=redefined-builtin
filters,
output_shape,
strides,
padding="SAME",
data_format=None,
dilations=None,
name=None) | The transpose of `convolution`.
This operation is sometimes called "deconvolution" after [Deconvolutional
Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf), but is
actually the transpose (gradient) of `convolution` rather than an actual
deconvolution.
Args:
input: An N+2 dimensional `Tensor` of shape
`[batch_size] + input_spatial_shape + [in_channels]` if data_format does
not start with "NC" (default), or
`[batch_size, in_channels] + input_spatial_shape` if data_format starts
with "NC". It must be one of the following types:
`half`, `bfloat16`, `float32`, `float64`.
filters: An N+2 dimensional `Tensor` with the same type as `input` and
shape `spatial_filter_shape + [in_channels, out_channels]`.
output_shape: A 1-D `Tensor` representing the output shape of the
deconvolution op.
strides: An int or list of `ints` that has length `1`, `N` or `N+2`. The
stride of the sliding window for each dimension of `input`. If a single
value is given it is replicated in the spatial dimensions. By default
the `N` and `C` dimensions are set to 0. The dimension order is determined
by the value of `data_format`, see below for details.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
the "returns" section of `tf.nn.convolution` for details.
data_format: A string or None. Specifies whether the channel dimension of
the `input` and output is the last dimension (default, or if `data_format`
does not start with "NC"), or the second dimension (if `data_format`
starts with "NC"). For N=1, the valid values are "NWC" (default) and
"NCW". For N=2, the valid values are "NHWC" (default) and "NCHW".
For N=3, the valid values are "NDHWC" (default) and "NCDHW".
dilations: An int or list of `ints` that has length `1`, `N` or `N+2`,
defaults to 1. The dilation factor for each dimension of`input`. If a
single value is given it is replicated in the spatial dimensions. By
default the `N` and `C` dimensions are set to 1. If set to k > 1, there
will be k-1 skipped cells between each filter element on that dimension.
The dimension order is determined by the value of `data_format`, see above
for details.
name: A name for the operation (optional). If not specified "conv_transpose"
is used.
Returns:
A `Tensor` with the same type as `value`. | The transpose of `convolution`. | [
"The",
"transpose",
"of",
"convolution",
"."
] | def conv_transpose(input, # pylint: disable=redefined-builtin
filters,
output_shape,
strides,
padding="SAME",
data_format=None,
dilations=None,
name=None):
"""The transpose of `convolution`.
This operation is sometimes called "deconvolution" after [Deconvolutional
Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf), but is
actually the transpose (gradient) of `convolution` rather than an actual
deconvolution.
Args:
input: An N+2 dimensional `Tensor` of shape
`[batch_size] + input_spatial_shape + [in_channels]` if data_format does
not start with "NC" (default), or
`[batch_size, in_channels] + input_spatial_shape` if data_format starts
with "NC". It must be one of the following types:
`half`, `bfloat16`, `float32`, `float64`.
filters: An N+2 dimensional `Tensor` with the same type as `input` and
shape `spatial_filter_shape + [in_channels, out_channels]`.
output_shape: A 1-D `Tensor` representing the output shape of the
deconvolution op.
strides: An int or list of `ints` that has length `1`, `N` or `N+2`. The
stride of the sliding window for each dimension of `input`. If a single
value is given it is replicated in the spatial dimensions. By default
the `N` and `C` dimensions are set to 0. The dimension order is determined
by the value of `data_format`, see below for details.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See
the "returns" section of `tf.nn.convolution` for details.
data_format: A string or None. Specifies whether the channel dimension of
the `input` and output is the last dimension (default, or if `data_format`
does not start with "NC"), or the second dimension (if `data_format`
starts with "NC"). For N=1, the valid values are "NWC" (default) and
"NCW". For N=2, the valid values are "NHWC" (default) and "NCHW".
For N=3, the valid values are "NDHWC" (default) and "NCDHW".
dilations: An int or list of `ints` that has length `1`, `N` or `N+2`,
defaults to 1. The dilation factor for each dimension of`input`. If a
single value is given it is replicated in the spatial dimensions. By
default the `N` and `C` dimensions are set to 1. If set to k > 1, there
will be k-1 skipped cells between each filter element on that dimension.
The dimension order is determined by the value of `data_format`, see above
for details.
name: A name for the operation (optional). If not specified "conv_transpose"
is used.
Returns:
A `Tensor` with the same type as `value`.
"""
with ops.name_scope(name, "conv_transpose",
[input, filter, output_shape]) as name:
if tensor_util.is_tensor(output_shape):
n = output_shape.shape[0] - 2
elif isinstance(output_shape, collections.Sized):
n = len(output_shape) - 2
else:
raise ValueError("output_shape must be a tensor or sized collection.")
if not 1 <= n <= 3:
raise ValueError(
"output_shape must be of length 3, 4 or 5 but was {}.".format(n + 2))
op = CONV_TRANSPOSE_OPS[n-1]
return op(
input,
filters,
output_shape,
strides,
padding=padding,
data_format=data_format,
dilations=dilations,
name=name) | [
"def",
"conv_transpose",
"(",
"input",
",",
"# pylint: disable=redefined-builtin",
"filters",
",",
"output_shape",
",",
"strides",
",",
"padding",
"=",
"\"SAME\"",
",",
"data_format",
"=",
"None",
",",
"dilations",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"conv_transpose\"",
",",
"[",
"input",
",",
"filter",
",",
"output_shape",
"]",
")",
"as",
"name",
":",
"if",
"tensor_util",
".",
"is_tensor",
"(",
"output_shape",
")",
":",
"n",
"=",
"output_shape",
".",
"shape",
"[",
"0",
"]",
"-",
"2",
"elif",
"isinstance",
"(",
"output_shape",
",",
"collections",
".",
"Sized",
")",
":",
"n",
"=",
"len",
"(",
"output_shape",
")",
"-",
"2",
"else",
":",
"raise",
"ValueError",
"(",
"\"output_shape must be a tensor or sized collection.\"",
")",
"if",
"not",
"1",
"<=",
"n",
"<=",
"3",
":",
"raise",
"ValueError",
"(",
"\"output_shape must be of length 3, 4 or 5 but was {}.\"",
".",
"format",
"(",
"n",
"+",
"2",
")",
")",
"op",
"=",
"CONV_TRANSPOSE_OPS",
"[",
"n",
"-",
"1",
"]",
"return",
"op",
"(",
"input",
",",
"filters",
",",
"output_shape",
",",
"strides",
",",
"padding",
"=",
"padding",
",",
"data_format",
"=",
"data_format",
",",
"dilations",
"=",
"dilations",
",",
"name",
"=",
"name",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_ops.py#L2608-L2682 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings._ConvertConditionalKeys | (self, configname) | Converts or warns on conditional keys. Xcode supports conditional keys,
such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation
with some keys converted while the rest force a warning. | Converts or warns on conditional keys. Xcode supports conditional keys,
such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation
with some keys converted while the rest force a warning. | [
"Converts",
"or",
"warns",
"on",
"conditional",
"keys",
".",
"Xcode",
"supports",
"conditional",
"keys",
"such",
"as",
"CODE_SIGN_IDENTITY",
"[",
"sdk",
"=",
"iphoneos",
"*",
"]",
".",
"This",
"is",
"a",
"partial",
"implementation",
"with",
"some",
"keys",
"converted",
"while",
"the",
"rest",
"force",
"a",
"warning",
"."
] | def _ConvertConditionalKeys(self, configname):
"""Converts or warns on conditional keys. Xcode supports conditional keys,
such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation
with some keys converted while the rest force a warning."""
settings = self.xcode_settings[configname]
conditional_keys = [key for key in settings if key.endswith(']')]
for key in conditional_keys:
# If you need more, speak up at http://crbug.com/122592
if key.endswith("[sdk=iphoneos*]"):
if configname.endswith("iphoneos"):
new_key = key.split("[")[0]
settings[new_key] = settings[key]
else:
print 'Warning: Conditional keys not implemented, ignoring:', \
' '.join(conditional_keys)
del settings[key] | [
"def",
"_ConvertConditionalKeys",
"(",
"self",
",",
"configname",
")",
":",
"settings",
"=",
"self",
".",
"xcode_settings",
"[",
"configname",
"]",
"conditional_keys",
"=",
"[",
"key",
"for",
"key",
"in",
"settings",
"if",
"key",
".",
"endswith",
"(",
"']'",
")",
"]",
"for",
"key",
"in",
"conditional_keys",
":",
"# If you need more, speak up at http://crbug.com/122592",
"if",
"key",
".",
"endswith",
"(",
"\"[sdk=iphoneos*]\"",
")",
":",
"if",
"configname",
".",
"endswith",
"(",
"\"iphoneos\"",
")",
":",
"new_key",
"=",
"key",
".",
"split",
"(",
"\"[\"",
")",
"[",
"0",
"]",
"settings",
"[",
"new_key",
"]",
"=",
"settings",
"[",
"key",
"]",
"else",
":",
"print",
"'Warning: Conditional keys not implemented, ignoring:'",
",",
"' '",
".",
"join",
"(",
"conditional_keys",
")",
"del",
"settings",
"[",
"key",
"]"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/xcode_emulation.py#L187-L202 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/compile_utils.py | python | LossesContainer.metrics | (self) | return [self._loss_metric] + per_output_metrics | Per-output loss metrics. | Per-output loss metrics. | [
"Per",
"-",
"output",
"loss",
"metrics",
"."
] | def metrics(self):
"""Per-output loss metrics."""
if not self._built:
return []
per_output_metrics = [
metric_obj for metric_obj in nest.flatten(self._per_output_metrics)
if metric_obj is not None
]
return [self._loss_metric] + per_output_metrics | [
"def",
"metrics",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_built",
":",
"return",
"[",
"]",
"per_output_metrics",
"=",
"[",
"metric_obj",
"for",
"metric_obj",
"in",
"nest",
".",
"flatten",
"(",
"self",
".",
"_per_output_metrics",
")",
"if",
"metric_obj",
"is",
"not",
"None",
"]",
"return",
"[",
"self",
".",
"_loss_metric",
"]",
"+",
"per_output_metrics"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/compile_utils.py#L120-L128 | |
lmb-freiburg/ogn | 974f72ef4bf840d6f6693d22d1843a79223e77ce | scripts/cpp_lint.py | python | _CppLintState.SetCountingStyle | (self, counting_style) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style | [
"def",
"SetCountingStyle",
"(",
"self",
",",
"counting_style",
")",
":",
"self",
".",
"counting",
"=",
"counting_style"
] | https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/scripts/cpp_lint.py#L713-L715 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | Decimal.copy_abs | (self) | return _dec_from_triple(0, self._int, self._exp, self._is_special) | Returns a copy with the sign set to 0. | Returns a copy with the sign set to 0. | [
"Returns",
"a",
"copy",
"with",
"the",
"sign",
"set",
"to",
"0",
"."
] | def copy_abs(self):
"""Returns a copy with the sign set to 0. """
return _dec_from_triple(0, self._int, self._exp, self._is_special) | [
"def",
"copy_abs",
"(",
"self",
")",
":",
"return",
"_dec_from_triple",
"(",
"0",
",",
"self",
".",
"_int",
",",
"self",
".",
"_exp",
",",
"self",
".",
"_is_special",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L2915-L2917 | |
LLNL/Caliper | 60e06980fc65057e1da01296e6eebbbed30f59c8 | src/mpi/services/mpiwrap/wrap.py | python | Chunk.evaluate | (self, out, scope) | This is an 'interactive' version of execute. This should be called when
the chunk's value (if any) should be written out. Body macros and the outermost
scope should use this instead of execute(). | This is an 'interactive' version of execute. This should be called when
the chunk's value (if any) should be written out. Body macros and the outermost
scope should use this instead of execute(). | [
"This",
"is",
"an",
"interactive",
"version",
"of",
"execute",
".",
"This",
"should",
"be",
"called",
"when",
"the",
"chunk",
"s",
"value",
"(",
"if",
"any",
")",
"should",
"be",
"written",
"out",
".",
"Body",
"macros",
"and",
"the",
"outermost",
"scope",
"should",
"use",
"this",
"instead",
"of",
"execute",
"()",
"."
] | def evaluate(self, out, scope):
"""This is an 'interactive' version of execute. This should be called when
the chunk's value (if any) should be written out. Body macros and the outermost
scope should use this instead of execute().
"""
value = self.execute(out, scope)
if value is not None: # Note the distinction here -- 0 is false but we want to print it!
out.write(self.stringify(value)) | [
"def",
"evaluate",
"(",
"self",
",",
"out",
",",
"scope",
")",
":",
"value",
"=",
"self",
".",
"execute",
"(",
"out",
",",
"scope",
")",
"if",
"value",
"is",
"not",
"None",
":",
"# Note the distinction here -- 0 is false but we want to print it!",
"out",
".",
"write",
"(",
"self",
".",
"stringify",
"(",
"value",
")",
")"
] | https://github.com/LLNL/Caliper/blob/60e06980fc65057e1da01296e6eebbbed30f59c8/src/mpi/services/mpiwrap/wrap.py#L1179-L1186 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/_remove_redundancy.py | python | _remove_redundancy_sparse | (A, rhs) | return A_orig[keep, :], rhs[keep], status, message | Eliminates redundant equations from system of equations defined by Ax = b
and identifies infeasibilities.
Parameters
----------
A : 2-D sparse matrix
An matrix representing the left-hand side of a system of equations
rhs : 1-D array
An array representing the right-hand side of a system of equations
Returns
-------
A : 2-D sparse matrix
A matrix representing the left-hand side of a system of equations
rhs : 1-D array
An array representing the right-hand side of a system of equations
status: int
An integer indicating the status of the system
0: No infeasibility identified
2: Trivially infeasible
message : str
A string descriptor of the exit status of the optimization.
References
----------
.. [2] Andersen, Erling D. "Finding all linearly dependent rows in
large-scale linear programming." Optimization Methods and Software
6.3 (1995): 219-227. | Eliminates redundant equations from system of equations defined by Ax = b
and identifies infeasibilities. | [
"Eliminates",
"redundant",
"equations",
"from",
"system",
"of",
"equations",
"defined",
"by",
"Ax",
"=",
"b",
"and",
"identifies",
"infeasibilities",
"."
] | def _remove_redundancy_sparse(A, rhs):
"""
Eliminates redundant equations from system of equations defined by Ax = b
and identifies infeasibilities.
Parameters
----------
A : 2-D sparse matrix
An matrix representing the left-hand side of a system of equations
rhs : 1-D array
An array representing the right-hand side of a system of equations
Returns
-------
A : 2-D sparse matrix
A matrix representing the left-hand side of a system of equations
rhs : 1-D array
An array representing the right-hand side of a system of equations
status: int
An integer indicating the status of the system
0: No infeasibility identified
2: Trivially infeasible
message : str
A string descriptor of the exit status of the optimization.
References
----------
.. [2] Andersen, Erling D. "Finding all linearly dependent rows in
large-scale linear programming." Optimization Methods and Software
6.3 (1995): 219-227.
"""
tolapiv = 1e-8
tolprimal = 1e-8
status = 0
message = ""
inconsistent = ("There is a linear combination of rows of A_eq that "
"results in zero, suggesting a redundant constraint. "
"However the same linear combination of b_eq is "
"nonzero, suggesting that the constraints conflict "
"and the problem is infeasible.")
A, rhs, status, message = _remove_zero_rows(A, rhs)
if status != 0:
return A, rhs, status, message
m, n = A.shape
v = list(range(m)) # Artificial column indices.
b = list(v) # Basis column indices.
# This is better as a list than a set because column order of basis matrix
# needs to be consistent.
k = set(range(m, m+n)) # Structural column indices.
d = [] # Indices of dependent rows
A_orig = A
A = scipy.sparse.hstack((scipy.sparse.eye(m), A)).tocsc()
e = np.zeros(m)
# Implements basic algorithm from [2]
# Uses only one of the suggested improvements (removing zero rows).
# Removing column singletons would be easy, but it is not as important
# because the procedure is performed only on the equality constraint
# matrix from the original problem - not on the canonical form matrix,
# which would have many more column singletons due to slack variables
# from the inequality constraints.
# The thoughts on "crashing" the initial basis sound useful, but the
# description of the procedure seems to assume a lot of familiarity with
# the subject; it is not very explicit. I already went through enough
# trouble getting the basic algorithm working, so I was not interested in
# trying to decipher this, too. (Overall, the paper is fraught with
# mistakes and ambiguities - which is strange, because the rest of
# Andersen's papers are quite good.)
# I tried and tried and tried to improve performance using the
# Bartels-Golub update. It works, but it's only practical if the LU
# factorization can be specialized as described, and that is not possible
# until the Scipy SuperLU interface permits control over column
# permutation - see issue #7700.
for i in v:
B = A[:, b]
e[i] = 1
if i > 0:
e[i-1] = 0
pi = scipy.sparse.linalg.spsolve(B.transpose(), e).reshape(-1, 1)
js = list(k-set(b)) # not efficient, but this is not the time sink...
# Due to overhead, it tends to be faster (for problems tested) to
# compute the full matrix-vector product rather than individual
# vector-vector products (with the chance of terminating as soon
# as any are nonzero). For very large matrices, it might be worth
# it to compute, say, 100 or 1000 at a time and stop when a nonzero
# is found.
c = (np.abs(A[:, js].transpose().dot(pi)) > tolapiv).nonzero()[0]
if len(c) > 0: # independent
j = js[c[0]]
# in a previous commit, the previous line was changed to choose
# index j corresponding with the maximum dot product.
# While this avoided issues with almost
# singular matrices, it slowed the routine in most NETLIB tests.
# I think this is because these columns were denser than the
# first column with nonzero dot product (c[0]).
# It would be nice to have a heuristic that balances sparsity with
# high dot product, but I don't think it's worth the time to
# develop one right now. Bartels-Golub update is a much higher
# priority.
b[i] = j # replace artificial column
else:
bibar = pi.T.dot(rhs.reshape(-1, 1))
bnorm = np.linalg.norm(rhs)
if abs(bibar)/(1 + bnorm) > tolprimal:
status = 2
message = inconsistent
return A_orig, rhs, status, message
else: # dependent
d.append(i)
keep = set(range(m))
keep = list(keep - set(d))
return A_orig[keep, :], rhs[keep], status, message | [
"def",
"_remove_redundancy_sparse",
"(",
"A",
",",
"rhs",
")",
":",
"tolapiv",
"=",
"1e-8",
"tolprimal",
"=",
"1e-8",
"status",
"=",
"0",
"message",
"=",
"\"\"",
"inconsistent",
"=",
"(",
"\"There is a linear combination of rows of A_eq that \"",
"\"results in zero, suggesting a redundant constraint. \"",
"\"However the same linear combination of b_eq is \"",
"\"nonzero, suggesting that the constraints conflict \"",
"\"and the problem is infeasible.\"",
")",
"A",
",",
"rhs",
",",
"status",
",",
"message",
"=",
"_remove_zero_rows",
"(",
"A",
",",
"rhs",
")",
"if",
"status",
"!=",
"0",
":",
"return",
"A",
",",
"rhs",
",",
"status",
",",
"message",
"m",
",",
"n",
"=",
"A",
".",
"shape",
"v",
"=",
"list",
"(",
"range",
"(",
"m",
")",
")",
"# Artificial column indices.",
"b",
"=",
"list",
"(",
"v",
")",
"# Basis column indices.",
"# This is better as a list than a set because column order of basis matrix",
"# needs to be consistent.",
"k",
"=",
"set",
"(",
"range",
"(",
"m",
",",
"m",
"+",
"n",
")",
")",
"# Structural column indices.",
"d",
"=",
"[",
"]",
"# Indices of dependent rows",
"A_orig",
"=",
"A",
"A",
"=",
"scipy",
".",
"sparse",
".",
"hstack",
"(",
"(",
"scipy",
".",
"sparse",
".",
"eye",
"(",
"m",
")",
",",
"A",
")",
")",
".",
"tocsc",
"(",
")",
"e",
"=",
"np",
".",
"zeros",
"(",
"m",
")",
"# Implements basic algorithm from [2]",
"# Uses only one of the suggested improvements (removing zero rows).",
"# Removing column singletons would be easy, but it is not as important",
"# because the procedure is performed only on the equality constraint",
"# matrix from the original problem - not on the canonical form matrix,",
"# which would have many more column singletons due to slack variables",
"# from the inequality constraints.",
"# The thoughts on \"crashing\" the initial basis sound useful, but the",
"# description of the procedure seems to assume a lot of familiarity with",
"# the subject; it is not very explicit. I already went through enough",
"# trouble getting the basic algorithm working, so I was not interested in",
"# trying to decipher this, too. (Overall, the paper is fraught with",
"# mistakes and ambiguities - which is strange, because the rest of",
"# Andersen's papers are quite good.)",
"# I tried and tried and tried to improve performance using the",
"# Bartels-Golub update. It works, but it's only practical if the LU",
"# factorization can be specialized as described, and that is not possible",
"# until the Scipy SuperLU interface permits control over column",
"# permutation - see issue #7700.",
"for",
"i",
"in",
"v",
":",
"B",
"=",
"A",
"[",
":",
",",
"b",
"]",
"e",
"[",
"i",
"]",
"=",
"1",
"if",
"i",
">",
"0",
":",
"e",
"[",
"i",
"-",
"1",
"]",
"=",
"0",
"pi",
"=",
"scipy",
".",
"sparse",
".",
"linalg",
".",
"spsolve",
"(",
"B",
".",
"transpose",
"(",
")",
",",
"e",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"js",
"=",
"list",
"(",
"k",
"-",
"set",
"(",
"b",
")",
")",
"# not efficient, but this is not the time sink...",
"# Due to overhead, it tends to be faster (for problems tested) to",
"# compute the full matrix-vector product rather than individual",
"# vector-vector products (with the chance of terminating as soon",
"# as any are nonzero). For very large matrices, it might be worth",
"# it to compute, say, 100 or 1000 at a time and stop when a nonzero",
"# is found.",
"c",
"=",
"(",
"np",
".",
"abs",
"(",
"A",
"[",
":",
",",
"js",
"]",
".",
"transpose",
"(",
")",
".",
"dot",
"(",
"pi",
")",
")",
">",
"tolapiv",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"c",
")",
">",
"0",
":",
"# independent",
"j",
"=",
"js",
"[",
"c",
"[",
"0",
"]",
"]",
"# in a previous commit, the previous line was changed to choose",
"# index j corresponding with the maximum dot product.",
"# While this avoided issues with almost",
"# singular matrices, it slowed the routine in most NETLIB tests.",
"# I think this is because these columns were denser than the",
"# first column with nonzero dot product (c[0]).",
"# It would be nice to have a heuristic that balances sparsity with",
"# high dot product, but I don't think it's worth the time to",
"# develop one right now. Bartels-Golub update is a much higher",
"# priority.",
"b",
"[",
"i",
"]",
"=",
"j",
"# replace artificial column",
"else",
":",
"bibar",
"=",
"pi",
".",
"T",
".",
"dot",
"(",
"rhs",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
")",
"bnorm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"rhs",
")",
"if",
"abs",
"(",
"bibar",
")",
"/",
"(",
"1",
"+",
"bnorm",
")",
">",
"tolprimal",
":",
"status",
"=",
"2",
"message",
"=",
"inconsistent",
"return",
"A_orig",
",",
"rhs",
",",
"status",
",",
"message",
"else",
":",
"# dependent",
"d",
".",
"append",
"(",
"i",
")",
"keep",
"=",
"set",
"(",
"range",
"(",
"m",
")",
")",
"keep",
"=",
"list",
"(",
"keep",
"-",
"set",
"(",
"d",
")",
")",
"return",
"A_orig",
"[",
"keep",
",",
":",
"]",
",",
"rhs",
"[",
"keep",
"]",
",",
"status",
",",
"message"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_remove_redundancy.py#L235-L359 | |
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | scripts/cpp_lint.py | python | ParseArguments | (args) | return filenames | Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint. | Parses the command line arguments. | [
"Parses",
"the",
"command",
"line",
"arguments",
"."
] | def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
'linelength=',
'extensions='])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
filters = val
if not filters:
PrintCategories()
elif opt == '--counting':
if val not in ('total', 'toplevel', 'detailed'):
PrintUsage('Valid counting options are total, toplevel, and detailed')
counting_style = val
elif opt == '--root':
global _root
_root = val
elif opt == '--linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage('Line length must be digits.')
elif opt == '--extensions':
global _valid_extensions
try:
_valid_extensions = set(val.split(','))
except ValueError:
PrintUsage('Extensions must be comma separated list.')
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames | [
"def",
"ParseArguments",
"(",
"args",
")",
":",
"try",
":",
"(",
"opts",
",",
"filenames",
")",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"''",
",",
"[",
"'help'",
",",
"'output='",
",",
"'verbose='",
",",
"'counting='",
",",
"'filter='",
",",
"'root='",
",",
"'linelength='",
",",
"'extensions='",
"]",
")",
"except",
"getopt",
".",
"GetoptError",
":",
"PrintUsage",
"(",
"'Invalid arguments.'",
")",
"verbosity",
"=",
"_VerboseLevel",
"(",
")",
"output_format",
"=",
"_OutputFormat",
"(",
")",
"filters",
"=",
"''",
"counting_style",
"=",
"''",
"for",
"(",
"opt",
",",
"val",
")",
"in",
"opts",
":",
"if",
"opt",
"==",
"'--help'",
":",
"PrintUsage",
"(",
"None",
")",
"elif",
"opt",
"==",
"'--output'",
":",
"if",
"val",
"not",
"in",
"(",
"'emacs'",
",",
"'vs7'",
",",
"'eclipse'",
")",
":",
"PrintUsage",
"(",
"'The only allowed output formats are emacs, vs7 and eclipse.'",
")",
"output_format",
"=",
"val",
"elif",
"opt",
"==",
"'--verbose'",
":",
"verbosity",
"=",
"int",
"(",
"val",
")",
"elif",
"opt",
"==",
"'--filter'",
":",
"filters",
"=",
"val",
"if",
"not",
"filters",
":",
"PrintCategories",
"(",
")",
"elif",
"opt",
"==",
"'--counting'",
":",
"if",
"val",
"not",
"in",
"(",
"'total'",
",",
"'toplevel'",
",",
"'detailed'",
")",
":",
"PrintUsage",
"(",
"'Valid counting options are total, toplevel, and detailed'",
")",
"counting_style",
"=",
"val",
"elif",
"opt",
"==",
"'--root'",
":",
"global",
"_root",
"_root",
"=",
"val",
"elif",
"opt",
"==",
"'--linelength'",
":",
"global",
"_line_length",
"try",
":",
"_line_length",
"=",
"int",
"(",
"val",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"'Line length must be digits.'",
")",
"elif",
"opt",
"==",
"'--extensions'",
":",
"global",
"_valid_extensions",
"try",
":",
"_valid_extensions",
"=",
"set",
"(",
"val",
".",
"split",
"(",
"','",
")",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"'Extensions must be comma separated list.'",
")",
"if",
"not",
"filenames",
":",
"PrintUsage",
"(",
"'No files were specified.'",
")",
"_SetOutputFormat",
"(",
"output_format",
")",
"_SetVerboseLevel",
"(",
"verbosity",
")",
"_SetFilters",
"(",
"filters",
")",
"_SetCountingStyle",
"(",
"counting_style",
")",
"return",
"filenames"
] | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/scripts/cpp_lint.py#L4779-L4846 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | Icon.SetDepth | (*args, **kwargs) | return _gdi_.Icon_SetDepth(*args, **kwargs) | SetDepth(self, int d) | SetDepth(self, int d) | [
"SetDepth",
"(",
"self",
"int",
"d",
")"
] | def SetDepth(*args, **kwargs):
"""SetDepth(self, int d)"""
return _gdi_.Icon_SetDepth(*args, **kwargs) | [
"def",
"SetDepth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Icon_SetDepth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L1308-L1310 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | GridCellAttr.HasFont | (*args, **kwargs) | return _grid.GridCellAttr_HasFont(*args, **kwargs) | HasFont(self) -> bool | HasFont(self) -> bool | [
"HasFont",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasFont(*args, **kwargs):
"""HasFont(self) -> bool"""
return _grid.GridCellAttr_HasFont(*args, **kwargs) | [
"def",
"HasFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridCellAttr_HasFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L591-L593 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py | python | Series.update | (self, other) | Modify Series in place using non-NA values from passed
Series. Aligns on index.
Parameters
----------
other : Series
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6]))
>>> s
0 4
1 5
2 6
dtype: int64
>>> s = pd.Series(['a', 'b', 'c'])
>>> s.update(pd.Series(['d', 'e'], index=[0, 2]))
>>> s
0 d
1 b
2 e
dtype: object
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6, 7, 8]))
>>> s
0 4
1 5
2 6
dtype: int64
If ``other`` contains NaNs the corresponding values are not updated
in the original Series.
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, np.nan, 6]))
>>> s
0 4
1 2
2 6
dtype: int64 | Modify Series in place using non-NA values from passed
Series. Aligns on index. | [
"Modify",
"Series",
"in",
"place",
"using",
"non",
"-",
"NA",
"values",
"from",
"passed",
"Series",
".",
"Aligns",
"on",
"index",
"."
] | def update(self, other):
"""
Modify Series in place using non-NA values from passed
Series. Aligns on index.
Parameters
----------
other : Series
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6]))
>>> s
0 4
1 5
2 6
dtype: int64
>>> s = pd.Series(['a', 'b', 'c'])
>>> s.update(pd.Series(['d', 'e'], index=[0, 2]))
>>> s
0 d
1 b
2 e
dtype: object
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6, 7, 8]))
>>> s
0 4
1 5
2 6
dtype: int64
If ``other`` contains NaNs the corresponding values are not updated
in the original Series.
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, np.nan, 6]))
>>> s
0 4
1 2
2 6
dtype: int64
"""
other = other.reindex_like(self)
mask = notna(other)
self._data = self._data.putmask(mask=mask, new=other, inplace=True)
self._maybe_update_cacher() | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"other",
".",
"reindex_like",
"(",
"self",
")",
"mask",
"=",
"notna",
"(",
"other",
")",
"self",
".",
"_data",
"=",
"self",
".",
"_data",
".",
"putmask",
"(",
"mask",
"=",
"mask",
",",
"new",
"=",
"other",
",",
"inplace",
"=",
"True",
")",
"self",
".",
"_maybe_update_cacher",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py#L2761-L2811 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.