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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15172658790/Blog | 46e5036f5fbcad535af2255dc0e095cebcd8d710 | 数学类/计算方法/code/第0章 绪论/vector_norm.py | python | matrix.__init__ | (self,s) | s is a list of lists | s is a list of lists | [
"s",
"is",
"a",
"list",
"of",
"lists"
] | def __init__(self,s):
'''s is a list of lists'''
self.data=np.mat(s)
self.T = None
self. I = None | [
"def",
"__init__",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"data",
"=",
"np",
".",
"mat",
"(",
"s",
")",
"self",
".",
"T",
"=",
"None",
"self",
".",
"I",
"=",
"None"
] | https://github.com/15172658790/Blog/blob/46e5036f5fbcad535af2255dc0e095cebcd8d710/数学类/计算方法/code/第0章 绪论/vector_norm.py#L73-L77 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/_polybase.py | python | ABCPolyBase.copy | (self) | return self.__class__(self.coef, self.domain, self.window) | Return a copy.
Returns
-------
new_series : series
Copy of self. | Return a copy. | [
"Return",
"a",
"copy",
"."
] | def copy(self):
"""Return a copy.
Returns
-------
new_series : series
Copy of self.
"""
return self.__class__(self.coef, self.domain, self.window) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"coef",
",",
"self",
".",
"domain",
",",
"self",
".",
"window",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/_polybase.py#L631-L640 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/__init__.py | python | Pool | (processes=None, initializer=None, initargs=(), maxtasksperchild=None) | return Pool(processes, initializer, initargs, maxtasksperchild) | Returns a process pool object | Returns a process pool object | [
"Returns",
"a",
"process",
"pool",
"object"
] | def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None):
'''
Returns a process pool object
'''
from multiprocessing.pool import Pool
return Pool(processes, initializer, initargs, maxtasksperchild) | [
"def",
"Pool",
"(",
"processes",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"initargs",
"=",
"(",
")",
",",
"maxtasksperchild",
"=",
"None",
")",
":",
"from",
"multiprocessing",
".",
"pool",
"import",
"Pool",
"return",
"Pool",
"(",
"processes",
",",
"initializer",
",",
"initargs",
",",
"maxtasksperchild",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/__init__.py#L227-L232 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/autograd/profiler_util.py | python | FunctionEvent.set_cpu_parent | (self, parent) | Set the immediate CPU parent of type FunctionEvent
One profiling FunctionEvent should have only one CPU parent such that
the child's range interval is completely inside the parent's. We use
this connection to determine the event is from top-level op or not. | Set the immediate CPU parent of type FunctionEvent | [
"Set",
"the",
"immediate",
"CPU",
"parent",
"of",
"type",
"FunctionEvent"
] | def set_cpu_parent(self, parent):
"""Set the immediate CPU parent of type FunctionEvent
One profiling FunctionEvent should have only one CPU parent such that
the child's range interval is completely inside the parent's. We use
this connection to determine the event is from top-level op or not.
"""
assert(self.device_type == DeviceType.CPU)
assert(isinstance(parent, FunctionEvent))
assert(parent.device_type == DeviceType.CPU)
self.cpu_parent = parent | [
"def",
"set_cpu_parent",
"(",
"self",
",",
"parent",
")",
":",
"assert",
"(",
"self",
".",
"device_type",
"==",
"DeviceType",
".",
"CPU",
")",
"assert",
"(",
"isinstance",
"(",
"parent",
",",
"FunctionEvent",
")",
")",
"assert",
"(",
"parent",
".",
"device_type",
"==",
"DeviceType",
".",
"CPU",
")",
"self",
".",
"cpu_parent",
"=",
"parent"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/autograd/profiler_util.py#L418-L428 | ||
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/build/lib.linux-x86_64-2.7/mxnet/kvstore_server.py | python | KVStoreServer._controller | (self) | return server_controller | return the server controller | return the server controller | [
"return",
"the",
"server",
"controller"
] | def _controller(self):
"""return the server controller"""
def server_controller(cmd_id, cmd_body):
"""server controler"""
if self.init_logginig == False:
# the reason put the codes here is because we cannot get
# kvstore.rank earlier
head = '%(asctime)-15s Server[' + str(
self.kvstore.rank) + '] %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
self.init_logginig = True
if cmd_id == 0:
try:
optimizer = pickle.loads(cmd_body)
except:
raise
self.kvstore.set_optimizer(optimizer)
else:
print ("server %d, unknown command (%d, %s)" % (
self.kvstore.rank, cmd_id, cmd_body))
return server_controller | [
"def",
"_controller",
"(",
"self",
")",
":",
"def",
"server_controller",
"(",
"cmd_id",
",",
"cmd_body",
")",
":",
"\"\"\"server controler\"\"\"",
"if",
"self",
".",
"init_logginig",
"==",
"False",
":",
"# the reason put the codes here is because we cannot get",
"# kvstore.rank earlier",
"head",
"=",
"'%(asctime)-15s Server['",
"+",
"str",
"(",
"self",
".",
"kvstore",
".",
"rank",
")",
"+",
"'] %(message)s'",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
",",
"format",
"=",
"head",
")",
"self",
".",
"init_logginig",
"=",
"True",
"if",
"cmd_id",
"==",
"0",
":",
"try",
":",
"optimizer",
"=",
"pickle",
".",
"loads",
"(",
"cmd_body",
")",
"except",
":",
"raise",
"self",
".",
"kvstore",
".",
"set_optimizer",
"(",
"optimizer",
")",
"else",
":",
"print",
"(",
"\"server %d, unknown command (%d, %s)\"",
"%",
"(",
"self",
".",
"kvstore",
".",
"rank",
",",
"cmd_id",
",",
"cmd_body",
")",
")",
"return",
"server_controller"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/kvstore_server.py#L23-L44 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/decimal.py | python | Context.to_integral_exact | (self, a) | return a.to_integral_exact(context=self) | Rounds to an integer.
When the operand has a negative exponent, the result is the same
as using the quantize() operation using the given operand as the
left-hand-operand, 1E+0 as the right-hand-operand, and the precision
of the operand as the precision setting; Inexact and Rounded flags
are allowed in this operation. The rounding mode is taken from the
context.
>>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Decimal('2')
>>> ExtendedContext.to_integral_exact(Decimal('100'))
Decimal('100')
>>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Decimal('100')
>>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Decimal('102')
>>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Decimal('-102')
>>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Decimal('1.0E+6')
>>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Decimal('7.89E+77')
>>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Decimal('-Infinity') | Rounds to an integer. | [
"Rounds",
"to",
"an",
"integer",
"."
] | def to_integral_exact(self, a):
"""Rounds to an integer.
When the operand has a negative exponent, the result is the same
as using the quantize() operation using the given operand as the
left-hand-operand, 1E+0 as the right-hand-operand, and the precision
of the operand as the precision setting; Inexact and Rounded flags
are allowed in this operation. The rounding mode is taken from the
context.
>>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Decimal('2')
>>> ExtendedContext.to_integral_exact(Decimal('100'))
Decimal('100')
>>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Decimal('100')
>>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Decimal('102')
>>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Decimal('-102')
>>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Decimal('1.0E+6')
>>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Decimal('7.89E+77')
>>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Decimal('-Infinity')
"""
a = _convert_other(a, raiseit=True)
return a.to_integral_exact(context=self) | [
"def",
"to_integral_exact",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"to_integral_exact",
"(",
"context",
"=",
"self",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L5376-L5404 | |
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/c64/sid.py | python | SID.set_raw_filter_control | (self, value) | Bit #0: 1 = Voice #1 filtered.
Bit #1: 1 = Voice #2 filtered.
Bit #2: 1 = Voice #3 filtered.
Bit #3: 1 = External voice filtered.
Bits #4-#7: Filter resonance. | Bit #0: 1 = Voice #1 filtered.
Bit #1: 1 = Voice #2 filtered.
Bit #2: 1 = Voice #3 filtered.
Bit #3: 1 = External voice filtered.
Bits #4-#7: Filter resonance. | [
"Bit",
"#0",
":",
"1",
"=",
"Voice",
"#1",
"filtered",
".",
"Bit",
"#1",
":",
"1",
"=",
"Voice",
"#2",
"filtered",
".",
"Bit",
"#2",
":",
"1",
"=",
"Voice",
"#3",
"filtered",
".",
"Bit",
"#3",
":",
"1",
"=",
"External",
"voice",
"filtered",
".",
"Bits",
"#4",
"-",
"#7",
":",
"Filter",
"resonance",
"."
] | def set_raw_filter_control(self, value):
"""
Bit #0: 1 = Voice #1 filtered.
Bit #1: 1 = Voice #2 filtered.
Bit #2: 1 = Voice #3 filtered.
Bit #3: 1 = External voice filtered.
Bits #4-#7: Filter resonance.
"""
self.raw_filter_control = value | [
"def",
"set_raw_filter_control",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"raw_filter_control",
"=",
"value"
] | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/c64/sid.py#L131-L139 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/graph_util.py | python | convert_variables_to_constants | (sess, input_graph_def, output_node_names,
variable_names_whitelist=None) | return output_graph_def | Replaces all the variables in a graph with constants of the same values.
If you have a trained graph containing Variable ops, it can be convenient to
convert them all to Const ops holding the same values. This makes it possible
to describe the network fully with a single GraphDef file, and allows the
removal of a lot of ops related to loading and saving the variables.
Args:
sess: Active TensorFlow session containing the variables.
input_graph_def: GraphDef object holding the network.
output_node_names: List of name strings for the result nodes of the graph.
variable_names_whitelist: The set of variable names to convert (by default,
all variables are converted).
Returns:
GraphDef containing a simplified version of the original. | Replaces all the variables in a graph with constants of the same values. | [
"Replaces",
"all",
"the",
"variables",
"in",
"a",
"graph",
"with",
"constants",
"of",
"the",
"same",
"values",
"."
] | def convert_variables_to_constants(sess, input_graph_def, output_node_names,
variable_names_whitelist=None):
"""Replaces all the variables in a graph with constants of the same values.
If you have a trained graph containing Variable ops, it can be convenient to
convert them all to Const ops holding the same values. This makes it possible
to describe the network fully with a single GraphDef file, and allows the
removal of a lot of ops related to loading and saving the variables.
Args:
sess: Active TensorFlow session containing the variables.
input_graph_def: GraphDef object holding the network.
output_node_names: List of name strings for the result nodes of the graph.
variable_names_whitelist: The set of variable names to convert (by default,
all variables are converted).
Returns:
GraphDef containing a simplified version of the original.
"""
found_variables = {}
variable_names = []
variable_dict_names = []
for node in input_graph_def.node:
if node.op == "Assign":
variable_name = node.input[0]
if (variable_names_whitelist is not None and
variable_name not in variable_names_whitelist):
continue
variable_dict_names.append(variable_name)
variable_names.append(variable_name + ":0")
if variable_names:
returned_variables = sess.run(variable_names)
else:
returned_variables = []
found_variables = dict(zip(variable_dict_names, returned_variables))
logging.info("Frozen %d variables." % len(returned_variables))
# This graph only includes the nodes needed to evaluate the output nodes, and
# removes unneeded nodes like those involved in saving and assignment.
inference_graph = extract_sub_graph(input_graph_def, output_node_names)
output_graph_def = graph_pb2.GraphDef()
how_many_converted = 0
for input_node in inference_graph.node:
output_node = graph_pb2.NodeDef()
if input_node.name in found_variables:
output_node.op = "Const"
output_node.name = input_node.name
dtype = input_node.attr["dtype"]
data = found_variables[input_node.name]
output_node.attr["dtype"].CopyFrom(dtype)
output_node.attr["value"].CopyFrom(attr_value_pb2.AttrValue(
tensor=tensor_util.make_tensor_proto(data,
dtype=dtype.type,
shape=data.shape)))
how_many_converted += 1
else:
output_node.CopyFrom(input_node)
output_graph_def.node.extend([output_node])
print("Converted %d variables to const ops." % how_many_converted)
return output_graph_def | [
"def",
"convert_variables_to_constants",
"(",
"sess",
",",
"input_graph_def",
",",
"output_node_names",
",",
"variable_names_whitelist",
"=",
"None",
")",
":",
"found_variables",
"=",
"{",
"}",
"variable_names",
"=",
"[",
"]",
"variable_dict_names",
"=",
"[",
"]",
"for",
"node",
"in",
"input_graph_def",
".",
"node",
":",
"if",
"node",
".",
"op",
"==",
"\"Assign\"",
":",
"variable_name",
"=",
"node",
".",
"input",
"[",
"0",
"]",
"if",
"(",
"variable_names_whitelist",
"is",
"not",
"None",
"and",
"variable_name",
"not",
"in",
"variable_names_whitelist",
")",
":",
"continue",
"variable_dict_names",
".",
"append",
"(",
"variable_name",
")",
"variable_names",
".",
"append",
"(",
"variable_name",
"+",
"\":0\"",
")",
"if",
"variable_names",
":",
"returned_variables",
"=",
"sess",
".",
"run",
"(",
"variable_names",
")",
"else",
":",
"returned_variables",
"=",
"[",
"]",
"found_variables",
"=",
"dict",
"(",
"zip",
"(",
"variable_dict_names",
",",
"returned_variables",
")",
")",
"logging",
".",
"info",
"(",
"\"Frozen %d variables.\"",
"%",
"len",
"(",
"returned_variables",
")",
")",
"# This graph only includes the nodes needed to evaluate the output nodes, and",
"# removes unneeded nodes like those involved in saving and assignment.",
"inference_graph",
"=",
"extract_sub_graph",
"(",
"input_graph_def",
",",
"output_node_names",
")",
"output_graph_def",
"=",
"graph_pb2",
".",
"GraphDef",
"(",
")",
"how_many_converted",
"=",
"0",
"for",
"input_node",
"in",
"inference_graph",
".",
"node",
":",
"output_node",
"=",
"graph_pb2",
".",
"NodeDef",
"(",
")",
"if",
"input_node",
".",
"name",
"in",
"found_variables",
":",
"output_node",
".",
"op",
"=",
"\"Const\"",
"output_node",
".",
"name",
"=",
"input_node",
".",
"name",
"dtype",
"=",
"input_node",
".",
"attr",
"[",
"\"dtype\"",
"]",
"data",
"=",
"found_variables",
"[",
"input_node",
".",
"name",
"]",
"output_node",
".",
"attr",
"[",
"\"dtype\"",
"]",
".",
"CopyFrom",
"(",
"dtype",
")",
"output_node",
".",
"attr",
"[",
"\"value\"",
"]",
".",
"CopyFrom",
"(",
"attr_value_pb2",
".",
"AttrValue",
"(",
"tensor",
"=",
"tensor_util",
".",
"make_tensor_proto",
"(",
"data",
",",
"dtype",
"=",
"dtype",
".",
"type",
",",
"shape",
"=",
"data",
".",
"shape",
")",
")",
")",
"how_many_converted",
"+=",
"1",
"else",
":",
"output_node",
".",
"CopyFrom",
"(",
"input_node",
")",
"output_graph_def",
".",
"node",
".",
"extend",
"(",
"[",
"output_node",
"]",
")",
"print",
"(",
"\"Converted %d variables to const ops.\"",
"%",
"how_many_converted",
")",
"return",
"output_graph_def"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/graph_util.py#L193-L253 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py | python | ExportSampleLogsToCSVFile.__init__ | (self) | return | Initialization
@return: | Initialization | [
"Initialization"
] | def __init__(self):
""" Initialization
@return:
"""
PythonAlgorithm.__init__(self)
return | [
"def",
"__init__",
"(",
"self",
")",
":",
"PythonAlgorithm",
".",
"__init__",
"(",
"self",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py#L35-L41 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | Joystick.HasZ | (*args, **kwargs) | return _misc_.Joystick_HasZ(*args, **kwargs) | HasZ(self) -> bool | HasZ(self) -> bool | [
"HasZ",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasZ(*args, **kwargs):
"""HasZ(self) -> bool"""
return _misc_.Joystick_HasZ(*args, **kwargs) | [
"def",
"HasZ",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Joystick_HasZ",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L2262-L2264 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/core/numerictypes.py | python | _scalar_type_key | (typ) | return (dt.kind.lower(), dt.itemsize) | A ``key`` function for `sorted`. | A ``key`` function for `sorted`. | [
"A",
"key",
"function",
"for",
"sorted",
"."
] | def _scalar_type_key(typ):
"""A ``key`` function for `sorted`."""
dt = dtype(typ)
return (dt.kind.lower(), dt.itemsize) | [
"def",
"_scalar_type_key",
"(",
"typ",
")",
":",
"dt",
"=",
"dtype",
"(",
"typ",
")",
"return",
"(",
"dt",
".",
"kind",
".",
"lower",
"(",
")",
",",
"dt",
".",
"itemsize",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/numerictypes.py#L515-L518 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | ArtProvider.GetMessageBoxIconId | (*args, **kwargs) | return _misc_.ArtProvider_GetMessageBoxIconId(*args, **kwargs) | GetMessageBoxIconId(int flags) -> wxArtID | GetMessageBoxIconId(int flags) -> wxArtID | [
"GetMessageBoxIconId",
"(",
"int",
"flags",
")",
"-",
">",
"wxArtID"
] | def GetMessageBoxIconId(*args, **kwargs):
"""GetMessageBoxIconId(int flags) -> wxArtID"""
return _misc_.ArtProvider_GetMessageBoxIconId(*args, **kwargs) | [
"def",
"GetMessageBoxIconId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"ArtProvider_GetMessageBoxIconId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L2839-L2841 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/stateless_random_ops.py | python | stateless_random_poisson | (shape,
seed,
lam,
dtype=dtypes.int32,
name=None) | Outputs deterministic pseudorandom values from a Poisson distribution.
The generated values follow a Poisson distribution with specified rate
parameter.
This is a stateless version of `tf.random.poisson`: if run twice with the same
seeds and shapes, it will produce the same pseudorandom numbers. The output is
consistent across multiple runs on the same hardware, but may change between
versions of TensorFlow or on non-CPU/GPU hardware.
A slight difference exists in the interpretation of the `shape` parameter
between `stateless_poisson` and `poisson`: in `poisson`, the `shape` is always
prepended to the shape of `lam`; whereas in `stateless_poisson` the shape of
`lam` must match the trailing dimensions of `shape`.
Example:
```python
samples = tf.random.stateless_poisson([10, 2], seed=[12, 34], lam=[5, 15])
# samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
# the samples drawn from each distribution
samples = tf.random.stateless_poisson([7, 5, 2], seed=[12, 34], lam=[5, 15])
# samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
# represents the 7x5 samples drawn from each of the two distributions
rate = tf.constant([[1.], [3.], [5.]])
samples = tf.random.stateless_poisson([30, 3, 1], seed=[12, 34], lam=rate)
# samples has shape [30, 3, 1], with 30 samples each of 3x1 distributions.
```
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
seed: A shape [2] Tensor, the seed to the random number generator. Must have
dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
lam: Tensor. The rate parameter "lambda" of the Poisson distribution. Shape
must match the rightmost dimensions of `shape`.
dtype: Dtype of the samples (int or float dtypes are permissible, as samples
are discrete). Default: int32.
name: A name for the operation (optional).
Returns:
samples: A Tensor of the specified shape filled with random Poisson values.
For each i, each `samples[..., i]` is an independent draw from the Poisson
distribution with rate `lam[i]`. | Outputs deterministic pseudorandom values from a Poisson distribution. | [
"Outputs",
"deterministic",
"pseudorandom",
"values",
"from",
"a",
"Poisson",
"distribution",
"."
] | def stateless_random_poisson(shape,
seed,
lam,
dtype=dtypes.int32,
name=None):
"""Outputs deterministic pseudorandom values from a Poisson distribution.
The generated values follow a Poisson distribution with specified rate
parameter.
This is a stateless version of `tf.random.poisson`: if run twice with the same
seeds and shapes, it will produce the same pseudorandom numbers. The output is
consistent across multiple runs on the same hardware, but may change between
versions of TensorFlow or on non-CPU/GPU hardware.
A slight difference exists in the interpretation of the `shape` parameter
between `stateless_poisson` and `poisson`: in `poisson`, the `shape` is always
prepended to the shape of `lam`; whereas in `stateless_poisson` the shape of
`lam` must match the trailing dimensions of `shape`.
Example:
```python
samples = tf.random.stateless_poisson([10, 2], seed=[12, 34], lam=[5, 15])
# samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
# the samples drawn from each distribution
samples = tf.random.stateless_poisson([7, 5, 2], seed=[12, 34], lam=[5, 15])
# samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
# represents the 7x5 samples drawn from each of the two distributions
rate = tf.constant([[1.], [3.], [5.]])
samples = tf.random.stateless_poisson([30, 3, 1], seed=[12, 34], lam=rate)
# samples has shape [30, 3, 1], with 30 samples each of 3x1 distributions.
```
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
seed: A shape [2] Tensor, the seed to the random number generator. Must have
dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
lam: Tensor. The rate parameter "lambda" of the Poisson distribution. Shape
must match the rightmost dimensions of `shape`.
dtype: Dtype of the samples (int or float dtypes are permissible, as samples
are discrete). Default: int32.
name: A name for the operation (optional).
Returns:
samples: A Tensor of the specified shape filled with random Poisson values.
For each i, each `samples[..., i]` is an independent draw from the Poisson
distribution with rate `lam[i]`.
"""
with ops.name_scope(name, "stateless_random_poisson",
[shape, seed, lam]) as name:
shape = tensor_util.shape_tensor(shape)
result = gen_stateless_random_ops.stateless_random_poisson(
shape, seed=seed, lam=lam, dtype=dtype)
tensor_util.maybe_set_static_shape(result, shape)
return result | [
"def",
"stateless_random_poisson",
"(",
"shape",
",",
"seed",
",",
"lam",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"stateless_random_poisson\"",
",",
"[",
"shape",
",",
"seed",
",",
"lam",
"]",
")",
"as",
"name",
":",
"shape",
"=",
"tensor_util",
".",
"shape_tensor",
"(",
"shape",
")",
"result",
"=",
"gen_stateless_random_ops",
".",
"stateless_random_poisson",
"(",
"shape",
",",
"seed",
"=",
"seed",
",",
"lam",
"=",
"lam",
",",
"dtype",
"=",
"dtype",
")",
"tensor_util",
".",
"maybe_set_static_shape",
"(",
"result",
",",
"shape",
")",
"return",
"result"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/stateless_random_ops.py#L539-L597 | ||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/tools/scan-build-py/libscanbuild/__init__.py | python | run_command | (command, cwd=None) | Run a given command and report the execution.
:param command: array of tokens
:param cwd: the working directory where the command will be executed
:return: output of the command | Run a given command and report the execution. | [
"Run",
"a",
"given",
"command",
"and",
"report",
"the",
"execution",
"."
] | def run_command(command, cwd=None):
""" Run a given command and report the execution.
:param command: array of tokens
:param cwd: the working directory where the command will be executed
:return: output of the command
"""
def decode_when_needed(result):
""" check_output returns bytes or string depend on python version """
return result.decode('utf-8') if isinstance(result, bytes) else result
try:
directory = os.path.abspath(cwd) if cwd else os.getcwd()
logging.debug('exec command %s in %s', command, directory)
output = subprocess.check_output(command,
cwd=directory,
stderr=subprocess.STDOUT)
return decode_when_needed(output).splitlines()
except subprocess.CalledProcessError as ex:
ex.output = decode_when_needed(ex.output).splitlines()
raise ex | [
"def",
"run_command",
"(",
"command",
",",
"cwd",
"=",
"None",
")",
":",
"def",
"decode_when_needed",
"(",
"result",
")",
":",
"\"\"\" check_output returns bytes or string depend on python version \"\"\"",
"return",
"result",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"result",
",",
"bytes",
")",
"else",
"result",
"try",
":",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"cwd",
")",
"if",
"cwd",
"else",
"os",
".",
"getcwd",
"(",
")",
"logging",
".",
"debug",
"(",
"'exec command %s in %s'",
",",
"command",
",",
"directory",
")",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"command",
",",
"cwd",
"=",
"directory",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"return",
"decode_when_needed",
"(",
"output",
")",
".",
"splitlines",
"(",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"ex",
":",
"ex",
".",
"output",
"=",
"decode_when_needed",
"(",
"ex",
".",
"output",
")",
".",
"splitlines",
"(",
")",
"raise",
"ex"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-build-py/libscanbuild/__init__.py#L60-L80 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | libVeles/cpplint.py | python | CheckAccess | (filename, clean_lines, linenum, nesting_state, error) | Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks for improper use of DISALLOW* macros. | [
"Checks",
"for",
"improper",
"use",
"of",
"DISALLOW",
"*",
"macros",
"."
] | def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
"""Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
r'DISALLOW_EVIL_CONSTRUCTORS|'
r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
if not matched:
return
if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
if nesting_state.stack[-1].access != 'private':
error(filename, linenum, 'readability/constructors', 3,
'%s must be in the private: section' % matched.group(1))
else:
# Found DISALLOW* macro outside a class declaration, or perhaps it
# was used inside a function when it should have been part of the
# class declaration. We could issue a warning here, but it
# probably resulted in a compiler error already.
pass | [
"def",
"CheckAccess",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# get rid of comments and strings",
"matched",
"=",
"Match",
"(",
"(",
"r'\\s*(DISALLOW_COPY_AND_ASSIGN|'",
"r'DISALLOW_EVIL_CONSTRUCTORS|'",
"r'DISALLOW_IMPLICIT_CONSTRUCTORS)'",
")",
",",
"line",
")",
"if",
"not",
"matched",
":",
"return",
"if",
"nesting_state",
".",
"stack",
"and",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_ClassInfo",
")",
":",
"if",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"access",
"!=",
"'private'",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/constructors'",
",",
"3",
",",
"'%s must be in the private: section'",
"%",
"matched",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"# Found DISALLOW* macro outside a class declaration, or perhaps it",
"# was used inside a function when it should have been part of the",
"# class declaration. We could issue a warning here, but it",
"# probably resulted in a compiler error already.",
"pass"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/libVeles/cpplint.py#L2043-L2071 | ||
hszhao/PSPNet | cf7e5a99ba37e46118026e96be5821a9bc63bde0 | scripts/cpp_lint.py | python | FindEndOfExpressionInLine | (line, startpos, depth, startchar, endchar) | return (-1, depth) | Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching endchar: (index just after matching endchar, 0)
Otherwise: (-1, new depth at end of this line) | Find the position just after the matching endchar. | [
"Find",
"the",
"position",
"just",
"after",
"the",
"matching",
"endchar",
"."
] | def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
"""Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching endchar: (index just after matching endchar, 0)
Otherwise: (-1, new depth at end of this line)
"""
for i in xrange(startpos, len(line)):
if line[i] == startchar:
depth += 1
elif line[i] == endchar:
depth -= 1
if depth == 0:
return (i + 1, 0)
return (-1, depth) | [
"def",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"startpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"startpos",
",",
"len",
"(",
"line",
")",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"startchar",
":",
"depth",
"+=",
"1",
"elif",
"line",
"[",
"i",
"]",
"==",
"endchar",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"return",
"(",
"i",
"+",
"1",
",",
"0",
")",
"return",
"(",
"-",
"1",
",",
"depth",
")"
] | https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L1230-L1251 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/insert-delete-getrandom-o1.py | python | RandomizedSet.insert | (self, val) | return True | Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool | Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool | [
"Inserts",
"a",
"value",
"to",
"the",
"set",
".",
"Returns",
"true",
"if",
"the",
"set",
"did",
"not",
"already",
"contain",
"the",
"specified",
"element",
".",
":",
"type",
"val",
":",
"int",
":",
"rtype",
":",
"bool"
] | def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.__used:
return False
self.__set += val,
self.__used[val] = len(self.__set)-1
return True | [
"def",
"insert",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
"in",
"self",
".",
"__used",
":",
"return",
"False",
"self",
".",
"__set",
"+=",
"val",
",",
"self",
".",
"__used",
"[",
"val",
"]",
"=",
"len",
"(",
"self",
".",
"__set",
")",
"-",
"1",
"return",
"True"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/insert-delete-getrandom-o1.py#L16-L28 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Signature/DSS.py | python | FipsEcDsaSigScheme._valid_hash | (self, msg_hash) | Verify that SHA-[23] (256|384|512) bits are used to
match the security of P-256 (128 bits), P-384 (192 bits)
or P-521 (256 bits) | Verify that SHA-[23] (256|384|512) bits are used to
match the security of P-256 (128 bits), P-384 (192 bits)
or P-521 (256 bits) | [
"Verify",
"that",
"SHA",
"-",
"[",
"23",
"]",
"(",
"256|384|512",
")",
"bits",
"are",
"used",
"to",
"match",
"the",
"security",
"of",
"P",
"-",
"256",
"(",
"128",
"bits",
")",
"P",
"-",
"384",
"(",
"192",
"bits",
")",
"or",
"P",
"-",
"521",
"(",
"256",
"bits",
")"
] | def _valid_hash(self, msg_hash):
"""Verify that SHA-[23] (256|384|512) bits are used to
match the security of P-256 (128 bits), P-384 (192 bits)
or P-521 (256 bits)"""
modulus_bits = self._key.pointQ.size_in_bits()
sha256 = ( "2.16.840.1.101.3.4.2.1", "2.16.840.1.101.3.4.2.8" )
sha384 = ( "2.16.840.1.101.3.4.2.2", "2.16.840.1.101.3.4.2.9" )
sha512 = ( "2.16.840.1.101.3.4.2.3", "2.16.840.1.101.3.4.2.10")
if msg_hash.oid in sha256:
return modulus_bits <= 256
elif msg_hash.oid in sha384:
return modulus_bits <= 384
else:
return msg_hash.oid in sha512 | [
"def",
"_valid_hash",
"(",
"self",
",",
"msg_hash",
")",
":",
"modulus_bits",
"=",
"self",
".",
"_key",
".",
"pointQ",
".",
"size_in_bits",
"(",
")",
"sha256",
"=",
"(",
"\"2.16.840.1.101.3.4.2.1\"",
",",
"\"2.16.840.1.101.3.4.2.8\"",
")",
"sha384",
"=",
"(",
"\"2.16.840.1.101.3.4.2.2\"",
",",
"\"2.16.840.1.101.3.4.2.9\"",
")",
"sha512",
"=",
"(",
"\"2.16.840.1.101.3.4.2.3\"",
",",
"\"2.16.840.1.101.3.4.2.10\"",
")",
"if",
"msg_hash",
".",
"oid",
"in",
"sha256",
":",
"return",
"modulus_bits",
"<=",
"256",
"elif",
"msg_hash",
".",
"oid",
"in",
"sha384",
":",
"return",
"modulus_bits",
"<=",
"384",
"else",
":",
"return",
"msg_hash",
".",
"oid",
"in",
"sha512"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Signature/DSS.py#L292-L308 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/sdist.py | python | sdist.check_license | (self) | Checks if license_file' or 'license_files' is configured and adds any
valid paths to 'self.filelist'. | Checks if license_file' or 'license_files' is configured and adds any
valid paths to 'self.filelist'. | [
"Checks",
"if",
"license_file",
"or",
"license_files",
"is",
"configured",
"and",
"adds",
"any",
"valid",
"paths",
"to",
"self",
".",
"filelist",
"."
] | def check_license(self):
"""Checks if license_file' or 'license_files' is configured and adds any
valid paths to 'self.filelist'.
"""
files = ordered_set.OrderedSet()
opts = self.distribution.get_option_dict('metadata')
# ignore the source of the value
_, license_file = opts.get('license_file', (None, None))
if license_file is None:
log.debug("'license_file' option was not specified")
else:
files.add(license_file)
try:
files.update(self.distribution.metadata.license_files)
except TypeError:
log.warn("warning: 'license_files' option is malformed")
for f in files:
if not os.path.exists(f):
log.warn(
"warning: Failed to find the configured license file '%s'",
f)
files.remove(f)
self.filelist.extend(files) | [
"def",
"check_license",
"(",
"self",
")",
":",
"files",
"=",
"ordered_set",
".",
"OrderedSet",
"(",
")",
"opts",
"=",
"self",
".",
"distribution",
".",
"get_option_dict",
"(",
"'metadata'",
")",
"# ignore the source of the value",
"_",
",",
"license_file",
"=",
"opts",
".",
"get",
"(",
"'license_file'",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"license_file",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"\"'license_file' option was not specified\"",
")",
"else",
":",
"files",
".",
"add",
"(",
"license_file",
")",
"try",
":",
"files",
".",
"update",
"(",
"self",
".",
"distribution",
".",
"metadata",
".",
"license_files",
")",
"except",
"TypeError",
":",
"log",
".",
"warn",
"(",
"\"warning: 'license_files' option is malformed\"",
")",
"for",
"f",
"in",
"files",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"f",
")",
":",
"log",
".",
"warn",
"(",
"\"warning: Failed to find the configured license file '%s'\"",
",",
"f",
")",
"files",
".",
"remove",
"(",
"f",
")",
"self",
".",
"filelist",
".",
"extend",
"(",
"files",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/sdist.py#L223-L252 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/common/extensions/docs/server2/schema_util.py | python | RemoveNoDocs | (item) | return False | Removes nodes that should not be rendered from an API schema. | Removes nodes that should not be rendered from an API schema. | [
"Removes",
"nodes",
"that",
"should",
"not",
"be",
"rendered",
"from",
"an",
"API",
"schema",
"."
] | def RemoveNoDocs(item):
'''Removes nodes that should not be rendered from an API schema.
'''
if json_parse.IsDict(item):
if item.get('nodoc', False):
return True
for key, value in item.items():
if RemoveNoDocs(value):
del item[key]
elif type(item) == list:
to_remove = []
for i in item:
if RemoveNoDocs(i):
to_remove.append(i)
for i in to_remove:
item.remove(i)
return False | [
"def",
"RemoveNoDocs",
"(",
"item",
")",
":",
"if",
"json_parse",
".",
"IsDict",
"(",
"item",
")",
":",
"if",
"item",
".",
"get",
"(",
"'nodoc'",
",",
"False",
")",
":",
"return",
"True",
"for",
"key",
",",
"value",
"in",
"item",
".",
"items",
"(",
")",
":",
"if",
"RemoveNoDocs",
"(",
"value",
")",
":",
"del",
"item",
"[",
"key",
"]",
"elif",
"type",
"(",
"item",
")",
"==",
"list",
":",
"to_remove",
"=",
"[",
"]",
"for",
"i",
"in",
"item",
":",
"if",
"RemoveNoDocs",
"(",
"i",
")",
":",
"to_remove",
".",
"append",
"(",
"i",
")",
"for",
"i",
"in",
"to_remove",
":",
"item",
".",
"remove",
"(",
"i",
")",
"return",
"False"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/schema_util.py#L11-L27 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/layers/python/layers/layers.py | python | repeat | (inputs, repetitions, layer, *args, **kwargs) | Applies the same layer with the same arguments repeatedly.
```python
y = repeat(x, 3, conv2d, 64, [3, 3], scope='conv1')
# It is equivalent to:
x = conv2d(x, 64, [3, 3], scope='conv1/conv1_1')
x = conv2d(x, 64, [3, 3], scope='conv1/conv1_2')
y = conv2d(x, 64, [3, 3], scope='conv1/conv1_3')
```
If the `scope` argument is not given in `kwargs`, it is set to
`layer.__name__`, or `layer.func.__name__` (for `functools.partial`
objects). If neither `__name__` nor `func.__name__` is available, the
layers are called with `scope='stack'`.
Args:
inputs: A `Tensor` suitable for layer.
repetitions: Int, number of repetitions.
layer: A layer with arguments `(inputs, *args, **kwargs)`
*args: Extra args for the layer.
**kwargs: Extra kwargs for the layer.
Returns:
A tensor result of applying the layer, repetitions times.
Raises:
ValueError: If the op is unknown or wrong. | Applies the same layer with the same arguments repeatedly. | [
"Applies",
"the",
"same",
"layer",
"with",
"the",
"same",
"arguments",
"repeatedly",
"."
] | def repeat(inputs, repetitions, layer, *args, **kwargs):
"""Applies the same layer with the same arguments repeatedly.
```python
y = repeat(x, 3, conv2d, 64, [3, 3], scope='conv1')
# It is equivalent to:
x = conv2d(x, 64, [3, 3], scope='conv1/conv1_1')
x = conv2d(x, 64, [3, 3], scope='conv1/conv1_2')
y = conv2d(x, 64, [3, 3], scope='conv1/conv1_3')
```
If the `scope` argument is not given in `kwargs`, it is set to
`layer.__name__`, or `layer.func.__name__` (for `functools.partial`
objects). If neither `__name__` nor `func.__name__` is available, the
layers are called with `scope='stack'`.
Args:
inputs: A `Tensor` suitable for layer.
repetitions: Int, number of repetitions.
layer: A layer with arguments `(inputs, *args, **kwargs)`
*args: Extra args for the layer.
**kwargs: Extra kwargs for the layer.
Returns:
A tensor result of applying the layer, repetitions times.
Raises:
ValueError: If the op is unknown or wrong.
"""
scope = kwargs.pop('scope', None)
with variable_scope.variable_scope(scope, 'Repeat', [inputs]):
inputs = ops.convert_to_tensor(inputs)
if scope is None:
if hasattr(layer, '__name__'):
scope = layer.__name__
elif hasattr(layer, 'func') and hasattr(layer.func, '__name__'):
scope = layer.func.__name__ # In case layer is a functools.partial.
else:
scope = 'repeat'
outputs = inputs
for i in range(repetitions):
kwargs['scope'] = scope + '_' + str(i+1)
outputs = layer(outputs, *args, **kwargs)
return outputs | [
"def",
"repeat",
"(",
"inputs",
",",
"repetitions",
",",
"layer",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"scope",
"=",
"kwargs",
".",
"pop",
"(",
"'scope'",
",",
"None",
")",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"scope",
",",
"'Repeat'",
",",
"[",
"inputs",
"]",
")",
":",
"inputs",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"inputs",
")",
"if",
"scope",
"is",
"None",
":",
"if",
"hasattr",
"(",
"layer",
",",
"'__name__'",
")",
":",
"scope",
"=",
"layer",
".",
"__name__",
"elif",
"hasattr",
"(",
"layer",
",",
"'func'",
")",
"and",
"hasattr",
"(",
"layer",
".",
"func",
",",
"'__name__'",
")",
":",
"scope",
"=",
"layer",
".",
"func",
".",
"__name__",
"# In case layer is a functools.partial.",
"else",
":",
"scope",
"=",
"'repeat'",
"outputs",
"=",
"inputs",
"for",
"i",
"in",
"range",
"(",
"repetitions",
")",
":",
"kwargs",
"[",
"'scope'",
"]",
"=",
"scope",
"+",
"'_'",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"outputs",
"=",
"layer",
"(",
"outputs",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"outputs"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/layers.py#L2018-L2061 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/incubate/fleet/base/role_maker.py | python | MPIRoleMaker._finalize | (self) | finalize the current MPI instance. | finalize the current MPI instance. | [
"finalize",
"the",
"current",
"MPI",
"instance",
"."
] | def _finalize(self):
"""
finalize the current MPI instance.
"""
self.MPI.Finalize() | [
"def",
"_finalize",
"(",
"self",
")",
":",
"self",
".",
"MPI",
".",
"Finalize",
"(",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/base/role_maker.py#L238-L242 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-time.py | python | SConsTimer.execute_subcommand | (self, argv) | Executes the do_*() function for the specified subcommand (argv[0]). | Executes the do_*() function for the specified subcommand (argv[0]). | [
"Executes",
"the",
"do_",
"*",
"()",
"function",
"for",
"the",
"specified",
"subcommand",
"(",
"argv",
"[",
"0",
"]",
")",
"."
] | def execute_subcommand(self, argv):
"""
Executes the do_*() function for the specified subcommand (argv[0]).
"""
if not argv:
return
cmdName = self.command_alias.get(argv[0], argv[0])
try:
func = getattr(self, 'do_' + cmdName)
except AttributeError:
return self.default(argv)
try:
return func(argv)
except TypeError as e:
sys.stderr.write("%s %s: %s\n" % (self.name, cmdName, e))
import traceback
traceback.print_exc(file=sys.stderr)
sys.stderr.write("Try '%s help %s'\n" % (self.name, cmdName)) | [
"def",
"execute_subcommand",
"(",
"self",
",",
"argv",
")",
":",
"if",
"not",
"argv",
":",
"return",
"cmdName",
"=",
"self",
".",
"command_alias",
".",
"get",
"(",
"argv",
"[",
"0",
"]",
",",
"argv",
"[",
"0",
"]",
")",
"try",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"'do_'",
"+",
"cmdName",
")",
"except",
"AttributeError",
":",
"return",
"self",
".",
"default",
"(",
"argv",
")",
"try",
":",
"return",
"func",
"(",
"argv",
")",
"except",
"TypeError",
"as",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s %s: %s\\n\"",
"%",
"(",
"self",
".",
"name",
",",
"cmdName",
",",
"e",
")",
")",
"import",
"traceback",
"traceback",
".",
"print_exc",
"(",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Try '%s help %s'\\n\"",
"%",
"(",
"self",
".",
"name",
",",
"cmdName",
")",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-time.py#L693-L710 | ||
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/utils/utils.py | python | build_unicast_route | (
route: Union[network_types_py3.UnicastRoute, network_types.UnicastRoute],
filter_for_networks: Optional[
List[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]
] = None,
filter_exact_match: bool = False,
) | return dest, nexthops | Build unicast route.
:param route: Unicast Route
:param filter_for_networks: IP/Prefixes to filter.
:param filter_exact_match: Indicate exact match or subnet match. | Build unicast route.
:param route: Unicast Route
:param filter_for_networks: IP/Prefixes to filter.
:param filter_exact_match: Indicate exact match or subnet match. | [
"Build",
"unicast",
"route",
".",
":",
"param",
"route",
":",
"Unicast",
"Route",
":",
"param",
"filter_for_networks",
":",
"IP",
"/",
"Prefixes",
"to",
"filter",
".",
":",
"param",
"filter_exact_match",
":",
"Indicate",
"exact",
"match",
"or",
"subnet",
"match",
"."
] | def build_unicast_route(
route: Union[network_types_py3.UnicastRoute, network_types.UnicastRoute],
filter_for_networks: Optional[
List[Union[ipaddress.IPv4Network, ipaddress.IPv6Network]]
] = None,
filter_exact_match: bool = False,
) -> Tuple[str, List[str]]:
"""
Build unicast route.
:param route: Unicast Route
:param filter_for_networks: IP/Prefixes to filter.
:param filter_exact_match: Indicate exact match or subnet match.
"""
dest = ipnetwork.sprint_prefix(route.dest)
if filter_for_networks:
if filter_exact_match:
if not ipaddress.ip_network(dest) in filter_for_networks:
return ("", [])
else:
if not ipnetwork.contain_any_prefix(dest, filter_for_networks):
return ("", [])
nexthops = [ip_nexthop_to_str(nh) for nh in route.nextHops]
return dest, nexthops | [
"def",
"build_unicast_route",
"(",
"route",
":",
"Union",
"[",
"network_types_py3",
".",
"UnicastRoute",
",",
"network_types",
".",
"UnicastRoute",
"]",
",",
"filter_for_networks",
":",
"Optional",
"[",
"List",
"[",
"Union",
"[",
"ipaddress",
".",
"IPv4Network",
",",
"ipaddress",
".",
"IPv6Network",
"]",
"]",
"]",
"=",
"None",
",",
"filter_exact_match",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Tuple",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"dest",
"=",
"ipnetwork",
".",
"sprint_prefix",
"(",
"route",
".",
"dest",
")",
"if",
"filter_for_networks",
":",
"if",
"filter_exact_match",
":",
"if",
"not",
"ipaddress",
".",
"ip_network",
"(",
"dest",
")",
"in",
"filter_for_networks",
":",
"return",
"(",
"\"\"",
",",
"[",
"]",
")",
"else",
":",
"if",
"not",
"ipnetwork",
".",
"contain_any_prefix",
"(",
"dest",
",",
"filter_for_networks",
")",
":",
"return",
"(",
"\"\"",
",",
"[",
"]",
")",
"nexthops",
"=",
"[",
"ip_nexthop_to_str",
"(",
"nh",
")",
"for",
"nh",
"in",
"route",
".",
"nextHops",
"]",
"return",
"dest",
",",
"nexthops"
] | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/utils/utils.py#L1661-L1683 | |
rootm0s/Protectors | 5b3f4d11687a5955caf9c3af30666c4bfc2c19ab | OWASP-ZSC/module/readline_windows/pyreadline/console/console.py | python | Console.get | (self) | Get next event from queue. | Get next event from queue. | [
"Get",
"next",
"event",
"from",
"queue",
"."
] | def get(self):
'''Get next event from queue.'''
inputHookFunc = c_void_p.from_address(self.inputHookPtr).value
Cevent = INPUT_RECORD()
count = DWORD(0)
while 1:
if inputHookFunc:
call_function(inputHookFunc, ())
status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1,
byref(count))
if status and count.value == 1:
e = event(self, Cevent)
return e | [
"def",
"get",
"(",
"self",
")",
":",
"inputHookFunc",
"=",
"c_void_p",
".",
"from_address",
"(",
"self",
".",
"inputHookPtr",
")",
".",
"value",
"Cevent",
"=",
"INPUT_RECORD",
"(",
")",
"count",
"=",
"DWORD",
"(",
"0",
")",
"while",
"1",
":",
"if",
"inputHookFunc",
":",
"call_function",
"(",
"inputHookFunc",
",",
"(",
")",
")",
"status",
"=",
"self",
".",
"ReadConsoleInputW",
"(",
"self",
".",
"hin",
",",
"byref",
"(",
"Cevent",
")",
",",
"1",
",",
"byref",
"(",
"count",
")",
")",
"if",
"status",
"and",
"count",
".",
"value",
"==",
"1",
":",
"e",
"=",
"event",
"(",
"self",
",",
"Cevent",
")",
"return",
"e"
] | https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/console/console.py#L501-L514 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/os2emxpath.py | python | basename | (p) | return split(p)[1] | Returns the final component of a pathname | Returns the final component of a pathname | [
"Returns",
"the",
"final",
"component",
"of",
"a",
"pathname"
] | def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1] | [
"def",
"basename",
"(",
"p",
")",
":",
"return",
"split",
"(",
"p",
")",
"[",
"1",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/os2emxpath.py#L88-L90 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/column/string.py | python | StringMethods.zfill | (self, width: int) | return self._return_or_inplace(libstrings.zfill(self._column, width)) | Pad strings in the Series/Index by prepending ‘0’ characters.
Strings in the Series/Index are padded with ‘0’ characters
on the left of the string to reach a total string length
width. Strings in the Series/Index with length greater
or equal to width are unchanged.
Parameters
----------
width : int
Minimum length of resulting string;
strings with length less than width
be prepended with ‘0’ characters.
Returns
-------
Series/Index of str dtype
Returns Series or Index with prepended ‘0’ characters.
See also
--------
rjust
Fills the left side of strings with an arbitrary character.
ljust
Fills the right side of strings with an arbitrary character.
pad
Fills the specified sides of strings with an arbitrary character.
center
Fills boths sides of strings with an arbitrary character.
Notes
-----
Differs from `str.zfill()
<https://docs.python.org/3/library/stdtypes.html#str.zfill>`_
which has special handling for ‘+’/’-‘ in the string.
Examples
--------
>>> import cudf
>>> s = cudf.Series(['-1', '1', '1000', None])
>>> s
0 -1
1 1
2 1000
3 <NA>
dtype: object
Note that ``None`` is not string, therefore it is converted
to ``None``. The minus sign in ``'-1'`` is treated as a
regular character and the zero is added to the left
of it (`str.zfill()
<https://docs.python.org/3/library/stdtypes.html#str.zfill>`_
would have moved it to the left). ``1000`` remains unchanged as
it is longer than width.
>>> s.str.zfill(3)
0 0-1
1 001
2 1000
3 <NA>
dtype: object | Pad strings in the Series/Index by prepending ‘0’ characters. | [
"Pad",
"strings",
"in",
"the",
"Series",
"/",
"Index",
"by",
"prepending",
"‘0’",
"characters",
"."
] | def zfill(self, width: int) -> SeriesOrIndex:
"""
Pad strings in the Series/Index by prepending ‘0’ characters.
Strings in the Series/Index are padded with ‘0’ characters
on the left of the string to reach a total string length
width. Strings in the Series/Index with length greater
or equal to width are unchanged.
Parameters
----------
width : int
Minimum length of resulting string;
strings with length less than width
be prepended with ‘0’ characters.
Returns
-------
Series/Index of str dtype
Returns Series or Index with prepended ‘0’ characters.
See also
--------
rjust
Fills the left side of strings with an arbitrary character.
ljust
Fills the right side of strings with an arbitrary character.
pad
Fills the specified sides of strings with an arbitrary character.
center
Fills boths sides of strings with an arbitrary character.
Notes
-----
Differs from `str.zfill()
<https://docs.python.org/3/library/stdtypes.html#str.zfill>`_
which has special handling for ‘+’/’-‘ in the string.
Examples
--------
>>> import cudf
>>> s = cudf.Series(['-1', '1', '1000', None])
>>> s
0 -1
1 1
2 1000
3 <NA>
dtype: object
Note that ``None`` is not string, therefore it is converted
to ``None``. The minus sign in ``'-1'`` is treated as a
regular character and the zero is added to the left
of it (`str.zfill()
<https://docs.python.org/3/library/stdtypes.html#str.zfill>`_
would have moved it to the left). ``1000`` remains unchanged as
it is longer than width.
>>> s.str.zfill(3)
0 0-1
1 001
2 1000
3 <NA>
dtype: object
"""
if not is_integer(width):
msg = f"width must be of integer type, not {type(width).__name__}"
raise TypeError(msg)
return self._return_or_inplace(libstrings.zfill(self._column, width)) | [
"def",
"zfill",
"(",
"self",
",",
"width",
":",
"int",
")",
"->",
"SeriesOrIndex",
":",
"if",
"not",
"is_integer",
"(",
"width",
")",
":",
"msg",
"=",
"f\"width must be of integer type, not {type(width).__name__}\"",
"raise",
"TypeError",
"(",
"msg",
")",
"return",
"self",
".",
"_return_or_inplace",
"(",
"libstrings",
".",
"zfill",
"(",
"self",
".",
"_column",
",",
"width",
")",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/string.py#L2832-L2903 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py | python | ExFileObject.read | (self, size=None) | return buf | Read at most size bytes from the file. If size is not
present or None, read all data until EOF is reached. | Read at most size bytes from the file. If size is not
present or None, read all data until EOF is reached. | [
"Read",
"at",
"most",
"size",
"bytes",
"from",
"the",
"file",
".",
"If",
"size",
"is",
"not",
"present",
"or",
"None",
"read",
"all",
"data",
"until",
"EOF",
"is",
"reached",
"."
] | def read(self, size=None):
"""Read at most size bytes from the file. If size is not
present or None, read all data until EOF is reached.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
buf = b""
if self.buffer:
if size is None:
buf = self.buffer
self.buffer = b""
else:
buf = self.buffer[:size]
self.buffer = self.buffer[size:]
if size is None:
buf += self.fileobj.read()
else:
buf += self.fileobj.read(size - len(buf))
self.position += len(buf)
return buf | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed file\"",
")",
"buf",
"=",
"b\"\"",
"if",
"self",
".",
"buffer",
":",
"if",
"size",
"is",
"None",
":",
"buf",
"=",
"self",
".",
"buffer",
"self",
".",
"buffer",
"=",
"b\"\"",
"else",
":",
"buf",
"=",
"self",
".",
"buffer",
"[",
":",
"size",
"]",
"self",
".",
"buffer",
"=",
"self",
".",
"buffer",
"[",
"size",
":",
"]",
"if",
"size",
"is",
"None",
":",
"buf",
"+=",
"self",
".",
"fileobj",
".",
"read",
"(",
")",
"else",
":",
"buf",
"+=",
"self",
".",
"fileobj",
".",
"read",
"(",
"size",
"-",
"len",
"(",
"buf",
")",
")",
"self",
".",
"position",
"+=",
"len",
"(",
"buf",
")",
"return",
"buf"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L810-L832 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | SpinButton.GetMin | (*args, **kwargs) | return _controls_.SpinButton_GetMin(*args, **kwargs) | GetMin(self) -> int | GetMin(self) -> int | [
"GetMin",
"(",
"self",
")",
"-",
">",
"int"
] | def GetMin(*args, **kwargs):
"""GetMin(self) -> int"""
return _controls_.SpinButton_GetMin(*args, **kwargs) | [
"def",
"GetMin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"SpinButton_GetMin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2258-L2260 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | FileDialog.SetPath | (*args, **kwargs) | return _windows_.FileDialog_SetPath(*args, **kwargs) | SetPath(self, String path)
Sets the path (the combined directory and filename that will be
returned when the dialog is dismissed). | SetPath(self, String path) | [
"SetPath",
"(",
"self",
"String",
"path",
")"
] | def SetPath(*args, **kwargs):
"""
SetPath(self, String path)
Sets the path (the combined directory and filename that will be
returned when the dialog is dismissed).
"""
return _windows_.FileDialog_SetPath(*args, **kwargs) | [
"def",
"SetPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"FileDialog_SetPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L3150-L3157 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py | python | CmsisDapDebugger.dap_read_idcode | (self) | return self.dap_read_reg(self.DP_IDCODE) | Reads the IDCODE from the SWD DP | Reads the IDCODE from the SWD DP | [
"Reads",
"the",
"IDCODE",
"from",
"the",
"SWD",
"DP"
] | def dap_read_idcode(self):
"""Reads the IDCODE from the SWD DP"""
self.logger.debug("reading swd idcode")
return self.dap_read_reg(self.DP_IDCODE) | [
"def",
"dap_read_idcode",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"reading swd idcode\"",
")",
"return",
"self",
".",
"dap_read_reg",
"(",
"self",
".",
"DP_IDCODE",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py#L488-L491 | |
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/clis/config.py | python | ConfigPrefixAllocatorCli.config_prefix_allocator | (cli_opts) | Dump prefix allocation config | Dump prefix allocation config | [
"Dump",
"prefix",
"allocation",
"config"
] | def config_prefix_allocator(cli_opts): # noqa: B902
"""Dump prefix allocation config"""
config.ConfigPrefixAllocatorCmd(cli_opts).run() | [
"def",
"config_prefix_allocator",
"(",
"cli_opts",
")",
":",
"# noqa: B902",
"config",
".",
"ConfigPrefixAllocatorCmd",
"(",
"cli_opts",
")",
".",
"run",
"(",
")"
] | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/clis/config.py#L76-L79 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | argmax | (a, axis=None, out=None) | return _npi.argmax(a, axis=axis, keepdims=False, out=out) | r"""
Returns the indices of the maximum values along an axis.
Parameters
----------
a : _Symbol
Input array. Only support dtype `float16`, `float32`, and `float64`.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
out : _Symbol or None, optional
Dummy parameter to keep the consistency with the ndarray counterpart.
Returns
-------
index_array : _Symbol of indices whose dtype is same as the input ndarray.
Array of indices into the array. It has the same shape as `a.shape`
with the dimension along `axis` removed.
Notes
-----
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.
This function differs from the original `numpy.argmax
<https://numpy.org/doc/stable/reference/generated/numpy.argmax.html>`_ in
the following aspects:
- Input type does not support Python native iterables(list, tuple, ...).
- ``out`` param: cannot perform auto broadcasting. ``out`` symbol's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` symnbol's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case. | r"""
Returns the indices of the maximum values along an axis. | [
"r",
"Returns",
"the",
"indices",
"of",
"the",
"maximum",
"values",
"along",
"an",
"axis",
"."
] | def argmax(a, axis=None, out=None):
r"""
Returns the indices of the maximum values along an axis.
Parameters
----------
a : _Symbol
Input array. Only support dtype `float16`, `float32`, and `float64`.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
out : _Symbol or None, optional
Dummy parameter to keep the consistency with the ndarray counterpart.
Returns
-------
index_array : _Symbol of indices whose dtype is same as the input ndarray.
Array of indices into the array. It has the same shape as `a.shape`
with the dimension along `axis` removed.
Notes
-----
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.
This function differs from the original `numpy.argmax
<https://numpy.org/doc/stable/reference/generated/numpy.argmax.html>`_ in
the following aspects:
- Input type does not support Python native iterables(list, tuple, ...).
- ``out`` param: cannot perform auto broadcasting. ``out`` symbol's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` symnbol's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
"""
return _npi.argmax(a, axis=axis, keepdims=False, out=out) | [
"def",
"argmax",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"return",
"_npi",
".",
"argmax",
"(",
"a",
",",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
"False",
",",
"out",
"=",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L4855-L4890 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/http_wrapper.py | python | Response.length | (self) | return len(self.content) | Return the length of this response.
We expose this as an attribute since using len() directly can fail
for responses larger than sys.maxint.
Returns:
Response length (as int or long) | Return the length of this response. | [
"Return",
"the",
"length",
"of",
"this",
"response",
"."
] | def length(self):
"""Return the length of this response.
We expose this as an attribute since using len() directly can fail
for responses larger than sys.maxint.
Returns:
Response length (as int or long)
"""
def ProcessContentRange(content_range):
_, _, range_spec = content_range.partition(' ')
byte_range, _, _ = range_spec.partition('/')
start, _, end = byte_range.partition('-')
return int(end) - int(start) + 1
if '-content-encoding' in self.info and 'content-range' in self.info:
# httplib2 rewrites content-length in the case of a compressed
# transfer; we can't trust the content-length header in that
# case, but we *can* trust content-range, if it's present.
return ProcessContentRange(self.info['content-range'])
elif 'content-length' in self.info:
return int(self.info.get('content-length'))
elif 'content-range' in self.info:
return ProcessContentRange(self.info['content-range'])
return len(self.content) | [
"def",
"length",
"(",
"self",
")",
":",
"def",
"ProcessContentRange",
"(",
"content_range",
")",
":",
"_",
",",
"_",
",",
"range_spec",
"=",
"content_range",
".",
"partition",
"(",
"' '",
")",
"byte_range",
",",
"_",
",",
"_",
"=",
"range_spec",
".",
"partition",
"(",
"'/'",
")",
"start",
",",
"_",
",",
"end",
"=",
"byte_range",
".",
"partition",
"(",
"'-'",
")",
"return",
"int",
"(",
"end",
")",
"-",
"int",
"(",
"start",
")",
"+",
"1",
"if",
"'-content-encoding'",
"in",
"self",
".",
"info",
"and",
"'content-range'",
"in",
"self",
".",
"info",
":",
"# httplib2 rewrites content-length in the case of a compressed",
"# transfer; we can't trust the content-length header in that",
"# case, but we *can* trust content-range, if it's present.",
"return",
"ProcessContentRange",
"(",
"self",
".",
"info",
"[",
"'content-range'",
"]",
")",
"elif",
"'content-length'",
"in",
"self",
".",
"info",
":",
"return",
"int",
"(",
"self",
".",
"info",
".",
"get",
"(",
"'content-length'",
")",
")",
"elif",
"'content-range'",
"in",
"self",
".",
"info",
":",
"return",
"ProcessContentRange",
"(",
"self",
".",
"info",
"[",
"'content-range'",
"]",
")",
"return",
"len",
"(",
"self",
".",
"content",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/http_wrapper.py#L153-L177 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | UpdateUIEvent.SetMode | (*args, **kwargs) | return _core_.UpdateUIEvent_SetMode(*args, **kwargs) | SetMode(int mode)
Specify how wxWidgets will send update events: to all windows, or only
to those which specify that they will process the events.
The mode may be one of the following values:
============================= ==========================================
wxUPDATE_UI_PROCESS_ALL Send UI update events to all windows. This
is the default setting.
wxUPDATE_UI_PROCESS_SPECIFIED Send UI update events only to windows that
have the wx.WS_EX_PROCESS_UI_UPDATES extra
style set.
============================= ========================================== | SetMode(int mode) | [
"SetMode",
"(",
"int",
"mode",
")"
] | def SetMode(*args, **kwargs):
"""
SetMode(int mode)
Specify how wxWidgets will send update events: to all windows, or only
to those which specify that they will process the events.
The mode may be one of the following values:
============================= ==========================================
wxUPDATE_UI_PROCESS_ALL Send UI update events to all windows. This
is the default setting.
wxUPDATE_UI_PROCESS_SPECIFIED Send UI update events only to windows that
have the wx.WS_EX_PROCESS_UI_UPDATES extra
style set.
============================= ==========================================
"""
return _core_.UpdateUIEvent_SetMode(*args, **kwargs) | [
"def",
"SetMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"UpdateUIEvent_SetMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L6908-L6926 | |
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | elle/drake/src/drake/__init__.py | python | FunctionExpander.__init__ | (self, function, *args, **kwargs) | Create a function expander.=
function -- The function to apply on key, values pairs.
args, kwargs -- Rest of the arguments for Expander constructor. | Create a function expander.= | [
"Create",
"a",
"function",
"expander",
".",
"="
] | def __init__(self, function, *args, **kwargs):
"""Create a function expander.=
function -- The function to apply on key, values pairs.
args, kwargs -- Rest of the arguments for Expander constructor.
"""
self.__function = function
Expander.__init__(self, *args, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__function",
"=",
"function",
"Expander",
".",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L2824-L2831 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | QuoteContainer.process | (self) | Process contents | Process contents | [
"Process",
"contents"
] | def process(self):
"Process contents"
self.type = self.header[2]
if not self.type in StyleConfig.quotes:
Trace.error('Quote type ' + self.type + ' not found')
self.html = ['"']
return
self.html = [StyleConfig.quotes[self.type]] | [
"def",
"process",
"(",
"self",
")",
":",
"self",
".",
"type",
"=",
"self",
".",
"header",
"[",
"2",
"]",
"if",
"not",
"self",
".",
"type",
"in",
"StyleConfig",
".",
"quotes",
":",
"Trace",
".",
"error",
"(",
"'Quote type '",
"+",
"self",
".",
"type",
"+",
"' not found'",
")",
"self",
".",
"html",
"=",
"[",
"'\"'",
"]",
"return",
"self",
".",
"html",
"=",
"[",
"StyleConfig",
".",
"quotes",
"[",
"self",
".",
"type",
"]",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L3550-L3557 | ||
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py | python | Cursor.is_move_constructor | (self) | return conf.lib.clang_CXXConstructor_isMoveConstructor(self) | Returns True if the cursor refers to a C++ move constructor. | Returns True if the cursor refers to a C++ move constructor. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"move",
"constructor",
"."
] | def is_move_constructor(self):
"""Returns True if the cursor refers to a C++ move constructor.
"""
return conf.lib.clang_CXXConstructor_isMoveConstructor(self) | [
"def",
"is_move_constructor",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXConstructor_isMoveConstructor",
"(",
"self",
")"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py#L1367-L1370 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xmlReg.regexpPrint | (self, output) | Print the content of the compiled regular expression | Print the content of the compiled regular expression | [
"Print",
"the",
"content",
"of",
"the",
"compiled",
"regular",
"expression"
] | def regexpPrint(self, output):
"""Print the content of the compiled regular expression """
libxml2mod.xmlRegexpPrint(output, self._o) | [
"def",
"regexpPrint",
"(",
"self",
",",
"output",
")",
":",
"libxml2mod",
".",
"xmlRegexpPrint",
"(",
"output",
",",
"self",
".",
"_o",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L6206-L6208 | ||
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/box.py | python | Box.tilts | (self) | return np.array([self.xy, self.xz, self.yz]) | (3, ) `numpy.ndarray` of `float`: The box tilts, ``[xy, xz, yz]``.
Can be set using one tilt for all axes or three tilts. If the box is 2D
``xz`` and ``yz`` will automatically be set to zero. | (3, ) `numpy.ndarray` of `float`: The box tilts, ``[xy, xz, yz]``. | [
"(",
"3",
")",
"numpy",
".",
"ndarray",
"of",
"float",
":",
"The",
"box",
"tilts",
"[",
"xy",
"xz",
"yz",
"]",
"."
] | def tilts(self):
"""(3, ) `numpy.ndarray` of `float`: The box tilts, ``[xy, xz, yz]``.
Can be set using one tilt for all axes or three tilts. If the box is 2D
``xz`` and ``yz`` will automatically be set to zero.
"""
return np.array([self.xy, self.xz, self.yz]) | [
"def",
"tilts",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"xy",
",",
"self",
".",
"xz",
",",
"self",
".",
"yz",
"]",
")"
] | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/box.py#L301-L307 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/mailbox.py | python | _ProxyFile.__iter__ | (self) | Iterate over lines. | Iterate over lines. | [
"Iterate",
"over",
"lines",
"."
] | def __iter__(self):
"""Iterate over lines."""
while True:
line = self.readline()
if not line:
return
yield line | [
"def",
"__iter__",
"(",
"self",
")",
":",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"return",
"yield",
"line"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L1957-L1963 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/stats/kde.py | python | gaussian_kde.integrate_box | (self, low_bounds, high_bounds, maxpts=None) | return value | Computes the integral of a pdf over a rectangular interval.
Parameters
----------
low_bounds : array_like
A 1-D array containing the lower bounds of integration.
high_bounds : array_like
A 1-D array containing the upper bounds of integration.
maxpts : int, optional
The maximum number of points to use for integration.
Returns
-------
value : scalar
The result of the integral. | Computes the integral of a pdf over a rectangular interval. | [
"Computes",
"the",
"integral",
"of",
"a",
"pdf",
"over",
"a",
"rectangular",
"interval",
"."
] | def integrate_box(self, low_bounds, high_bounds, maxpts=None):
"""Computes the integral of a pdf over a rectangular interval.
Parameters
----------
low_bounds : array_like
A 1-D array containing the lower bounds of integration.
high_bounds : array_like
A 1-D array containing the upper bounds of integration.
maxpts : int, optional
The maximum number of points to use for integration.
Returns
-------
value : scalar
The result of the integral.
"""
from . import mvn
if maxpts is not None:
extra_kwds = {'maxpts': maxpts}
else:
extra_kwds = {}
value, inform = mvn.mvnun_weighted(low_bounds, high_bounds,
self.dataset, self.weights,
self.covariance, **extra_kwds)
if inform:
msg = ('An integral in mvn.mvnun requires more points than %s' %
(self.d * 1000))
warnings.warn(msg)
return value | [
"def",
"integrate_box",
"(",
"self",
",",
"low_bounds",
",",
"high_bounds",
",",
"maxpts",
"=",
"None",
")",
":",
"from",
".",
"import",
"mvn",
"if",
"maxpts",
"is",
"not",
"None",
":",
"extra_kwds",
"=",
"{",
"'maxpts'",
":",
"maxpts",
"}",
"else",
":",
"extra_kwds",
"=",
"{",
"}",
"value",
",",
"inform",
"=",
"mvn",
".",
"mvnun_weighted",
"(",
"low_bounds",
",",
"high_bounds",
",",
"self",
".",
"dataset",
",",
"self",
".",
"weights",
",",
"self",
".",
"covariance",
",",
"*",
"*",
"extra_kwds",
")",
"if",
"inform",
":",
"msg",
"=",
"(",
"'An integral in mvn.mvnun requires more points than %s'",
"%",
"(",
"self",
".",
"d",
"*",
"1000",
")",
")",
"warnings",
".",
"warn",
"(",
"msg",
")",
"return",
"value"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/kde.py#L353-L386 | |
moderngl/moderngl | 32fe79927e02b0fa893b3603d677bdae39771e14 | moderngl/context.py | python | Context.core_profile_check | (self) | Core profile check.
FOR DEBUG PURPOSES ONLY | Core profile check. | [
"Core",
"profile",
"check",
"."
] | def core_profile_check(self) -> None:
'''
Core profile check.
FOR DEBUG PURPOSES ONLY
'''
profile_mask = self.info['GL_CONTEXT_PROFILE_MASK']
if profile_mask != 1:
warnings.warn('The window should request a CORE OpenGL profile')
version_code = self.version_code
if not version_code:
major, minor = map(int, self.info['GL_VERSION'].split('.', 2)[:2])
version_code = major * 100 + minor * 10
if version_code < 330:
warnings.warn('The window should support OpenGL 3.3+ (version_code=%d)' % version_code) | [
"def",
"core_profile_check",
"(",
"self",
")",
"->",
"None",
":",
"profile_mask",
"=",
"self",
".",
"info",
"[",
"'GL_CONTEXT_PROFILE_MASK'",
"]",
"if",
"profile_mask",
"!=",
"1",
":",
"warnings",
".",
"warn",
"(",
"'The window should request a CORE OpenGL profile'",
")",
"version_code",
"=",
"self",
".",
"version_code",
"if",
"not",
"version_code",
":",
"major",
",",
"minor",
"=",
"map",
"(",
"int",
",",
"self",
".",
"info",
"[",
"'GL_VERSION'",
"]",
".",
"split",
"(",
"'.'",
",",
"2",
")",
"[",
":",
"2",
"]",
")",
"version_code",
"=",
"major",
"*",
"100",
"+",
"minor",
"*",
"10",
"if",
"version_code",
"<",
"330",
":",
"warnings",
".",
"warn",
"(",
"'The window should support OpenGL 3.3+ (version_code=%d)'",
"%",
"version_code",
")"
] | https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/context.py#L1710-L1727 | ||
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/gen_vehicle_protocol/gen_protocols.py | python | gen_protocols | (protocol_conf_file, protocol_dir) | doc string: | doc string: | [
"doc",
"string",
":"
] | def gen_protocols(protocol_conf_file, protocol_dir):
"""
doc string:
"""
print("Generating protocols")
if not os.path.exists(protocol_dir):
os.makedirs(protocol_dir)
with open(protocol_conf_file, 'r') as fp:
content = yaml.safe_load(fp)
protocols = content["protocols"]
car_type = content["car_type"]
for p_name in protocols:
protocol = protocols[p_name]
if protocol["protocol_type"] == "report":
gen_report_header(car_type, protocol, protocol_dir)
gen_report_cpp(car_type, protocol, protocol_dir)
elif protocol["protocol_type"] == "control":
gen_control_header(car_type, protocol, protocol_dir)
gen_control_cpp(car_type, protocol, protocol_dir)
else:
print("Unknown protocol_type:%s" % protocol["protocol_type"])
gen_build_file(car_type, protocol_dir) | [
"def",
"gen_protocols",
"(",
"protocol_conf_file",
",",
"protocol_dir",
")",
":",
"print",
"(",
"\"Generating protocols\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"protocol_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"protocol_dir",
")",
"with",
"open",
"(",
"protocol_conf_file",
",",
"'r'",
")",
"as",
"fp",
":",
"content",
"=",
"yaml",
".",
"safe_load",
"(",
"fp",
")",
"protocols",
"=",
"content",
"[",
"\"protocols\"",
"]",
"car_type",
"=",
"content",
"[",
"\"car_type\"",
"]",
"for",
"p_name",
"in",
"protocols",
":",
"protocol",
"=",
"protocols",
"[",
"p_name",
"]",
"if",
"protocol",
"[",
"\"protocol_type\"",
"]",
"==",
"\"report\"",
":",
"gen_report_header",
"(",
"car_type",
",",
"protocol",
",",
"protocol_dir",
")",
"gen_report_cpp",
"(",
"car_type",
",",
"protocol",
",",
"protocol_dir",
")",
"elif",
"protocol",
"[",
"\"protocol_type\"",
"]",
"==",
"\"control\"",
":",
"gen_control_header",
"(",
"car_type",
",",
"protocol",
",",
"protocol_dir",
")",
"gen_control_cpp",
"(",
"car_type",
",",
"protocol",
",",
"protocol_dir",
")",
"else",
":",
"print",
"(",
"\"Unknown protocol_type:%s\"",
"%",
"protocol",
"[",
"\"protocol_type\"",
"]",
")",
"gen_build_file",
"(",
"car_type",
",",
"protocol_dir",
")"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/gen_vehicle_protocol/gen_protocols.py#L436-L459 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/locators.py | python | DependencyFinder.find | (self, requirement, meta_extras=None, prereleases=False) | return dists, problems | Find a distribution and all distributions it depends on.
:param requirement: The requirement specifying the distribution to
find, or a Distribution instance.
:param meta_extras: A list of meta extras such as :test:, :build: and
so on.
:param prereleases: If ``True``, allow pre-release versions to be
returned - otherwise, don't return prereleases
unless they're all that's available.
Return a set of :class:`Distribution` instances and a set of
problems.
The distributions returned should be such that they have the
:attr:`required` attribute set to ``True`` if they were
from the ``requirement`` passed to ``find()``, and they have the
:attr:`build_time_dependency` attribute set to ``True`` unless they
are post-installation dependencies of the ``requirement``.
The problems should be a tuple consisting of the string
``'unsatisfied'`` and the requirement which couldn't be satisfied
by any distribution known to the locator. | Find a distribution and all distributions it depends on. | [
"Find",
"a",
"distribution",
"and",
"all",
"distributions",
"it",
"depends",
"on",
"."
] | def find(self, requirement, meta_extras=None, prereleases=False):
"""
Find a distribution and all distributions it depends on.
:param requirement: The requirement specifying the distribution to
find, or a Distribution instance.
:param meta_extras: A list of meta extras such as :test:, :build: and
so on.
:param prereleases: If ``True``, allow pre-release versions to be
returned - otherwise, don't return prereleases
unless they're all that's available.
Return a set of :class:`Distribution` instances and a set of
problems.
The distributions returned should be such that they have the
:attr:`required` attribute set to ``True`` if they were
from the ``requirement`` passed to ``find()``, and they have the
:attr:`build_time_dependency` attribute set to ``True`` unless they
are post-installation dependencies of the ``requirement``.
The problems should be a tuple consisting of the string
``'unsatisfied'`` and the requirement which couldn't be satisfied
by any distribution known to the locator.
"""
self.provided = {}
self.dists = {}
self.dists_by_name = {}
self.reqts = {}
meta_extras = set(meta_extras or [])
if ':*:' in meta_extras:
meta_extras.remove(':*:')
# :meta: and :run: are implicitly included
meta_extras |= set([':test:', ':build:', ':dev:'])
if isinstance(requirement, Distribution):
dist = odist = requirement
logger.debug('passed %s as requirement', odist)
else:
dist = odist = self.locator.locate(requirement,
prereleases=prereleases)
if dist is None:
raise DistlibException('Unable to locate %r' % requirement)
logger.debug('located %s', odist)
dist.requested = True
problems = set()
todo = set([dist])
install_dists = set([odist])
while todo:
dist = todo.pop()
name = dist.key # case-insensitive
if name not in self.dists_by_name:
self.add_distribution(dist)
else:
#import pdb; pdb.set_trace()
other = self.dists_by_name[name]
if other != dist:
self.try_to_replace(dist, other, problems)
ireqts = dist.run_requires | dist.meta_requires
sreqts = dist.build_requires
ereqts = set()
if dist in install_dists:
for key in ('test', 'build', 'dev'):
e = ':%s:' % key
if e in meta_extras:
ereqts |= getattr(dist, '%s_requires' % key)
all_reqts = ireqts | sreqts | ereqts
for r in all_reqts:
providers = self.find_providers(r)
if not providers:
logger.debug('No providers found for %r', r)
provider = self.locator.locate(r, prereleases=prereleases)
# If no provider is found and we didn't consider
# prereleases, consider them now.
if provider is None and not prereleases:
provider = self.locator.locate(r, prereleases=True)
if provider is None:
logger.debug('Cannot satisfy %r', r)
problems.add(('unsatisfied', r))
else:
n, v = provider.key, provider.version
if (n, v) not in self.dists:
todo.add(provider)
providers.add(provider)
if r in ireqts and dist in install_dists:
install_dists.add(provider)
logger.debug('Adding %s to install_dists',
provider.name_and_version)
for p in providers:
name = p.key
if name not in self.dists_by_name:
self.reqts.setdefault(p, set()).add(r)
else:
other = self.dists_by_name[name]
if other != p:
# see if other can be replaced by p
self.try_to_replace(p, other, problems)
dists = set(self.dists.values())
for dist in dists:
dist.build_time_dependency = dist not in install_dists
if dist.build_time_dependency:
logger.debug('%s is a build-time dependency only.',
dist.name_and_version)
logger.debug('find done for %s', odist)
return dists, problems | [
"def",
"find",
"(",
"self",
",",
"requirement",
",",
"meta_extras",
"=",
"None",
",",
"prereleases",
"=",
"False",
")",
":",
"self",
".",
"provided",
"=",
"{",
"}",
"self",
".",
"dists",
"=",
"{",
"}",
"self",
".",
"dists_by_name",
"=",
"{",
"}",
"self",
".",
"reqts",
"=",
"{",
"}",
"meta_extras",
"=",
"set",
"(",
"meta_extras",
"or",
"[",
"]",
")",
"if",
"':*:'",
"in",
"meta_extras",
":",
"meta_extras",
".",
"remove",
"(",
"':*:'",
")",
"# :meta: and :run: are implicitly included",
"meta_extras",
"|=",
"set",
"(",
"[",
"':test:'",
",",
"':build:'",
",",
"':dev:'",
"]",
")",
"if",
"isinstance",
"(",
"requirement",
",",
"Distribution",
")",
":",
"dist",
"=",
"odist",
"=",
"requirement",
"logger",
".",
"debug",
"(",
"'passed %s as requirement'",
",",
"odist",
")",
"else",
":",
"dist",
"=",
"odist",
"=",
"self",
".",
"locator",
".",
"locate",
"(",
"requirement",
",",
"prereleases",
"=",
"prereleases",
")",
"if",
"dist",
"is",
"None",
":",
"raise",
"DistlibException",
"(",
"'Unable to locate %r'",
"%",
"requirement",
")",
"logger",
".",
"debug",
"(",
"'located %s'",
",",
"odist",
")",
"dist",
".",
"requested",
"=",
"True",
"problems",
"=",
"set",
"(",
")",
"todo",
"=",
"set",
"(",
"[",
"dist",
"]",
")",
"install_dists",
"=",
"set",
"(",
"[",
"odist",
"]",
")",
"while",
"todo",
":",
"dist",
"=",
"todo",
".",
"pop",
"(",
")",
"name",
"=",
"dist",
".",
"key",
"# case-insensitive",
"if",
"name",
"not",
"in",
"self",
".",
"dists_by_name",
":",
"self",
".",
"add_distribution",
"(",
"dist",
")",
"else",
":",
"#import pdb; pdb.set_trace()",
"other",
"=",
"self",
".",
"dists_by_name",
"[",
"name",
"]",
"if",
"other",
"!=",
"dist",
":",
"self",
".",
"try_to_replace",
"(",
"dist",
",",
"other",
",",
"problems",
")",
"ireqts",
"=",
"dist",
".",
"run_requires",
"|",
"dist",
".",
"meta_requires",
"sreqts",
"=",
"dist",
".",
"build_requires",
"ereqts",
"=",
"set",
"(",
")",
"if",
"dist",
"in",
"install_dists",
":",
"for",
"key",
"in",
"(",
"'test'",
",",
"'build'",
",",
"'dev'",
")",
":",
"e",
"=",
"':%s:'",
"%",
"key",
"if",
"e",
"in",
"meta_extras",
":",
"ereqts",
"|=",
"getattr",
"(",
"dist",
",",
"'%s_requires'",
"%",
"key",
")",
"all_reqts",
"=",
"ireqts",
"|",
"sreqts",
"|",
"ereqts",
"for",
"r",
"in",
"all_reqts",
":",
"providers",
"=",
"self",
".",
"find_providers",
"(",
"r",
")",
"if",
"not",
"providers",
":",
"logger",
".",
"debug",
"(",
"'No providers found for %r'",
",",
"r",
")",
"provider",
"=",
"self",
".",
"locator",
".",
"locate",
"(",
"r",
",",
"prereleases",
"=",
"prereleases",
")",
"# If no provider is found and we didn't consider",
"# prereleases, consider them now.",
"if",
"provider",
"is",
"None",
"and",
"not",
"prereleases",
":",
"provider",
"=",
"self",
".",
"locator",
".",
"locate",
"(",
"r",
",",
"prereleases",
"=",
"True",
")",
"if",
"provider",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"'Cannot satisfy %r'",
",",
"r",
")",
"problems",
".",
"add",
"(",
"(",
"'unsatisfied'",
",",
"r",
")",
")",
"else",
":",
"n",
",",
"v",
"=",
"provider",
".",
"key",
",",
"provider",
".",
"version",
"if",
"(",
"n",
",",
"v",
")",
"not",
"in",
"self",
".",
"dists",
":",
"todo",
".",
"add",
"(",
"provider",
")",
"providers",
".",
"add",
"(",
"provider",
")",
"if",
"r",
"in",
"ireqts",
"and",
"dist",
"in",
"install_dists",
":",
"install_dists",
".",
"add",
"(",
"provider",
")",
"logger",
".",
"debug",
"(",
"'Adding %s to install_dists'",
",",
"provider",
".",
"name_and_version",
")",
"for",
"p",
"in",
"providers",
":",
"name",
"=",
"p",
".",
"key",
"if",
"name",
"not",
"in",
"self",
".",
"dists_by_name",
":",
"self",
".",
"reqts",
".",
"setdefault",
"(",
"p",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"r",
")",
"else",
":",
"other",
"=",
"self",
".",
"dists_by_name",
"[",
"name",
"]",
"if",
"other",
"!=",
"p",
":",
"# see if other can be replaced by p",
"self",
".",
"try_to_replace",
"(",
"p",
",",
"other",
",",
"problems",
")",
"dists",
"=",
"set",
"(",
"self",
".",
"dists",
".",
"values",
"(",
")",
")",
"for",
"dist",
"in",
"dists",
":",
"dist",
".",
"build_time_dependency",
"=",
"dist",
"not",
"in",
"install_dists",
"if",
"dist",
".",
"build_time_dependency",
":",
"logger",
".",
"debug",
"(",
"'%s is a build-time dependency only.'",
",",
"dist",
".",
"name_and_version",
")",
"logger",
".",
"debug",
"(",
"'find done for %s'",
",",
"odist",
")",
"return",
"dists",
",",
"problems"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/locators.py#L1125-L1233 | |
ledger/ledger | 8e79216887cf3c342dfca1ffa52cf4e6389d6de4 | contrib/non-profit-audit-reports/ooolib2/__init__.py | python | CalcStyles.get_automatic_styles | (self) | return automatic_styles | Return 'office:automatic-styles' lists | Return 'office:automatic-styles' lists | [
"Return",
"office",
":",
"automatic",
"-",
"styles",
"lists"
] | def get_automatic_styles(self):
"Return 'office:automatic-styles' lists"
automatic_styles = ['tag', 'office:automatic-styles']
for style_data in self.style_config:
style_code = self.style_config[style_data]
style_data = list(style_data)
style = style_data.pop(0)
if style == 'column':
style_list = ['tag', 'style:style',
['element', 'style:name', style_code], # Column 'co1' properties
['element', 'style:family', 'table-column']]
tagline = ['tagline', 'style:table-column-properties',
['element', 'fo:break-before', 'auto']] # unsure what break before means
for set in style_data:
name, value = set
if name == 'style:column-width':
tagline.append(['element', 'style:column-width', value])
style_list.append(tagline)
automatic_styles.append(style_list)
if style == 'row':
style_list = ['tag', 'style:style',
['element', 'style:name', style_code], # Column 'ro1' properties
['element', 'style:family', 'table-row']]
tagline = ['tagline', 'style:table-row-properties']
for set in style_data:
name, value = set
if name == 'style:row-height':
tagline.append(['element', 'style:row-height', value])
tagline.append(['element', 'fo:break-before', 'auto'])
# tagline.append(['element', 'style:use-optimal-row-height', 'true']) # Overrides settings
style_list.append(tagline)
automatic_styles.append(style_list)
if style == 'pagebreak':
style_list = ['tag', 'style:style',
['element', 'style:name', style_code], # Column 'ro1' properties
['element', 'style:family', 'table-row']]
tagline = ['tagline', 'style:table-row-properties']
for set in style_data:
name, value = set
if name == 'style:row-height':
tagline.append(['element', 'style:row-height', value])
tagline.append(['element', 'fo:break-before', 'page'])
# tagline.append(['element', 'style:use-optimal-row-height', 'true']) # Overrides settings
style_list.append(tagline)
automatic_styles.append(style_list)
if style == 'cell':
style_list = ['tag', 'style:style',
['element', 'style:name', style_code], # ce1 style
['element', 'style:family', 'table-cell'], # cell
['element', 'style:parent-style-name', 'Default']] # parent is Default
# hack for currency
if style_code == 'ce1':
style_list.append(['element',
'style:data-style-name',
'N104'])
# Cell Properties
tagline = ['tag', 'style:table-cell-properties']
tagline_additional = []
for set in style_data:
name, value = set
if name == 'background':
tagline.append(['element', 'fo:background-color', value])
if name == 'backgroundimage':
tagline.append(['element', 'fo:background-color', 'transparent'])
# Additional tags added later
bgimagetag = ['tagline', 'style:background-image']
bgimagetag.append(['element', 'xlink:href', value])
bgimagetag.append(['element', 'xlink:type', 'simple'])
bgimagetag.append(['element', 'xlink:actuate', 'onLoad'])
tagline_additional.append(bgimagetag)
if name == 'valign':
if value in ['top', 'bottom', 'middle']:
tagline.append(['element', 'style:vertical-align', value])
if name == 'halign':
tagline.append(['element', 'style:text-align-source', 'fix'])
if value in ['filled']:
tagline.append(['element', 'style:repeat-content', 'true'])
else:
tagline.append(['element', 'style:repeat-content', 'false'])
# Add any additional internal tags
while tagline_additional:
tagadd = tagline_additional.pop(0)
tagline.append(tagadd)
style_list.append(tagline)
# Paragraph Properties
tagline = ['tagline', 'style:paragraph-properties']
tagline_valid = False
for set in style_data:
name, value = set
if name == 'halign':
tagline_valid = True
if value in ['center']:
tagline.append(['element', 'fo:text-align', 'center'])
if value in ['end', 'right']:
tagline.append(['element', 'fo:text-align', 'end'])
if value in ['start', 'filled', 'left']:
tagline.append(['element', 'fo:text-align', 'start'])
if value in ['justify']:
tagline.append(['element', 'fo:text-align', 'justify'])
# Conditionally add the tagline
if tagline_valid: style_list.append(tagline)
# Text Properties
tagline = ['tagline', 'style:text-properties']
for set in style_data:
name, value = set
if name == 'bold':
tagline.append(['element', 'fo:font-weight', 'bold'])
if name == 'italic':
tagline.append(['element', 'fo:font-style', 'italic'])
if name == 'underline':
tagline.append(['element', 'style:text-underline-style', 'solid'])
tagline.append(['element', 'style:text-underline-width', 'auto'])
tagline.append(['element', 'style:text-underline-color', 'font-color'])
if name == 'color':
tagline.append(['element', 'fo:color', value])
if name == 'fontsize':
tagline.append(['element', 'fo:font-size', '%spt' % value])
style_list.append(tagline)
automatic_styles.append(style_list)
# Attach ta1 style
automatic_styles.append(['tag', 'style:style',
['element', 'style:name', 'ta1'],
['element', 'style:family', 'table'],
['element', 'style:master-page-name', 'Default'],
['tagline', 'style:table-properties',
['element', 'table:display', 'true'],
['element', 'style:writing-mode', 'lr-tb']]])
return automatic_styles | [
"def",
"get_automatic_styles",
"(",
"self",
")",
":",
"automatic_styles",
"=",
"[",
"'tag'",
",",
"'office:automatic-styles'",
"]",
"for",
"style_data",
"in",
"self",
".",
"style_config",
":",
"style_code",
"=",
"self",
".",
"style_config",
"[",
"style_data",
"]",
"style_data",
"=",
"list",
"(",
"style_data",
")",
"style",
"=",
"style_data",
".",
"pop",
"(",
"0",
")",
"if",
"style",
"==",
"'column'",
":",
"style_list",
"=",
"[",
"'tag'",
",",
"'style:style'",
",",
"[",
"'element'",
",",
"'style:name'",
",",
"style_code",
"]",
",",
"# Column 'co1' properties",
"[",
"'element'",
",",
"'style:family'",
",",
"'table-column'",
"]",
"]",
"tagline",
"=",
"[",
"'tagline'",
",",
"'style:table-column-properties'",
",",
"[",
"'element'",
",",
"'fo:break-before'",
",",
"'auto'",
"]",
"]",
"# unsure what break before means",
"for",
"set",
"in",
"style_data",
":",
"name",
",",
"value",
"=",
"set",
"if",
"name",
"==",
"'style:column-width'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:column-width'",
",",
"value",
"]",
")",
"style_list",
".",
"append",
"(",
"tagline",
")",
"automatic_styles",
".",
"append",
"(",
"style_list",
")",
"if",
"style",
"==",
"'row'",
":",
"style_list",
"=",
"[",
"'tag'",
",",
"'style:style'",
",",
"[",
"'element'",
",",
"'style:name'",
",",
"style_code",
"]",
",",
"# Column 'ro1' properties",
"[",
"'element'",
",",
"'style:family'",
",",
"'table-row'",
"]",
"]",
"tagline",
"=",
"[",
"'tagline'",
",",
"'style:table-row-properties'",
"]",
"for",
"set",
"in",
"style_data",
":",
"name",
",",
"value",
"=",
"set",
"if",
"name",
"==",
"'style:row-height'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:row-height'",
",",
"value",
"]",
")",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:break-before'",
",",
"'auto'",
"]",
")",
"#\t\t\t\ttagline.append(['element', 'style:use-optimal-row-height', 'true']) # Overrides settings",
"style_list",
".",
"append",
"(",
"tagline",
")",
"automatic_styles",
".",
"append",
"(",
"style_list",
")",
"if",
"style",
"==",
"'pagebreak'",
":",
"style_list",
"=",
"[",
"'tag'",
",",
"'style:style'",
",",
"[",
"'element'",
",",
"'style:name'",
",",
"style_code",
"]",
",",
"# Column 'ro1' properties",
"[",
"'element'",
",",
"'style:family'",
",",
"'table-row'",
"]",
"]",
"tagline",
"=",
"[",
"'tagline'",
",",
"'style:table-row-properties'",
"]",
"for",
"set",
"in",
"style_data",
":",
"name",
",",
"value",
"=",
"set",
"if",
"name",
"==",
"'style:row-height'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:row-height'",
",",
"value",
"]",
")",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:break-before'",
",",
"'page'",
"]",
")",
"#\t\t\t\ttagline.append(['element', 'style:use-optimal-row-height', 'true']) # Overrides settings",
"style_list",
".",
"append",
"(",
"tagline",
")",
"automatic_styles",
".",
"append",
"(",
"style_list",
")",
"if",
"style",
"==",
"'cell'",
":",
"style_list",
"=",
"[",
"'tag'",
",",
"'style:style'",
",",
"[",
"'element'",
",",
"'style:name'",
",",
"style_code",
"]",
",",
"# ce1 style",
"[",
"'element'",
",",
"'style:family'",
",",
"'table-cell'",
"]",
",",
"# cell",
"[",
"'element'",
",",
"'style:parent-style-name'",
",",
"'Default'",
"]",
"]",
"# parent is Default",
"# hack for currency",
"if",
"style_code",
"==",
"'ce1'",
":",
"style_list",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:data-style-name'",
",",
"'N104'",
"]",
")",
"# Cell Properties",
"tagline",
"=",
"[",
"'tag'",
",",
"'style:table-cell-properties'",
"]",
"tagline_additional",
"=",
"[",
"]",
"for",
"set",
"in",
"style_data",
":",
"name",
",",
"value",
"=",
"set",
"if",
"name",
"==",
"'background'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:background-color'",
",",
"value",
"]",
")",
"if",
"name",
"==",
"'backgroundimage'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:background-color'",
",",
"'transparent'",
"]",
")",
"# Additional tags added later",
"bgimagetag",
"=",
"[",
"'tagline'",
",",
"'style:background-image'",
"]",
"bgimagetag",
".",
"append",
"(",
"[",
"'element'",
",",
"'xlink:href'",
",",
"value",
"]",
")",
"bgimagetag",
".",
"append",
"(",
"[",
"'element'",
",",
"'xlink:type'",
",",
"'simple'",
"]",
")",
"bgimagetag",
".",
"append",
"(",
"[",
"'element'",
",",
"'xlink:actuate'",
",",
"'onLoad'",
"]",
")",
"tagline_additional",
".",
"append",
"(",
"bgimagetag",
")",
"if",
"name",
"==",
"'valign'",
":",
"if",
"value",
"in",
"[",
"'top'",
",",
"'bottom'",
",",
"'middle'",
"]",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:vertical-align'",
",",
"value",
"]",
")",
"if",
"name",
"==",
"'halign'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:text-align-source'",
",",
"'fix'",
"]",
")",
"if",
"value",
"in",
"[",
"'filled'",
"]",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:repeat-content'",
",",
"'true'",
"]",
")",
"else",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:repeat-content'",
",",
"'false'",
"]",
")",
"# Add any additional internal tags",
"while",
"tagline_additional",
":",
"tagadd",
"=",
"tagline_additional",
".",
"pop",
"(",
"0",
")",
"tagline",
".",
"append",
"(",
"tagadd",
")",
"style_list",
".",
"append",
"(",
"tagline",
")",
"# Paragraph Properties",
"tagline",
"=",
"[",
"'tagline'",
",",
"'style:paragraph-properties'",
"]",
"tagline_valid",
"=",
"False",
"for",
"set",
"in",
"style_data",
":",
"name",
",",
"value",
"=",
"set",
"if",
"name",
"==",
"'halign'",
":",
"tagline_valid",
"=",
"True",
"if",
"value",
"in",
"[",
"'center'",
"]",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:text-align'",
",",
"'center'",
"]",
")",
"if",
"value",
"in",
"[",
"'end'",
",",
"'right'",
"]",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:text-align'",
",",
"'end'",
"]",
")",
"if",
"value",
"in",
"[",
"'start'",
",",
"'filled'",
",",
"'left'",
"]",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:text-align'",
",",
"'start'",
"]",
")",
"if",
"value",
"in",
"[",
"'justify'",
"]",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:text-align'",
",",
"'justify'",
"]",
")",
"# Conditionally add the tagline",
"if",
"tagline_valid",
":",
"style_list",
".",
"append",
"(",
"tagline",
")",
"# Text Properties",
"tagline",
"=",
"[",
"'tagline'",
",",
"'style:text-properties'",
"]",
"for",
"set",
"in",
"style_data",
":",
"name",
",",
"value",
"=",
"set",
"if",
"name",
"==",
"'bold'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:font-weight'",
",",
"'bold'",
"]",
")",
"if",
"name",
"==",
"'italic'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:font-style'",
",",
"'italic'",
"]",
")",
"if",
"name",
"==",
"'underline'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:text-underline-style'",
",",
"'solid'",
"]",
")",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:text-underline-width'",
",",
"'auto'",
"]",
")",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'style:text-underline-color'",
",",
"'font-color'",
"]",
")",
"if",
"name",
"==",
"'color'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:color'",
",",
"value",
"]",
")",
"if",
"name",
"==",
"'fontsize'",
":",
"tagline",
".",
"append",
"(",
"[",
"'element'",
",",
"'fo:font-size'",
",",
"'%spt'",
"%",
"value",
"]",
")",
"style_list",
".",
"append",
"(",
"tagline",
")",
"automatic_styles",
".",
"append",
"(",
"style_list",
")",
"# Attach ta1 style",
"automatic_styles",
".",
"append",
"(",
"[",
"'tag'",
",",
"'style:style'",
",",
"[",
"'element'",
",",
"'style:name'",
",",
"'ta1'",
"]",
",",
"[",
"'element'",
",",
"'style:family'",
",",
"'table'",
"]",
",",
"[",
"'element'",
",",
"'style:master-page-name'",
",",
"'Default'",
"]",
",",
"[",
"'tagline'",
",",
"'style:table-properties'",
",",
"[",
"'element'",
",",
"'table:display'",
",",
"'true'",
"]",
",",
"[",
"'element'",
",",
"'style:writing-mode'",
",",
"'lr-tb'",
"]",
"]",
"]",
")",
"return",
"automatic_styles"
] | https://github.com/ledger/ledger/blob/8e79216887cf3c342dfca1ffa52cf4e6389d6de4/contrib/non-profit-audit-reports/ooolib2/__init__.py#L499-L645 | |
luliyucoordinate/Leetcode | 96afcdc54807d1d184e881a075d1dbf3371e31fb | src/0141-Linked-List-Cycle/0141.py | python | Solution.hasCycle | (self, head) | return False | :type head: ListNode
:rtype: bool | :type head: ListNode
:rtype: bool | [
":",
"type",
"head",
":",
"ListNode",
":",
"rtype",
":",
"bool"
] | def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
fast, slow = head, head
while fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False | [
"def",
"hasCycle",
"(",
"self",
",",
"head",
")",
":",
"if",
"head",
"==",
"None",
":",
"return",
"False",
"fast",
",",
"slow",
"=",
"head",
",",
"head",
"while",
"fast",
".",
"next",
"!=",
"None",
"and",
"fast",
".",
"next",
".",
"next",
"!=",
"None",
":",
"slow",
"=",
"slow",
".",
"next",
"fast",
"=",
"fast",
".",
"next",
".",
"next",
"if",
"slow",
"==",
"fast",
":",
"return",
"True",
"return",
"False"
] | https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0141-Linked-List-Cycle/0141.py#L8-L23 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | GridSizeEvent.GetPosition | (*args, **kwargs) | return _grid.GridSizeEvent_GetPosition(*args, **kwargs) | GetPosition(self) -> Point | GetPosition(self) -> Point | [
"GetPosition",
"(",
"self",
")",
"-",
">",
"Point"
] | def GetPosition(*args, **kwargs):
"""GetPosition(self) -> Point"""
return _grid.GridSizeEvent_GetPosition(*args, **kwargs) | [
"def",
"GetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridSizeEvent_GetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2361-L2363 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/xs/cache.py | python | XSCache.load | (self, temp=300.0) | Loads the cross sections from all data sources. | Loads the cross sections from all data sources. | [
"Loads",
"the",
"cross",
"sections",
"from",
"all",
"data",
"sources",
"."
] | def load(self, temp=300.0):
"""Loads the cross sections from all data sources."""
for ds in self.data_sources:
ds.load(temp=temp) | [
"def",
"load",
"(",
"self",
",",
"temp",
"=",
"300.0",
")",
":",
"for",
"ds",
"in",
"self",
".",
"data_sources",
":",
"ds",
".",
"load",
"(",
"temp",
"=",
"temp",
")"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/xs/cache.py#L155-L158 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/os.py | python | makedirs | (name, mode=0777) | makedirs(path [, mode=0777])
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist. This is
recursive. | makedirs(path [, mode=0777]) | [
"makedirs",
"(",
"path",
"[",
"mode",
"=",
"0777",
"]",
")"
] | def makedirs(name, mode=0777):
"""makedirs(path [, mode=0777])
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist. This is
recursive.
"""
head, tail = path.split(name)
if not tail:
head, tail = path.split(head)
if head and tail and not path.exists(head):
try:
makedirs(head, mode)
except OSError, e:
# be happy if someone already created the path
if e.errno != errno.EEXIST:
raise
if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists
return
mkdir(name, mode) | [
"def",
"makedirs",
"(",
"name",
",",
"mode",
"=",
"0777",
")",
":",
"head",
",",
"tail",
"=",
"path",
".",
"split",
"(",
"name",
")",
"if",
"not",
"tail",
":",
"head",
",",
"tail",
"=",
"path",
".",
"split",
"(",
"head",
")",
"if",
"head",
"and",
"tail",
"and",
"not",
"path",
".",
"exists",
"(",
"head",
")",
":",
"try",
":",
"makedirs",
"(",
"head",
",",
"mode",
")",
"except",
"OSError",
",",
"e",
":",
"# be happy if someone already created the path",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"if",
"tail",
"==",
"curdir",
":",
"# xxx/newdir/. exists if xxx/newdir exists",
"return",
"mkdir",
"(",
"name",
",",
"mode",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/os.py#L136-L157 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/akg/gpu/csr_reduce_sum.py | python | _csr_reduce_sum_akg | () | return | CSRReduceSum AutoDiff register | CSRReduceSum AutoDiff register | [
"CSRReduceSum",
"AutoDiff",
"register"
] | def _csr_reduce_sum_akg():
"""CSRReduceSum AutoDiff register"""
return | [
"def",
"_csr_reduce_sum_akg",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/akg/gpu/csr_reduce_sum.py#L31-L33 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py | python | Maildir.clean | (self) | Delete old files in "tmp". | Delete old files in "tmp". | [
"Delete",
"old",
"files",
"in",
"tmp",
"."
] | def clean(self):
"""Delete old files in "tmp"."""
now = time.time()
for entry in os.listdir(os.path.join(self._path, 'tmp')):
path = os.path.join(self._path, 'tmp', entry)
if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
os.remove(path) | [
"def",
"clean",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"'tmp'",
")",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"'tmp'",
",",
"entry",
")",
"if",
"now",
"-",
"os",
".",
"path",
".",
"getatime",
"(",
"path",
")",
">",
"129600",
":",
"# 60 * 60 * 36",
"os",
".",
"remove",
"(",
"path",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L457-L463 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | Geometry.Union | (self, *args) | return _ogr.Geometry_Union(self, *args) | r"""
Union(Geometry self, Geometry other) -> Geometry
OGRGeometryH OGR_G_Union(OGRGeometryH
hThis, OGRGeometryH hOther)
Compute union.
Generates a new geometry which is the region of union of the two
geometries operated on.
Geometry validity is not checked. In case you are unsure of the
validity of the input geometries, call IsValid() before, otherwise the
result might be wrong.
This function is the same as the C++ method OGRGeometry::Union().
This function is built on the GEOS library, check it for the
definition of the geometry operation. If OGR is built without the GEOS
library, this function will always fail, issuing a CPLE_NotSupported
error.
Parameters:
-----------
hThis: the geometry.
hOther: the other geometry.
a new geometry representing the union or NULL if an error occurs. | r"""
Union(Geometry self, Geometry other) -> Geometry
OGRGeometryH OGR_G_Union(OGRGeometryH
hThis, OGRGeometryH hOther) | [
"r",
"Union",
"(",
"Geometry",
"self",
"Geometry",
"other",
")",
"-",
">",
"Geometry",
"OGRGeometryH",
"OGR_G_Union",
"(",
"OGRGeometryH",
"hThis",
"OGRGeometryH",
"hOther",
")"
] | def Union(self, *args):
r"""
Union(Geometry self, Geometry other) -> Geometry
OGRGeometryH OGR_G_Union(OGRGeometryH
hThis, OGRGeometryH hOther)
Compute union.
Generates a new geometry which is the region of union of the two
geometries operated on.
Geometry validity is not checked. In case you are unsure of the
validity of the input geometries, call IsValid() before, otherwise the
result might be wrong.
This function is the same as the C++ method OGRGeometry::Union().
This function is built on the GEOS library, check it for the
definition of the geometry operation. If OGR is built without the GEOS
library, this function will always fail, issuing a CPLE_NotSupported
error.
Parameters:
-----------
hThis: the geometry.
hOther: the other geometry.
a new geometry representing the union or NULL if an error occurs.
"""
return _ogr.Geometry_Union(self, *args) | [
"def",
"Union",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"Geometry_Union",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L6374-L6405 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py | python | reduce_all | (input_tensor, axis=None, keepdims=False, name=None) | return _may_reduce_to_scalar(
keepdims, axis,
gen_math_ops._all(
input_tensor, _ReductionDims(input_tensor, axis), keepdims,
name=name)) | Computes the "logical and" of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[True, True], [False, False]])
tf.reduce_all(x) # False
tf.reduce_all(x, 0) # [False, False]
tf.reduce_all(x, 1) # [True, False]
```
Args:
input_tensor: The boolean tensor to reduce.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.all
@end_compatibility | Computes the "logical and" of elements across dimensions of a tensor. | [
"Computes",
"the",
"logical",
"and",
"of",
"elements",
"across",
"dimensions",
"of",
"a",
"tensor",
"."
] | def reduce_all(input_tensor, axis=None, keepdims=False, name=None):
"""Computes the "logical and" of elements across dimensions of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keepdims` is true, the reduced dimensions
are retained with length 1.
If `axis` is None, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[True, True], [False, False]])
tf.reduce_all(x) # False
tf.reduce_all(x, 0) # [False, False]
tf.reduce_all(x, 1) # [True, False]
```
Args:
input_tensor: The boolean tensor to reduce.
axis: The dimensions to reduce. If `None` (the default), reduces all
dimensions. Must be in the range `[-rank(input_tensor),
rank(input_tensor))`.
keepdims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.all
@end_compatibility
"""
keepdims = False if keepdims is None else keepdims
return _may_reduce_to_scalar(
keepdims, axis,
gen_math_ops._all(
input_tensor, _ReductionDims(input_tensor, axis), keepdims,
name=name)) | [
"def",
"reduce_all",
"(",
"input_tensor",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"keepdims",
"=",
"False",
"if",
"keepdims",
"is",
"None",
"else",
"keepdims",
"return",
"_may_reduce_to_scalar",
"(",
"keepdims",
",",
"axis",
",",
"gen_math_ops",
".",
"_all",
"(",
"input_tensor",
",",
"_ReductionDims",
"(",
"input_tensor",
",",
"axis",
")",
",",
"keepdims",
",",
"name",
"=",
"name",
")",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py#L2266-L2306 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/util/version.py | python | ModifyOptionsCompat | (options, parser) | Support compatibility with old versions.
Specifically, for old versions that considered the first two
positional arguments shorthands for --input and --output. | Support compatibility with old versions. | [
"Support",
"compatibility",
"with",
"old",
"versions",
"."
] | def ModifyOptionsCompat(options, parser):
"""Support compatibility with old versions.
Specifically, for old versions that considered the first two
positional arguments shorthands for --input and --output.
"""
while len(options.args) and (options.input is None or options.output is None):
if options.input is None:
options.input = options.args.pop(0)
elif options.output is None:
options.output = options.args.pop(0)
if options.args:
parser.error('Unexpected arguments: %r' % options.args) | [
"def",
"ModifyOptionsCompat",
"(",
"options",
",",
"parser",
")",
":",
"while",
"len",
"(",
"options",
".",
"args",
")",
"and",
"(",
"options",
".",
"input",
"is",
"None",
"or",
"options",
".",
"output",
"is",
"None",
")",
":",
"if",
"options",
".",
"input",
"is",
"None",
":",
"options",
".",
"input",
"=",
"options",
".",
"args",
".",
"pop",
"(",
"0",
")",
"elif",
"options",
".",
"output",
"is",
"None",
":",
"options",
".",
"output",
"=",
"options",
".",
"args",
".",
"pop",
"(",
"0",
")",
"if",
"options",
".",
"args",
":",
"parser",
".",
"error",
"(",
"'Unexpected arguments: %r'",
"%",
"options",
".",
"args",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/util/version.py#L172-L184 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/cephfs/kernel_mount.py | python | KernelMount.disable_dynamic_debug | (self) | Disable the dynamic debug. | Disable the dynamic debug. | [
"Disable",
"the",
"dynamic",
"debug",
"."
] | def disable_dynamic_debug(self):
"""
Disable the dynamic debug.
"""
self._dynamic_debug_control(False) | [
"def",
"disable_dynamic_debug",
"(",
"self",
")",
":",
"self",
".",
"_dynamic_debug_control",
"(",
"False",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/cephfs/kernel_mount.py#L285-L289 | ||
robotics/open_abb | 211630855bbf2b529910cac129b20cffc5c19ad6 | abb_node/packages/abb_communications/abb.py | python | Robot.set_zone | (self,
zone_key = 'z1',
point_motion = False,
manual_zone = []) | Sets the motion zone of the robot. This can also be thought of as
the flyby zone, AKA if the robot is going from point A -> B -> C,
how close do we have to pass by B to get to C
zone_key: uses values from RAPID handbook (stored here in zone_dict)
with keys 'z*', you should probably use these
point_motion: go to point exactly, and stop briefly before moving on
manual_zone = [pzone_tcp, pzone_ori, zone_ori]
pzone_tcp: mm, radius from goal where robot tool centerpoint
is not rigidly constrained
pzone_ori: mm, radius from goal where robot tool orientation
is not rigidly constrained
zone_ori: degrees, zone size for the tool reorientation | Sets the motion zone of the robot. This can also be thought of as
the flyby zone, AKA if the robot is going from point A -> B -> C,
how close do we have to pass by B to get to C
zone_key: uses values from RAPID handbook (stored here in zone_dict)
with keys 'z*', you should probably use these | [
"Sets",
"the",
"motion",
"zone",
"of",
"the",
"robot",
".",
"This",
"can",
"also",
"be",
"thought",
"of",
"as",
"the",
"flyby",
"zone",
"AKA",
"if",
"the",
"robot",
"is",
"going",
"from",
"point",
"A",
"-",
">",
"B",
"-",
">",
"C",
"how",
"close",
"do",
"we",
"have",
"to",
"pass",
"by",
"B",
"to",
"get",
"to",
"C",
"zone_key",
":",
"uses",
"values",
"from",
"RAPID",
"handbook",
"(",
"stored",
"here",
"in",
"zone_dict",
")",
"with",
"keys",
"z",
"*",
"you",
"should",
"probably",
"use",
"these"
] | def set_zone(self,
zone_key = 'z1',
point_motion = False,
manual_zone = []):
zone_dict = {'z0' : [.3,.3,.03],
'z1' : [1,1,.1],
'z5' : [5,8,.8],
'z10' : [10,15,1.5],
'z15' : [15,23,2.3],
'z20' : [20,30,3],
'z30' : [30,45,4.5],
'z50' : [50,75,7.5],
'z100': [100,150,15],
'z200': [200,300,30]}
'''
Sets the motion zone of the robot. This can also be thought of as
the flyby zone, AKA if the robot is going from point A -> B -> C,
how close do we have to pass by B to get to C
zone_key: uses values from RAPID handbook (stored here in zone_dict)
with keys 'z*', you should probably use these
point_motion: go to point exactly, and stop briefly before moving on
manual_zone = [pzone_tcp, pzone_ori, zone_ori]
pzone_tcp: mm, radius from goal where robot tool centerpoint
is not rigidly constrained
pzone_ori: mm, radius from goal where robot tool orientation
is not rigidly constrained
zone_ori: degrees, zone size for the tool reorientation
'''
if point_motion:
zone = [0,0,0]
elif len(manual_zone) == 3:
zone = manual_zone
elif zone_key in zone_dict.keys():
zone = zone_dict[zone_key]
else: return False
msg = "09 "
msg += str(int(point_motion)) + " "
msg += format(zone[0], "+08.4f") + " "
msg += format(zone[1], "+08.4f") + " "
msg += format(zone[2], "+08.4f") + " #"
self.send(msg) | [
"def",
"set_zone",
"(",
"self",
",",
"zone_key",
"=",
"'z1'",
",",
"point_motion",
"=",
"False",
",",
"manual_zone",
"=",
"[",
"]",
")",
":",
"zone_dict",
"=",
"{",
"'z0'",
":",
"[",
".3",
",",
".3",
",",
".03",
"]",
",",
"'z1'",
":",
"[",
"1",
",",
"1",
",",
".1",
"]",
",",
"'z5'",
":",
"[",
"5",
",",
"8",
",",
".8",
"]",
",",
"'z10'",
":",
"[",
"10",
",",
"15",
",",
"1.5",
"]",
",",
"'z15'",
":",
"[",
"15",
",",
"23",
",",
"2.3",
"]",
",",
"'z20'",
":",
"[",
"20",
",",
"30",
",",
"3",
"]",
",",
"'z30'",
":",
"[",
"30",
",",
"45",
",",
"4.5",
"]",
",",
"'z50'",
":",
"[",
"50",
",",
"75",
",",
"7.5",
"]",
",",
"'z100'",
":",
"[",
"100",
",",
"150",
",",
"15",
"]",
",",
"'z200'",
":",
"[",
"200",
",",
"300",
",",
"30",
"]",
"}",
"if",
"point_motion",
":",
"zone",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"elif",
"len",
"(",
"manual_zone",
")",
"==",
"3",
":",
"zone",
"=",
"manual_zone",
"elif",
"zone_key",
"in",
"zone_dict",
".",
"keys",
"(",
")",
":",
"zone",
"=",
"zone_dict",
"[",
"zone_key",
"]",
"else",
":",
"return",
"False",
"msg",
"=",
"\"09 \"",
"msg",
"+=",
"str",
"(",
"int",
"(",
"point_motion",
")",
")",
"+",
"\" \"",
"msg",
"+=",
"format",
"(",
"zone",
"[",
"0",
"]",
",",
"\"+08.4f\"",
")",
"+",
"\" \"",
"msg",
"+=",
"format",
"(",
"zone",
"[",
"1",
"]",
",",
"\"+08.4f\"",
")",
"+",
"\" \"",
"msg",
"+=",
"format",
"(",
"zone",
"[",
"2",
"]",
",",
"\"+08.4f\"",
")",
"+",
"\" #\"",
"self",
".",
"send",
"(",
"msg",
")"
] | https://github.com/robotics/open_abb/blob/211630855bbf2b529910cac129b20cffc5c19ad6/abb_node/packages/abb_communications/abb.py#L176-L221 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/distributed/AsyncRequest.py | python | AsyncRequest.askForObjectField | (
self, dclassName, fieldName, doId, key = None, context = None) | Request an already created object, i.e. read from database. | Request an already created object, i.e. read from database. | [
"Request",
"an",
"already",
"created",
"object",
"i",
".",
"e",
".",
"read",
"from",
"database",
"."
] | def askForObjectField(
self, dclassName, fieldName, doId, key = None, context = None):
"""
Request an already created object, i.e. read from database.
"""
assert AsyncRequest.notify.debugCall()
if key is None:
# default the dictionary key to the fieldName
key = fieldName
assert doId
if context is None:
context = self.air.allocateContext()
self.air.contextToClassName[context] = dclassName
self.acceptOnce(
"doFieldResponse-%s"%(context,),
self._checkCompletion, [key])
self.neededObjects[key] = None
self.air.queryObjectField(dclassName, fieldName, doId, context)
self._resetTimeoutTask() | [
"def",
"askForObjectField",
"(",
"self",
",",
"dclassName",
",",
"fieldName",
",",
"doId",
",",
"key",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"assert",
"AsyncRequest",
".",
"notify",
".",
"debugCall",
"(",
")",
"if",
"key",
"is",
"None",
":",
"# default the dictionary key to the fieldName",
"key",
"=",
"fieldName",
"assert",
"doId",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"self",
".",
"air",
".",
"allocateContext",
"(",
")",
"self",
".",
"air",
".",
"contextToClassName",
"[",
"context",
"]",
"=",
"dclassName",
"self",
".",
"acceptOnce",
"(",
"\"doFieldResponse-%s\"",
"%",
"(",
"context",
",",
")",
",",
"self",
".",
"_checkCompletion",
",",
"[",
"key",
"]",
")",
"self",
".",
"neededObjects",
"[",
"key",
"]",
"=",
"None",
"self",
".",
"air",
".",
"queryObjectField",
"(",
"dclassName",
",",
"fieldName",
",",
"doId",
",",
"context",
")",
"self",
".",
"_resetTimeoutTask",
"(",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/distributed/AsyncRequest.py#L79-L99 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/tracing.py | python | TracingTrack.GetMatchingMainFrameEvents | (self, category, name) | return [e for e in matching_events
if 'frame' in e.args and e.args['frame'] == self.GetMainFrameID()] | Gets events matching |category| and |name| that occur in the main frame.
Events without a 'frame' key in their |args| are discarded. | Gets events matching |category| and |name| that occur in the main frame. | [
"Gets",
"events",
"matching",
"|category|",
"and",
"|name|",
"that",
"occur",
"in",
"the",
"main",
"frame",
"."
] | def GetMatchingMainFrameEvents(self, category, name):
"""Gets events matching |category| and |name| that occur in the main frame.
Events without a 'frame' key in their |args| are discarded.
"""
matching_events = self.GetMatchingEvents(category, name)
return [e for e in matching_events
if 'frame' in e.args and e.args['frame'] == self.GetMainFrameID()] | [
"def",
"GetMatchingMainFrameEvents",
"(",
"self",
",",
"category",
",",
"name",
")",
":",
"matching_events",
"=",
"self",
".",
"GetMatchingEvents",
"(",
"category",
",",
"name",
")",
"return",
"[",
"e",
"for",
"e",
"in",
"matching_events",
"if",
"'frame'",
"in",
"e",
".",
"args",
"and",
"e",
".",
"args",
"[",
"'frame'",
"]",
"==",
"self",
".",
"GetMainFrameID",
"(",
")",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/tracing.py#L80-L87 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | Bracket.parseliteral | (self, pos) | return self | Parse a literal bracket | Parse a literal bracket | [
"Parse",
"a",
"literal",
"bracket"
] | def parseliteral(self, pos):
"Parse a literal bracket"
self.parsecomplete(pos, self.innerliteral)
return self | [
"def",
"parseliteral",
"(",
"self",
",",
"pos",
")",
":",
"self",
".",
"parsecomplete",
"(",
"pos",
",",
"self",
".",
"innerliteral",
")",
"return",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L2779-L2782 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/xml/sax/handler.py | python | ContentHandler.startElement | (self, name, attrs) | Signals the start of an element in non-namespace mode.
The name parameter contains the raw XML 1.0 name of the
element type as a string and the attrs parameter holds an
instance of the Attributes class containing the attributes of
the element. | Signals the start of an element in non-namespace mode. | [
"Signals",
"the",
"start",
"of",
"an",
"element",
"in",
"non",
"-",
"namespace",
"mode",
"."
] | def startElement(self, name, attrs):
"""Signals the start of an element in non-namespace mode.
The name parameter contains the raw XML 1.0 name of the
element type as a string and the attrs parameter holds an
instance of the Attributes class containing the attributes of
the element.""" | [
"def",
"startElement",
"(",
"self",
",",
"name",
",",
"attrs",
")",
":"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/xml/sax/handler.py#L126-L132 | ||
martinmoene/optional-lite | a006f229a77b3b2dacf927e4029b8c1c60c86b52 | script/create-cov-rpt.py | python | executable_folder | ( f ) | return os.path.dirname( os.path.abspath(f) ) | Folder where the xecutable is | Folder where the xecutable is | [
"Folder",
"where",
"the",
"xecutable",
"is"
] | def executable_folder( f ):
"""Folder where the xecutable is"""
return os.path.dirname( os.path.abspath(f) ) | [
"def",
"executable_folder",
"(",
"f",
")",
":",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"f",
")",
")"
] | https://github.com/martinmoene/optional-lite/blob/a006f229a77b3b2dacf927e4029b8c1c60c86b52/script/create-cov-rpt.py#L146-L148 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py | python | Netrc.get_hosts | (self) | return self.__hosts.keys() | Return a list of hosts mentioned in the .netrc file. | Return a list of hosts mentioned in the .netrc file. | [
"Return",
"a",
"list",
"of",
"hosts",
"mentioned",
"in",
"the",
".",
"netrc",
"file",
"."
] | def get_hosts(self):
"""Return a list of hosts mentioned in the .netrc file."""
return self.__hosts.keys() | [
"def",
"get_hosts",
"(",
"self",
")",
":",
"return",
"self",
".",
"__hosts",
".",
"keys",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py#L960-L962 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/oldnumeric/ma.py | python | MaskedArray._set_shape | (self, newshape) | Set the array's shape. | Set the array's shape. | [
"Set",
"the",
"array",
"s",
"shape",
"."
] | def _set_shape (self, newshape):
"Set the array's shape."
self._data.shape = newshape
if self._mask is not nomask:
self._mask = self._mask.copy()
self._mask.shape = newshape | [
"def",
"_set_shape",
"(",
"self",
",",
"newshape",
")",
":",
"self",
".",
"_data",
".",
"shape",
"=",
"newshape",
"if",
"self",
".",
"_mask",
"is",
"not",
"nomask",
":",
"self",
".",
"_mask",
"=",
"self",
".",
"_mask",
".",
"copy",
"(",
")",
"self",
".",
"_mask",
".",
"shape",
"=",
"newshape"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L665-L670 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/TemplatePyMod/DocumentObject.py | python | ViewProvider.DisplayModes | (self) | return self.__vobject__.listDisplayModes() | lists the display modes of this object | lists the display modes of this object | [
"lists",
"the",
"display",
"modes",
"of",
"this",
"object"
] | def DisplayModes(self):
"lists the display modes of this object"
return self.__vobject__.listDisplayModes() | [
"def",
"DisplayModes",
"(",
"self",
")",
":",
"return",
"self",
".",
"__vobject__",
".",
"listDisplayModes",
"(",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/TemplatePyMod/DocumentObject.py#L241-L243 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/usb_gadget/hid_gadget.py | python | HidCompositeFeature.ClassControlRead | (self, recipient, request, value, index, length) | Handle class-specific control requests.
See Device Class Definition for Human Interface Devices (HID) Version 1.11
section 7.2.
Args:
recipient: Request recipient (device, interface, endpoint, etc.)
request: bRequest field of the setup packet.
value: wValue field of the setup packet.
index: wIndex field of the setup packet.
length: Maximum amount of data the host expects the device to return.
Returns:
A buffer to return to the USB host with len <= length on success or
None to stall the pipe. | Handle class-specific control requests. | [
"Handle",
"class",
"-",
"specific",
"control",
"requests",
"."
] | def ClassControlRead(self, recipient, request, value, index, length):
"""Handle class-specific control requests.
See Device Class Definition for Human Interface Devices (HID) Version 1.11
section 7.2.
Args:
recipient: Request recipient (device, interface, endpoint, etc.)
request: bRequest field of the setup packet.
value: wValue field of the setup packet.
index: wIndex field of the setup packet.
length: Maximum amount of data the host expects the device to return.
Returns:
A buffer to return to the USB host with len <= length on success or
None to stall the pipe.
"""
if recipient != usb_constants.Recipient.INTERFACE:
return None
if index != self._interface_number:
return None
if request == hid_constants.Request.GET_REPORT:
report_type, report_id = value >> 8, value & 0xFF
print ('GetReport(type={}, id={}, length={})'
.format(report_type, report_id, length))
return self.GetReport(report_type, report_id, length) | [
"def",
"ClassControlRead",
"(",
"self",
",",
"recipient",
",",
"request",
",",
"value",
",",
"index",
",",
"length",
")",
":",
"if",
"recipient",
"!=",
"usb_constants",
".",
"Recipient",
".",
"INTERFACE",
":",
"return",
"None",
"if",
"index",
"!=",
"self",
".",
"_interface_number",
":",
"return",
"None",
"if",
"request",
"==",
"hid_constants",
".",
"Request",
".",
"GET_REPORT",
":",
"report_type",
",",
"report_id",
"=",
"value",
">>",
"8",
",",
"value",
"&",
"0xFF",
"print",
"(",
"'GetReport(type={}, id={}, length={})'",
".",
"format",
"(",
"report_type",
",",
"report_id",
",",
"length",
")",
")",
"return",
"self",
".",
"GetReport",
"(",
"report_type",
",",
"report_id",
",",
"length",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/usb_gadget/hid_gadget.py#L136-L162 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py | python | IMetadataProvider.has_metadata | (name) | Does the package's distribution contain the named metadata? | Does the package's distribution contain the named metadata? | [
"Does",
"the",
"package",
"s",
"distribution",
"contain",
"the",
"named",
"metadata?"
] | def has_metadata(name):
"""Does the package's distribution contain the named metadata?""" | [
"def",
"has_metadata",
"(",
"name",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py#L504-L505 | ||
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/__init__.py | python | StreamStreamClientInterceptor.intercept_stream_stream | (self, continuation, client_call_details,
request_iterator) | Intercepts a stream-stream invocation.
Args:
continuation: A function that proceeds with the invocation by
executing the next interceptor in chain or invoking the
actual RPC on the underlying Channel. It is the interceptor's
responsibility to call it if it decides to move the RPC forward.
The interceptor can use
`response_iterator = continuation(client_call_details, request_iterator)`
to continue with the RPC. `continuation` returns an object that is
both a Call for the RPC and an iterator for response values.
Drawing response values from the returned Call-iterator may
raise RpcError indicating termination of the RPC with non-OK
status.
client_call_details: A ClientCallDetails object describing the
outgoing RPC.
request_iterator: An iterator that yields request values for the RPC.
Returns:
An object that is both a Call for the RPC and an iterator of
response values. Drawing response values from the returned
Call-iterator may raise RpcError indicating termination of
the RPC with non-OK status. This object *should* also fulfill the
Future interface, though it may not. | Intercepts a stream-stream invocation. | [
"Intercepts",
"a",
"stream",
"-",
"stream",
"invocation",
"."
] | def intercept_stream_stream(self, continuation, client_call_details,
request_iterator):
"""Intercepts a stream-stream invocation.
Args:
continuation: A function that proceeds with the invocation by
executing the next interceptor in chain or invoking the
actual RPC on the underlying Channel. It is the interceptor's
responsibility to call it if it decides to move the RPC forward.
The interceptor can use
`response_iterator = continuation(client_call_details, request_iterator)`
to continue with the RPC. `continuation` returns an object that is
both a Call for the RPC and an iterator for response values.
Drawing response values from the returned Call-iterator may
raise RpcError indicating termination of the RPC with non-OK
status.
client_call_details: A ClientCallDetails object describing the
outgoing RPC.
request_iterator: An iterator that yields request values for the RPC.
Returns:
An object that is both a Call for the RPC and an iterator of
response values. Drawing response values from the returned
Call-iterator may raise RpcError indicating termination of
the RPC with non-OK status. This object *should* also fulfill the
Future interface, though it may not.
"""
raise NotImplementedError() | [
"def",
"intercept_stream_stream",
"(",
"self",
",",
"continuation",
",",
"client_call_details",
",",
"request_iterator",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/__init__.py#L532-L559 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/rcnn/rcnn/dataset/pascal_voc.py | python | PascalVOC.gt_roidb | (self) | return gt_roidb | return ground truth image regions database
:return: imdb[image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped'] | return ground truth image regions database
:return: imdb[image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped'] | [
"return",
"ground",
"truth",
"image",
"regions",
"database",
":",
"return",
":",
"imdb",
"[",
"image_index",
"]",
"[",
"boxes",
"gt_classes",
"gt_overlaps",
"flipped",
"]"
] | def gt_roidb(self):
"""
return ground truth image regions database
:return: imdb[image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
"""
cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl')
if os.path.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = cPickle.load(fid)
logger.info('%s gt roidb loaded from %s' % (self.name, cache_file))
return roidb
gt_roidb = [self.load_pascal_annotation(index) for index in self.image_set_index]
with open(cache_file, 'wb') as fid:
cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL)
logger.info('%s wrote gt roidb to %s' % (self.name, cache_file))
return gt_roidb | [
"def",
"gt_roidb",
"(",
"self",
")",
":",
"cache_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_path",
",",
"self",
".",
"name",
"+",
"'_gt_roidb.pkl'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"cache_file",
")",
":",
"with",
"open",
"(",
"cache_file",
",",
"'rb'",
")",
"as",
"fid",
":",
"roidb",
"=",
"cPickle",
".",
"load",
"(",
"fid",
")",
"logger",
".",
"info",
"(",
"'%s gt roidb loaded from %s'",
"%",
"(",
"self",
".",
"name",
",",
"cache_file",
")",
")",
"return",
"roidb",
"gt_roidb",
"=",
"[",
"self",
".",
"load_pascal_annotation",
"(",
"index",
")",
"for",
"index",
"in",
"self",
".",
"image_set_index",
"]",
"with",
"open",
"(",
"cache_file",
",",
"'wb'",
")",
"as",
"fid",
":",
"cPickle",
".",
"dump",
"(",
"gt_roidb",
",",
"fid",
",",
"cPickle",
".",
"HIGHEST_PROTOCOL",
")",
"logger",
".",
"info",
"(",
"'%s wrote gt roidb to %s'",
"%",
"(",
"self",
".",
"name",
",",
"cache_file",
")",
")",
"return",
"gt_roidb"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/rcnn/rcnn/dataset/pascal_voc.py#L89-L106 | |
envoyproxy/envoy-wasm | ab5d9381fdf92a1efa0b87cff80036b5b3e81198 | tools/protoxform/protoprint.py | python | FormatTypeContextComments | (type_context, annotation_xforms=None) | return leading, trailing | Format the leading/trailing comments in a given TypeContext.
Args:
type_context: contextual information for message/enum/field.
annotation_xforms: a dict of transformers for annotations in leading
comment.
Returns:
Tuple of formatted leading and trailing comment blocks. | Format the leading/trailing comments in a given TypeContext. | [
"Format",
"the",
"leading",
"/",
"trailing",
"comments",
"in",
"a",
"given",
"TypeContext",
"."
] | def FormatTypeContextComments(type_context, annotation_xforms=None):
"""Format the leading/trailing comments in a given TypeContext.
Args:
type_context: contextual information for message/enum/field.
annotation_xforms: a dict of transformers for annotations in leading
comment.
Returns:
Tuple of formatted leading and trailing comment blocks.
"""
leading_comment = type_context.leading_comment
if annotation_xforms:
leading_comment = leading_comment.getCommentWithTransforms(annotation_xforms)
leading = FormatComments(list(type_context.leading_detached_comments) + [leading_comment.raw])
trailing = FormatBlock(FormatComments([type_context.trailing_comment]))
return leading, trailing | [
"def",
"FormatTypeContextComments",
"(",
"type_context",
",",
"annotation_xforms",
"=",
"None",
")",
":",
"leading_comment",
"=",
"type_context",
".",
"leading_comment",
"if",
"annotation_xforms",
":",
"leading_comment",
"=",
"leading_comment",
".",
"getCommentWithTransforms",
"(",
"annotation_xforms",
")",
"leading",
"=",
"FormatComments",
"(",
"list",
"(",
"type_context",
".",
"leading_detached_comments",
")",
"+",
"[",
"leading_comment",
".",
"raw",
"]",
")",
"trailing",
"=",
"FormatBlock",
"(",
"FormatComments",
"(",
"[",
"type_context",
".",
"trailing_comment",
"]",
")",
")",
"return",
"leading",
",",
"trailing"
] | https://github.com/envoyproxy/envoy-wasm/blob/ab5d9381fdf92a1efa0b87cff80036b5b3e81198/tools/protoxform/protoprint.py#L155-L171 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/__init__.py | python | _get_frame_op_default_axis | (name) | Only DataFrame cares about default_axis, specifically:
special methods have default_axis=None and flex methods
have default_axis='columns'.
Parameters
----------
name : str
Returns
-------
default_axis: str or None | Only DataFrame cares about default_axis, specifically:
special methods have default_axis=None and flex methods
have default_axis='columns'. | [
"Only",
"DataFrame",
"cares",
"about",
"default_axis",
"specifically",
":",
"special",
"methods",
"have",
"default_axis",
"=",
"None",
"and",
"flex",
"methods",
"have",
"default_axis",
"=",
"columns",
"."
] | def _get_frame_op_default_axis(name):
"""
Only DataFrame cares about default_axis, specifically:
special methods have default_axis=None and flex methods
have default_axis='columns'.
Parameters
----------
name : str
Returns
-------
default_axis: str or None
"""
if name.replace("__r", "__") in ["__and__", "__or__", "__xor__"]:
# bool methods
return "columns"
elif name.startswith("__"):
# __add__, __mul__, ...
return None
else:
# add, mul, ...
return "columns" | [
"def",
"_get_frame_op_default_axis",
"(",
"name",
")",
":",
"if",
"name",
".",
"replace",
"(",
"\"__r\"",
",",
"\"__\"",
")",
"in",
"[",
"\"__and__\"",
",",
"\"__or__\"",
",",
"\"__xor__\"",
"]",
":",
"# bool methods",
"return",
"\"columns\"",
"elif",
"name",
".",
"startswith",
"(",
"\"__\"",
")",
":",
"# __add__, __mul__, ...",
"return",
"None",
"else",
":",
"# add, mul, ...",
"return",
"\"columns\""
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/__init__.py#L221-L243 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/rfc822.py | python | AddrlistClass.getcomment | (self) | return self.getdelimited('(', ')\r', 1) | Get a parenthesis-delimited fragment from self's field. | Get a parenthesis-delimited fragment from self's field. | [
"Get",
"a",
"parenthesis",
"-",
"delimited",
"fragment",
"from",
"self",
"s",
"field",
"."
] | def getcomment(self):
"""Get a parenthesis-delimited fragment from self's field."""
return self.getdelimited('(', ')\r', 1) | [
"def",
"getcomment",
"(",
"self",
")",
":",
"return",
"self",
".",
"getdelimited",
"(",
"'('",
",",
"')\\r'",
",",
"1",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/rfc822.py#L725-L727 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/k-th-smallest-in-lexicographical-order.py | python | Solution2.findKthNumber | (self, n, k) | return findKthNumberHelper(n, k, 0, 0)[0] | :type n: int
:type k: int
:rtype: int | :type n: int
:type k: int
:rtype: int | [
":",
"type",
"n",
":",
"int",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"int"
] | def findKthNumber(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
def count(n, prefix):
result, number = 0, 1
while prefix <= n:
result += number
prefix *= 10
number *= 10
result -= max(number/10 - (n - prefix/10 + 1), 0)
return result
def findKthNumberHelper(n, k, cur, index):
if cur:
index += 1
if index == k:
return (cur, index)
i = int(cur == 0)
while i <= 9:
cur = cur * 10 + i
cnt = count(n, cur)
if k > cnt + index:
index += cnt
elif cur <= n:
result = findKthNumberHelper(n, k, cur, index)
if result[0]:
return result
i += 1
cur /= 10
return (0, index)
return findKthNumberHelper(n, k, 0, 0)[0] | [
"def",
"findKthNumber",
"(",
"self",
",",
"n",
",",
"k",
")",
":",
"def",
"count",
"(",
"n",
",",
"prefix",
")",
":",
"result",
",",
"number",
"=",
"0",
",",
"1",
"while",
"prefix",
"<=",
"n",
":",
"result",
"+=",
"number",
"prefix",
"*=",
"10",
"number",
"*=",
"10",
"result",
"-=",
"max",
"(",
"number",
"/",
"10",
"-",
"(",
"n",
"-",
"prefix",
"/",
"10",
"+",
"1",
")",
",",
"0",
")",
"return",
"result",
"def",
"findKthNumberHelper",
"(",
"n",
",",
"k",
",",
"cur",
",",
"index",
")",
":",
"if",
"cur",
":",
"index",
"+=",
"1",
"if",
"index",
"==",
"k",
":",
"return",
"(",
"cur",
",",
"index",
")",
"i",
"=",
"int",
"(",
"cur",
"==",
"0",
")",
"while",
"i",
"<=",
"9",
":",
"cur",
"=",
"cur",
"*",
"10",
"+",
"i",
"cnt",
"=",
"count",
"(",
"n",
",",
"cur",
")",
"if",
"k",
">",
"cnt",
"+",
"index",
":",
"index",
"+=",
"cnt",
"elif",
"cur",
"<=",
"n",
":",
"result",
"=",
"findKthNumberHelper",
"(",
"n",
",",
"k",
",",
"cur",
",",
"index",
")",
"if",
"result",
"[",
"0",
"]",
":",
"return",
"result",
"i",
"+=",
"1",
"cur",
"/=",
"10",
"return",
"(",
"0",
",",
"index",
")",
"return",
"findKthNumberHelper",
"(",
"n",
",",
"k",
",",
"0",
",",
"0",
")",
"[",
"0",
"]"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/k-th-smallest-in-lexicographical-order.py#L51-L86 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/ops.py | python | pack | (labeled_tensors, new_axis, axis_position=0, name=None) | Pack tensors along a new axis.
See tf.pack.
Args:
labeled_tensors: The input tensors, which must have identical axes.
new_axis: The name of the new axis, or a tuple containing the name
and coordinate labels.
axis_position: Optional integer position at which to insert the new axis.
name: Optional op name.
Returns:
The packed tensors as a single LabeledTensor, with `new_axis` in the given
`axis_position`.
Raises:
ValueError: If fewer than one input tensors is provided, or if the tensors
don't have identical axes. | Pack tensors along a new axis. | [
"Pack",
"tensors",
"along",
"a",
"new",
"axis",
"."
] | def pack(labeled_tensors, new_axis, axis_position=0, name=None):
"""Pack tensors along a new axis.
See tf.pack.
Args:
labeled_tensors: The input tensors, which must have identical axes.
new_axis: The name of the new axis, or a tuple containing the name
and coordinate labels.
axis_position: Optional integer position at which to insert the new axis.
name: Optional op name.
Returns:
The packed tensors as a single LabeledTensor, with `new_axis` in the given
`axis_position`.
Raises:
ValueError: If fewer than one input tensors is provided, or if the tensors
don't have identical axes.
"""
with ops.name_scope(name, 'lt_pack', labeled_tensors) as scope:
labeled_tensors = [
core.convert_to_labeled_tensor(lt) for lt in labeled_tensors
]
if len(labeled_tensors) < 1:
raise ValueError('pack expects at least 1 tensors, but received %s' %
labeled_tensors)
axes_0 = labeled_tensors[0].axes
for t in labeled_tensors:
if t.axes != axes_0:
raise ValueError('Non-identical axes. Expected %s but got %s' %
(axes_0, t.axes))
pack_op = array_ops.stack(
[t.tensor for t in labeled_tensors], axis=axis_position, name=scope)
axes = list(axes_0.values())
axes.insert(axis_position, new_axis)
return core.LabeledTensor(pack_op, axes) | [
"def",
"pack",
"(",
"labeled_tensors",
",",
"new_axis",
",",
"axis_position",
"=",
"0",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'lt_pack'",
",",
"labeled_tensors",
")",
"as",
"scope",
":",
"labeled_tensors",
"=",
"[",
"core",
".",
"convert_to_labeled_tensor",
"(",
"lt",
")",
"for",
"lt",
"in",
"labeled_tensors",
"]",
"if",
"len",
"(",
"labeled_tensors",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'pack expects at least 1 tensors, but received %s'",
"%",
"labeled_tensors",
")",
"axes_0",
"=",
"labeled_tensors",
"[",
"0",
"]",
".",
"axes",
"for",
"t",
"in",
"labeled_tensors",
":",
"if",
"t",
".",
"axes",
"!=",
"axes_0",
":",
"raise",
"ValueError",
"(",
"'Non-identical axes. Expected %s but got %s'",
"%",
"(",
"axes_0",
",",
"t",
".",
"axes",
")",
")",
"pack_op",
"=",
"array_ops",
".",
"stack",
"(",
"[",
"t",
".",
"tensor",
"for",
"t",
"in",
"labeled_tensors",
"]",
",",
"axis",
"=",
"axis_position",
",",
"name",
"=",
"scope",
")",
"axes",
"=",
"list",
"(",
"axes_0",
".",
"values",
"(",
")",
")",
"axes",
".",
"insert",
"(",
"axis_position",
",",
"new_axis",
")",
"return",
"core",
".",
"LabeledTensor",
"(",
"pack_op",
",",
"axes",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/ops.py#L218-L257 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/resource_variable_ops.py | python | BaseResourceVariable.scatter_max | (self, sparse_delta, use_locking=False, name=None) | return self._lazy_read(
gen_resource_variable_ops.resource_scatter_max(
self.handle,
sparse_delta.indices,
ops.convert_to_tensor(sparse_delta.values, self.dtype),
name=name)) | Updates this variable with the max of `tf.IndexedSlices` and itself.
Args:
sparse_delta: `tf.IndexedSlices` to use as an argument of max with this
variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
The updated variable.
Raises:
TypeError: if `sparse_delta` is not an `IndexedSlices`. | Updates this variable with the max of `tf.IndexedSlices` and itself. | [
"Updates",
"this",
"variable",
"with",
"the",
"max",
"of",
"tf",
".",
"IndexedSlices",
"and",
"itself",
"."
] | def scatter_max(self, sparse_delta, use_locking=False, name=None):
"""Updates this variable with the max of `tf.IndexedSlices` and itself.
Args:
sparse_delta: `tf.IndexedSlices` to use as an argument of max with this
variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
The updated variable.
Raises:
TypeError: if `sparse_delta` is not an `IndexedSlices`.
"""
if not isinstance(sparse_delta, indexed_slices.IndexedSlices):
raise TypeError(f"Argument `sparse_delta` must be a "
f"`tf.IndexedSlices`. Received arg: {sparse_delta}")
return self._lazy_read(
gen_resource_variable_ops.resource_scatter_max(
self.handle,
sparse_delta.indices,
ops.convert_to_tensor(sparse_delta.values, self.dtype),
name=name)) | [
"def",
"scatter_max",
"(",
"self",
",",
"sparse_delta",
",",
"use_locking",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"sparse_delta",
",",
"indexed_slices",
".",
"IndexedSlices",
")",
":",
"raise",
"TypeError",
"(",
"f\"Argument `sparse_delta` must be a \"",
"f\"`tf.IndexedSlices`. Received arg: {sparse_delta}\"",
")",
"return",
"self",
".",
"_lazy_read",
"(",
"gen_resource_variable_ops",
".",
"resource_scatter_max",
"(",
"self",
".",
"handle",
",",
"sparse_delta",
".",
"indices",
",",
"ops",
".",
"convert_to_tensor",
"(",
"sparse_delta",
".",
"values",
",",
"self",
".",
"dtype",
")",
",",
"name",
"=",
"name",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/resource_variable_ops.py#L1006-L1029 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/barbican.py | python | setup_venv | (ctx, config) | Setup the virtualenv for Barbican using pip. | Setup the virtualenv for Barbican using pip. | [
"Setup",
"the",
"virtualenv",
"for",
"Barbican",
"using",
"pip",
"."
] | def setup_venv(ctx, config):
"""
Setup the virtualenv for Barbican using pip.
"""
assert isinstance(config, dict)
log.info('Setting up virtualenv for barbican...')
for (client, _) in config.items():
run_in_barbican_dir(ctx, client,
['python3', '-m', 'venv', '.barbicanenv'])
run_in_barbican_venv(ctx, client,
['pip', 'install', '--upgrade', 'pip'])
run_in_barbican_venv(ctx, client,
['pip', 'install', 'pytz',
'-e', get_barbican_dir(ctx)])
yield | [
"def",
"setup_venv",
"(",
"ctx",
",",
"config",
")",
":",
"assert",
"isinstance",
"(",
"config",
",",
"dict",
")",
"log",
".",
"info",
"(",
"'Setting up virtualenv for barbican...'",
")",
"for",
"(",
"client",
",",
"_",
")",
"in",
"config",
".",
"items",
"(",
")",
":",
"run_in_barbican_dir",
"(",
"ctx",
",",
"client",
",",
"[",
"'python3'",
",",
"'-m'",
",",
"'venv'",
",",
"'.barbicanenv'",
"]",
")",
"run_in_barbican_venv",
"(",
"ctx",
",",
"client",
",",
"[",
"'pip'",
",",
"'install'",
",",
"'--upgrade'",
",",
"'pip'",
"]",
")",
"run_in_barbican_venv",
"(",
"ctx",
",",
"client",
",",
"[",
"'pip'",
",",
"'install'",
",",
"'pytz'",
",",
"'-e'",
",",
"get_barbican_dir",
"(",
"ctx",
")",
"]",
")",
"yield"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/barbican.py#L92-L106 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/masked_fill.py | python | _masked_fill_tbe | () | return | MaskedFill TBE register | MaskedFill TBE register | [
"MaskedFill",
"TBE",
"register"
] | def _masked_fill_tbe():
"""MaskedFill TBE register"""
return | [
"def",
"_masked_fill_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/masked_fill.py#L38-L40 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/settings.py | python | Settings.load | (self, ignoreErrors=False) | return True | Load the settings from the file at filename | Load the settings from the file at filename | [
"Load",
"the",
"settings",
"from",
"the",
"file",
"at",
"filename"
] | def load(self, ignoreErrors=False):
"""Load the settings from the file at filename
"""
if self._ephemeral:
return
try:
# In Python 3, pickle.load will not accept an input file that is
# opened in text mode. Opening in binary won't work on windows
# because of \r\n line endings. Reading in the settings file as
# text and converting to utf-8 should work on all
# platforms/versions.
with open(self._filename, "r") as f:
contents = f.read().encode('utf-8')
self.update(loads(contents))
except:
if ignoreErrors:
return False
raise
return True | [
"def",
"load",
"(",
"self",
",",
"ignoreErrors",
"=",
"False",
")",
":",
"if",
"self",
".",
"_ephemeral",
":",
"return",
"try",
":",
"# In Python 3, pickle.load will not accept an input file that is",
"# opened in text mode. Opening in binary won't work on windows",
"# because of \\r\\n line endings. Reading in the settings file as",
"# text and converting to utf-8 should work on all",
"# platforms/versions.",
"with",
"open",
"(",
"self",
".",
"_filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"contents",
"=",
"f",
".",
"read",
"(",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"self",
".",
"update",
"(",
"loads",
"(",
"contents",
")",
")",
"except",
":",
"if",
"ignoreErrors",
":",
"return",
"False",
"raise",
"return",
"True"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/settings.py#L99-L117 | |
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | python/dolfinx/fem/problem.py | python | LinearProblem.L | (self) | return self._L | Get the compiled linear form | Get the compiled linear form | [
"Get",
"the",
"compiled",
"linear",
"form"
] | def L(self) -> FormMetaClass:
"""Get the compiled linear form"""
return self._L | [
"def",
"L",
"(",
"self",
")",
"->",
"FormMetaClass",
":",
"return",
"self",
".",
"_L"
] | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/fem/problem.py#L128-L130 | |
microsoft/DirectXShaderCompiler | 8348ff8d9e0287610ba05d3a828e10af981a1c05 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.is_definition | (self) | return conf.lib.clang_isCursorDefinition(self) | Returns true if the declaration pointed at by the cursor is also a
definition of that entity. | Returns true if the declaration pointed at by the cursor is also a
definition of that entity. | [
"Returns",
"true",
"if",
"the",
"declaration",
"pointed",
"at",
"by",
"the",
"cursor",
"is",
"also",
"a",
"definition",
"of",
"that",
"entity",
"."
] | def is_definition(self):
"""
Returns true if the declaration pointed at by the cursor is also a
definition of that entity.
"""
return conf.lib.clang_isCursorDefinition(self) | [
"def",
"is_definition",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isCursorDefinition",
"(",
"self",
")"
] | https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/tools/clang/bindings/python/clang/cindex.py#L1158-L1163 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBValue.IsSynthetic | (self) | return _lldb.SBValue_IsSynthetic(self) | IsSynthetic(self) -> bool | IsSynthetic(self) -> bool | [
"IsSynthetic",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsSynthetic(self):
"""IsSynthetic(self) -> bool"""
return _lldb.SBValue_IsSynthetic(self) | [
"def",
"IsSynthetic",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBValue_IsSynthetic",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11912-L11914 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | Appearance.__init__ | (self, *args) | r"""
__init__ (): :class:`~klampt.Appearance`
__init__ (app): :class:`~klampt.Appearance`
Args:
app (:class:`~klampt.Appearance`, optional): | r"""
__init__ (): :class:`~klampt.Appearance` | [
"r",
"__init__",
"()",
":",
":",
"class",
":",
"~klampt",
".",
"Appearance"
] | def __init__(self, *args):
r"""
__init__ (): :class:`~klampt.Appearance`
__init__ (app): :class:`~klampt.Appearance`
Args:
app (:class:`~klampt.Appearance`, optional):
"""
_robotsim.Appearance_swiginit(self, _robotsim.new_Appearance(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_robotsim",
".",
"Appearance_swiginit",
"(",
"self",
",",
"_robotsim",
".",
"new_Appearance",
"(",
"*",
"args",
")",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L2717-L2727 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py | python | _mboxMMDF.get_bytes | (self, key, from_=False) | return string.replace(linesep, b'\n') | Return a string representation or raise a KeyError. | Return a string representation or raise a KeyError. | [
"Return",
"a",
"string",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] | def get_bytes(self, key, from_=False):
"""Return a string representation or raise a KeyError."""
start, stop = self._lookup(key)
self._file.seek(start)
if not from_:
self._file.readline()
string = self._file.read(stop - self._file.tell())
return string.replace(linesep, b'\n') | [
"def",
"get_bytes",
"(",
"self",
",",
"key",
",",
"from_",
"=",
"False",
")",
":",
"start",
",",
"stop",
"=",
"self",
".",
"_lookup",
"(",
"key",
")",
"self",
".",
"_file",
".",
"seek",
"(",
"start",
")",
"if",
"not",
"from_",
":",
"self",
".",
"_file",
".",
"readline",
"(",
")",
"string",
"=",
"self",
".",
"_file",
".",
"read",
"(",
"stop",
"-",
"self",
".",
"_file",
".",
"tell",
"(",
")",
")",
"return",
"string",
".",
"replace",
"(",
"linesep",
",",
"b'\\n'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py#L789-L796 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_stc.py | python | EditraStc.IsLoading | (self) | return getattr(self, '_loading', None) is not None | Is a background thread loading the text into the file
@return: bool | Is a background thread loading the text into the file
@return: bool | [
"Is",
"a",
"background",
"thread",
"loading",
"the",
"text",
"into",
"the",
"file",
"@return",
":",
"bool"
] | def IsLoading(self):
"""Is a background thread loading the text into the file
@return: bool
"""
# NOTE: keep the getattr check here some cases
# are reporting a yet unexplainable AttributeError here
return getattr(self, '_loading', None) is not None | [
"def",
"IsLoading",
"(",
"self",
")",
":",
"# NOTE: keep the getattr check here some cases",
"# are reporting a yet unexplainable AttributeError here",
"return",
"getattr",
"(",
"self",
",",
"'_loading'",
",",
"None",
")",
"is",
"not",
"None"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L1332-L1339 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/pyplugin_installer/installer.py | python | QgsPluginInstaller.installPlugin | (self, key, quiet=False, stable=True) | Install given plugin | Install given plugin | [
"Install",
"given",
"plugin"
] | def installPlugin(self, key, quiet=False, stable=True):
""" Install given plugin """
error = False
status_key = 'status' if stable else 'status_exp'
infoString = ('', '')
plugin = plugins.all()[key]
previousStatus = plugin[status_key]
if not plugin:
return
if plugin[status_key] == "newer" and not plugin["error"]: # ask for confirmation if user downgrades an usable plugin
if QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!"), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No:
return
dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugin, stable=stable)
dlg.exec_()
plugin_path = qgis.utils.home_plugin_path + "/" + key
if dlg.result():
error = True
infoString = (self.tr("Plugin installation failed"), dlg.result())
elif not QDir(plugin_path).exists():
error = True
infoString = (
self.tr("Plugin has disappeared"),
self.tr(
"The plugin seems to have been installed but it's not possible to know where. The directory \"{}\" "
"has not been found. Probably the plugin package contained a wrong named directory.\nPlease search "
"the list of installed plugins. You should find the plugin there, but it's not possible to "
"determine which of them it is and it's also not possible to inform you about available updates. "
"Please contact the plugin author and submit this issue.").format(plugin_path))
with OverrideCursor(Qt.WaitCursor):
plugins.getAllInstalled()
plugins.rebuild()
self.exportPluginsToManager()
else:
QApplication.setOverrideCursor(Qt.WaitCursor)
# update the list of plugins in plugin handling routines
updateAvailablePlugins()
self.processDependencies(plugin["id"])
# try to load the plugin
loadPlugin(plugin["id"])
plugins.getAllInstalled()
plugins.rebuild()
plugin = plugins.all()[key]
if not plugin["error"]:
if previousStatus in ["not installed", "new"]:
infoString = (self.tr("Plugin installed successfully"), "")
if startPlugin(plugin["id"]):
settings = QgsSettings()
settings.setValue("/PythonPlugins/" + plugin["id"], True)
else:
settings = QgsSettings()
if settings.value("/PythonPlugins/" + key, False, type=bool): # plugin will be reloaded on the fly only if currently loaded
reloadPlugin(key) # unloadPlugin + loadPlugin + startPlugin
infoString = (self.tr("Plugin reinstalled successfully"), "")
else:
unloadPlugin(key) # Just for a case. Will exit quietly if really not loaded
loadPlugin(key)
infoString = (self.tr("Plugin reinstalled successfully"), self.tr("Python plugin reinstalled.\nYou need to restart QGIS in order to reload it."))
if quiet:
infoString = (None, None)
QApplication.restoreOverrideCursor()
else:
QApplication.restoreOverrideCursor()
if plugin["error"] == "incompatible":
message = self.tr("The plugin is not compatible with this version of QGIS. It's designed for QGIS versions:")
message += " <b>" + plugin["error_details"] + "</b>"
elif plugin["error"] == "dependent":
message = self.tr("The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:")
message += "<b> " + plugin["error_details"] + "</b>"
else:
message = self.tr("The plugin is broken. Python said:")
message += "<br><b>" + plugin["error_details"] + "</b>"
dlg = QgsPluginInstallerPluginErrorDialog(iface.mainWindow(), message)
dlg.exec_()
if dlg.result():
# revert installation
pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"]
result = removeDir(pluginDir)
if QDir(pluginDir).exists():
error = True
infoString = (self.tr("Plugin uninstall failed"), result)
try:
exec("sys.path_importer_cache.clear()")
exec("import %s" % plugin["id"])
exec("reload (%s)" % plugin["id"])
except:
pass
else:
try:
exec("del sys.modules[%s]" % plugin["id"])
except:
pass
plugins.getAllInstalled()
plugins.rebuild()
self.exportPluginsToManager()
if infoString[0]:
level = error and Qgis.Critical or Qgis.Info
msg = "<b>%s</b>" % infoString[0]
if infoString[1]:
msg += "<b>:</b> %s" % infoString[1]
iface.pluginManagerInterface().pushMessage(msg, level) | [
"def",
"installPlugin",
"(",
"self",
",",
"key",
",",
"quiet",
"=",
"False",
",",
"stable",
"=",
"True",
")",
":",
"error",
"=",
"False",
"status_key",
"=",
"'status'",
"if",
"stable",
"else",
"'status_exp'",
"infoString",
"=",
"(",
"''",
",",
"''",
")",
"plugin",
"=",
"plugins",
".",
"all",
"(",
")",
"[",
"key",
"]",
"previousStatus",
"=",
"plugin",
"[",
"status_key",
"]",
"if",
"not",
"plugin",
":",
"return",
"if",
"plugin",
"[",
"status_key",
"]",
"==",
"\"newer\"",
"and",
"not",
"plugin",
"[",
"\"error\"",
"]",
":",
"# ask for confirmation if user downgrades an usable plugin",
"if",
"QMessageBox",
".",
"warning",
"(",
"iface",
".",
"mainWindow",
"(",
")",
",",
"self",
".",
"tr",
"(",
"\"QGIS Python Plugin Installer\"",
")",
",",
"self",
".",
"tr",
"(",
"\"Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!\"",
")",
",",
"QMessageBox",
".",
"Yes",
",",
"QMessageBox",
".",
"No",
")",
"==",
"QMessageBox",
".",
"No",
":",
"return",
"dlg",
"=",
"QgsPluginInstallerInstallingDialog",
"(",
"iface",
".",
"mainWindow",
"(",
")",
",",
"plugin",
",",
"stable",
"=",
"stable",
")",
"dlg",
".",
"exec_",
"(",
")",
"plugin_path",
"=",
"qgis",
".",
"utils",
".",
"home_plugin_path",
"+",
"\"/\"",
"+",
"key",
"if",
"dlg",
".",
"result",
"(",
")",
":",
"error",
"=",
"True",
"infoString",
"=",
"(",
"self",
".",
"tr",
"(",
"\"Plugin installation failed\"",
")",
",",
"dlg",
".",
"result",
"(",
")",
")",
"elif",
"not",
"QDir",
"(",
"plugin_path",
")",
".",
"exists",
"(",
")",
":",
"error",
"=",
"True",
"infoString",
"=",
"(",
"self",
".",
"tr",
"(",
"\"Plugin has disappeared\"",
")",
",",
"self",
".",
"tr",
"(",
"\"The plugin seems to have been installed but it's not possible to know where. The directory \\\"{}\\\" \"",
"\"has not been found. Probably the plugin package contained a wrong named directory.\\nPlease search \"",
"\"the list of installed plugins. You should find the plugin there, but it's not possible to \"",
"\"determine which of them it is and it's also not possible to inform you about available updates. \"",
"\"Please contact the plugin author and submit this issue.\"",
")",
".",
"format",
"(",
"plugin_path",
")",
")",
"with",
"OverrideCursor",
"(",
"Qt",
".",
"WaitCursor",
")",
":",
"plugins",
".",
"getAllInstalled",
"(",
")",
"plugins",
".",
"rebuild",
"(",
")",
"self",
".",
"exportPluginsToManager",
"(",
")",
"else",
":",
"QApplication",
".",
"setOverrideCursor",
"(",
"Qt",
".",
"WaitCursor",
")",
"# update the list of plugins in plugin handling routines",
"updateAvailablePlugins",
"(",
")",
"self",
".",
"processDependencies",
"(",
"plugin",
"[",
"\"id\"",
"]",
")",
"# try to load the plugin",
"loadPlugin",
"(",
"plugin",
"[",
"\"id\"",
"]",
")",
"plugins",
".",
"getAllInstalled",
"(",
")",
"plugins",
".",
"rebuild",
"(",
")",
"plugin",
"=",
"plugins",
".",
"all",
"(",
")",
"[",
"key",
"]",
"if",
"not",
"plugin",
"[",
"\"error\"",
"]",
":",
"if",
"previousStatus",
"in",
"[",
"\"not installed\"",
",",
"\"new\"",
"]",
":",
"infoString",
"=",
"(",
"self",
".",
"tr",
"(",
"\"Plugin installed successfully\"",
")",
",",
"\"\"",
")",
"if",
"startPlugin",
"(",
"plugin",
"[",
"\"id\"",
"]",
")",
":",
"settings",
"=",
"QgsSettings",
"(",
")",
"settings",
".",
"setValue",
"(",
"\"/PythonPlugins/\"",
"+",
"plugin",
"[",
"\"id\"",
"]",
",",
"True",
")",
"else",
":",
"settings",
"=",
"QgsSettings",
"(",
")",
"if",
"settings",
".",
"value",
"(",
"\"/PythonPlugins/\"",
"+",
"key",
",",
"False",
",",
"type",
"=",
"bool",
")",
":",
"# plugin will be reloaded on the fly only if currently loaded",
"reloadPlugin",
"(",
"key",
")",
"# unloadPlugin + loadPlugin + startPlugin",
"infoString",
"=",
"(",
"self",
".",
"tr",
"(",
"\"Plugin reinstalled successfully\"",
")",
",",
"\"\"",
")",
"else",
":",
"unloadPlugin",
"(",
"key",
")",
"# Just for a case. Will exit quietly if really not loaded",
"loadPlugin",
"(",
"key",
")",
"infoString",
"=",
"(",
"self",
".",
"tr",
"(",
"\"Plugin reinstalled successfully\"",
")",
",",
"self",
".",
"tr",
"(",
"\"Python plugin reinstalled.\\nYou need to restart QGIS in order to reload it.\"",
")",
")",
"if",
"quiet",
":",
"infoString",
"=",
"(",
"None",
",",
"None",
")",
"QApplication",
".",
"restoreOverrideCursor",
"(",
")",
"else",
":",
"QApplication",
".",
"restoreOverrideCursor",
"(",
")",
"if",
"plugin",
"[",
"\"error\"",
"]",
"==",
"\"incompatible\"",
":",
"message",
"=",
"self",
".",
"tr",
"(",
"\"The plugin is not compatible with this version of QGIS. It's designed for QGIS versions:\"",
")",
"message",
"+=",
"\" <b>\"",
"+",
"plugin",
"[",
"\"error_details\"",
"]",
"+",
"\"</b>\"",
"elif",
"plugin",
"[",
"\"error\"",
"]",
"==",
"\"dependent\"",
":",
"message",
"=",
"self",
".",
"tr",
"(",
"\"The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:\"",
")",
"message",
"+=",
"\"<b> \"",
"+",
"plugin",
"[",
"\"error_details\"",
"]",
"+",
"\"</b>\"",
"else",
":",
"message",
"=",
"self",
".",
"tr",
"(",
"\"The plugin is broken. Python said:\"",
")",
"message",
"+=",
"\"<br><b>\"",
"+",
"plugin",
"[",
"\"error_details\"",
"]",
"+",
"\"</b>\"",
"dlg",
"=",
"QgsPluginInstallerPluginErrorDialog",
"(",
"iface",
".",
"mainWindow",
"(",
")",
",",
"message",
")",
"dlg",
".",
"exec_",
"(",
")",
"if",
"dlg",
".",
"result",
"(",
")",
":",
"# revert installation",
"pluginDir",
"=",
"qgis",
".",
"utils",
".",
"home_plugin_path",
"+",
"\"/\"",
"+",
"plugin",
"[",
"\"id\"",
"]",
"result",
"=",
"removeDir",
"(",
"pluginDir",
")",
"if",
"QDir",
"(",
"pluginDir",
")",
".",
"exists",
"(",
")",
":",
"error",
"=",
"True",
"infoString",
"=",
"(",
"self",
".",
"tr",
"(",
"\"Plugin uninstall failed\"",
")",
",",
"result",
")",
"try",
":",
"exec",
"(",
"\"sys.path_importer_cache.clear()\"",
")",
"exec",
"(",
"\"import %s\"",
"%",
"plugin",
"[",
"\"id\"",
"]",
")",
"exec",
"(",
"\"reload (%s)\"",
"%",
"plugin",
"[",
"\"id\"",
"]",
")",
"except",
":",
"pass",
"else",
":",
"try",
":",
"exec",
"(",
"\"del sys.modules[%s]\"",
"%",
"plugin",
"[",
"\"id\"",
"]",
")",
"except",
":",
"pass",
"plugins",
".",
"getAllInstalled",
"(",
")",
"plugins",
".",
"rebuild",
"(",
")",
"self",
".",
"exportPluginsToManager",
"(",
")",
"if",
"infoString",
"[",
"0",
"]",
":",
"level",
"=",
"error",
"and",
"Qgis",
".",
"Critical",
"or",
"Qgis",
".",
"Info",
"msg",
"=",
"\"<b>%s</b>\"",
"%",
"infoString",
"[",
"0",
"]",
"if",
"infoString",
"[",
"1",
"]",
":",
"msg",
"+=",
"\"<b>:</b> %s\"",
"%",
"infoString",
"[",
"1",
"]",
"iface",
".",
"pluginManagerInterface",
"(",
")",
".",
"pushMessage",
"(",
"msg",
",",
"level",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/pyplugin_installer/installer.py#L295-L398 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage2.py | python | ShardingStage2._grad_scale | (self) | Before the gradient accumulation, scale the gradient. | Before the gradient accumulation, scale the gradient. | [
"Before",
"the",
"gradient",
"accumulation",
"scale",
"the",
"gradient",
"."
] | def _grad_scale(self):
"""
Before the gradient accumulation, scale the gradient.
"""
# Scale grad storages
for dtype in self._grad_storages.keys():
if not self._offload and self._rank in self._grad_storages[
dtype].keys():
self._grad_storages[dtype][self._rank].buffer.scale_(
scale=self._world_size_scaling)
# Scale grads of params
for param in self._trainable_params:
if param.name in self._param_grads and param.grad is not None:
param.grad.scale_(scale=self._world_size_scaling)
param._reset_grad_inplace_version(True)
# Scale grads of master params with offload strategy
if self._offload:
self._sharding_optimizers[0]._offload_scale_grad(
self._world_size_scaling) | [
"def",
"_grad_scale",
"(",
"self",
")",
":",
"# Scale grad storages",
"for",
"dtype",
"in",
"self",
".",
"_grad_storages",
".",
"keys",
"(",
")",
":",
"if",
"not",
"self",
".",
"_offload",
"and",
"self",
".",
"_rank",
"in",
"self",
".",
"_grad_storages",
"[",
"dtype",
"]",
".",
"keys",
"(",
")",
":",
"self",
".",
"_grad_storages",
"[",
"dtype",
"]",
"[",
"self",
".",
"_rank",
"]",
".",
"buffer",
".",
"scale_",
"(",
"scale",
"=",
"self",
".",
"_world_size_scaling",
")",
"# Scale grads of params",
"for",
"param",
"in",
"self",
".",
"_trainable_params",
":",
"if",
"param",
".",
"name",
"in",
"self",
".",
"_param_grads",
"and",
"param",
".",
"grad",
"is",
"not",
"None",
":",
"param",
".",
"grad",
".",
"scale_",
"(",
"scale",
"=",
"self",
".",
"_world_size_scaling",
")",
"param",
".",
"_reset_grad_inplace_version",
"(",
"True",
")",
"# Scale grads of master params with offload strategy",
"if",
"self",
".",
"_offload",
":",
"self",
".",
"_sharding_optimizers",
"[",
"0",
"]",
".",
"_offload_scale_grad",
"(",
"self",
".",
"_world_size_scaling",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage2.py#L189-L209 | ||
Tencent/mars | 54969ba56b402a622db123e780a4f760b38c5c36 | mars/lint/cpplint.py | python | NestingState.SeenOpenBrace | (self) | return (not self.stack) or self.stack[-1].seen_open_brace | Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace. | Check if we have seen the opening brace for the innermost block. | [
"Check",
"if",
"we",
"have",
"seen",
"the",
"opening",
"brace",
"for",
"the",
"innermost",
"block",
"."
] | def SeenOpenBrace(self):
"""Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace.
"""
return (not self.stack) or self.stack[-1].seen_open_brace | [
"def",
"SeenOpenBrace",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"stack",
")",
"or",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"seen_open_brace"
] | https://github.com/Tencent/mars/blob/54969ba56b402a622db123e780a4f760b38c5c36/mars/lint/cpplint.py#L2230-L2237 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/algorithms.py | python | _reconstruct_data | (values, dtype, original) | return values | reverse of _ensure_data
Parameters
----------
values : ndarray
dtype : pandas_dtype
original : ndarray-like
Returns
-------
Index for extension types, otherwise ndarray casted to dtype | reverse of _ensure_data | [
"reverse",
"of",
"_ensure_data"
] | def _reconstruct_data(values, dtype, original):
"""
reverse of _ensure_data
Parameters
----------
values : ndarray
dtype : pandas_dtype
original : ndarray-like
Returns
-------
Index for extension types, otherwise ndarray casted to dtype
"""
if is_extension_array_dtype(dtype):
values = dtype.construct_array_type()._from_sequence(values)
elif is_bool_dtype(dtype):
values = values.astype(dtype, copy=False)
# we only support object dtypes bool Index
if isinstance(original, ABCIndexClass):
values = values.astype(object, copy=False)
elif dtype is not None:
if is_datetime64_dtype(dtype):
dtype = "datetime64[ns]"
elif is_timedelta64_dtype(dtype):
dtype = "timedelta64[ns]"
values = values.astype(dtype, copy=False)
return values | [
"def",
"_reconstruct_data",
"(",
"values",
",",
"dtype",
",",
"original",
")",
":",
"if",
"is_extension_array_dtype",
"(",
"dtype",
")",
":",
"values",
"=",
"dtype",
".",
"construct_array_type",
"(",
")",
".",
"_from_sequence",
"(",
"values",
")",
"elif",
"is_bool_dtype",
"(",
"dtype",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"dtype",
",",
"copy",
"=",
"False",
")",
"# we only support object dtypes bool Index",
"if",
"isinstance",
"(",
"original",
",",
"ABCIndexClass",
")",
":",
"values",
"=",
"values",
".",
"astype",
"(",
"object",
",",
"copy",
"=",
"False",
")",
"elif",
"dtype",
"is",
"not",
"None",
":",
"if",
"is_datetime64_dtype",
"(",
"dtype",
")",
":",
"dtype",
"=",
"\"datetime64[ns]\"",
"elif",
"is_timedelta64_dtype",
"(",
"dtype",
")",
":",
"dtype",
"=",
"\"timedelta64[ns]\"",
"values",
"=",
"values",
".",
"astype",
"(",
"dtype",
",",
"copy",
"=",
"False",
")",
"return",
"values"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/algorithms.py#L171-L202 | |
continental/ecal | 204dab80a24fe01abca62541133b311bf0c09608 | lang/python/core/ecal/core/core.py | python | server_create | (service_name) | return _ecal.server_create(service_name) | create server
:param service_name: the unique service name
:type service_name: string | create server | [
"create",
"server"
] | def server_create(service_name):
""" create server
:param service_name: the unique service name
:type service_name: string
"""
return _ecal.server_create(service_name) | [
"def",
"server_create",
"(",
"service_name",
")",
":",
"return",
"_ecal",
".",
"server_create",
"(",
"service_name",
")"
] | https://github.com/continental/ecal/blob/204dab80a24fe01abca62541133b311bf0c09608/lang/python/core/ecal/core/core.py#L372-L379 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/layers/python/layers/feature_column_ops.py | python | input_from_feature_columns | (columns_to_tensors,
feature_columns,
weight_collections=None,
trainable=True,
scope=None) | return _input_from_feature_columns(columns_to_tensors,
feature_columns,
weight_collections,
trainable,
scope,
output_rank=2,
default_name='input_from_feature_columns') | A tf.contrib.layers style input layer builder based on FeatureColumns.
Generally a single example in training data is described with feature columns.
At the first layer of the model, this column oriented data should be converted
to a single tensor. Each feature column needs a different kind of operation
during this conversion. For example sparse features need a totally different
handling than continuous features.
Example:
```python
# Building model for training
columns_to_tensor = tf.parse_example(...)
first_layer = input_from_feature_columns(
columns_to_tensors=columns_to_tensor,
feature_columns=feature_columns)
second_layer = fully_connected(inputs=first_layer, ...)
...
```
where feature_columns can be defined as follows:
```python
sparse_feature = sparse_column_with_hash_bucket(
column_name="sparse_col", ...)
sparse_feature_emb = embedding_column(sparse_id_column=sparse_feature, ...)
real_valued_feature = real_valued_column(...)
real_valued_buckets = bucketized_column(
source_column=real_valued_feature, ...)
feature_columns=[sparse_feature_emb, real_valued_buckets]
```
Args:
columns_to_tensors: A mapping from feature column to tensors. 'string' key
means a base feature (not-transformed). It can have FeatureColumn as a
key too. That means that FeatureColumn is already transformed by input
pipeline.
feature_columns: A set containing all the feature columns. All items in the
set should be instances of classes derived by FeatureColumn.
weight_collections: List of graph collections to which weights are added.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for variable_scope.
Returns:
A Tensor which can be consumed by hidden layers in the neural network.
Raises:
ValueError: if FeatureColumn cannot be consumed by a neural network. | A tf.contrib.layers style input layer builder based on FeatureColumns. | [
"A",
"tf",
".",
"contrib",
".",
"layers",
"style",
"input",
"layer",
"builder",
"based",
"on",
"FeatureColumns",
"."
] | def input_from_feature_columns(columns_to_tensors,
feature_columns,
weight_collections=None,
trainable=True,
scope=None):
"""A tf.contrib.layers style input layer builder based on FeatureColumns.
Generally a single example in training data is described with feature columns.
At the first layer of the model, this column oriented data should be converted
to a single tensor. Each feature column needs a different kind of operation
during this conversion. For example sparse features need a totally different
handling than continuous features.
Example:
```python
# Building model for training
columns_to_tensor = tf.parse_example(...)
first_layer = input_from_feature_columns(
columns_to_tensors=columns_to_tensor,
feature_columns=feature_columns)
second_layer = fully_connected(inputs=first_layer, ...)
...
```
where feature_columns can be defined as follows:
```python
sparse_feature = sparse_column_with_hash_bucket(
column_name="sparse_col", ...)
sparse_feature_emb = embedding_column(sparse_id_column=sparse_feature, ...)
real_valued_feature = real_valued_column(...)
real_valued_buckets = bucketized_column(
source_column=real_valued_feature, ...)
feature_columns=[sparse_feature_emb, real_valued_buckets]
```
Args:
columns_to_tensors: A mapping from feature column to tensors. 'string' key
means a base feature (not-transformed). It can have FeatureColumn as a
key too. That means that FeatureColumn is already transformed by input
pipeline.
feature_columns: A set containing all the feature columns. All items in the
set should be instances of classes derived by FeatureColumn.
weight_collections: List of graph collections to which weights are added.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for variable_scope.
Returns:
A Tensor which can be consumed by hidden layers in the neural network.
Raises:
ValueError: if FeatureColumn cannot be consumed by a neural network.
"""
return _input_from_feature_columns(columns_to_tensors,
feature_columns,
weight_collections,
trainable,
scope,
output_rank=2,
default_name='input_from_feature_columns') | [
"def",
"input_from_feature_columns",
"(",
"columns_to_tensors",
",",
"feature_columns",
",",
"weight_collections",
"=",
"None",
",",
"trainable",
"=",
"True",
",",
"scope",
"=",
"None",
")",
":",
"return",
"_input_from_feature_columns",
"(",
"columns_to_tensors",
",",
"feature_columns",
",",
"weight_collections",
",",
"trainable",
",",
"scope",
",",
"output_rank",
"=",
"2",
",",
"default_name",
"=",
"'input_from_feature_columns'",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/layers/python/layers/feature_column_ops.py#L150-L212 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/packaging.py | python | _get_increment_kwargs | (git_dir, tag) | return result | Calculate the sort of semver increment needed from git history.
Every commit from HEAD to tag is consider for Sem-Ver metadata lines.
See the pbr docs for their syntax.
:return: a dict of kwargs for passing into SemanticVersion.increment. | Calculate the sort of semver increment needed from git history. | [
"Calculate",
"the",
"sort",
"of",
"semver",
"increment",
"needed",
"from",
"git",
"history",
"."
] | def _get_increment_kwargs(git_dir, tag):
"""Calculate the sort of semver increment needed from git history.
Every commit from HEAD to tag is consider for Sem-Ver metadata lines.
See the pbr docs for their syntax.
:return: a dict of kwargs for passing into SemanticVersion.increment.
"""
result = {}
if tag:
version_spec = tag + "..HEAD"
else:
version_spec = "HEAD"
# Get the raw body of the commit messages so that we don't have to
# parse out any formatting whitespace and to avoid user settings on
# git log output affecting out ability to have working sem ver headers.
changelog = git._run_git_command(['log', '--pretty=%B', version_spec],
git_dir)
header_len = len('sem-ver:')
commands = [line[header_len:].strip() for line in changelog.split('\n')
if line.lower().startswith('sem-ver:')]
symbols = set()
for command in commands:
symbols.update([symbol.strip() for symbol in command.split(',')])
def _handle_symbol(symbol, symbols, impact):
if symbol in symbols:
result[impact] = True
symbols.discard(symbol)
_handle_symbol('bugfix', symbols, 'patch')
_handle_symbol('feature', symbols, 'minor')
_handle_symbol('deprecation', symbols, 'minor')
_handle_symbol('api-break', symbols, 'major')
for symbol in symbols:
log.info('[pbr] Unknown Sem-Ver symbol %r' % symbol)
# We don't want patch in the kwargs since it is not a keyword argument -
# its the default minimum increment.
result.pop('patch', None)
return result | [
"def",
"_get_increment_kwargs",
"(",
"git_dir",
",",
"tag",
")",
":",
"result",
"=",
"{",
"}",
"if",
"tag",
":",
"version_spec",
"=",
"tag",
"+",
"\"..HEAD\"",
"else",
":",
"version_spec",
"=",
"\"HEAD\"",
"# Get the raw body of the commit messages so that we don't have to",
"# parse out any formatting whitespace and to avoid user settings on",
"# git log output affecting out ability to have working sem ver headers.",
"changelog",
"=",
"git",
".",
"_run_git_command",
"(",
"[",
"'log'",
",",
"'--pretty=%B'",
",",
"version_spec",
"]",
",",
"git_dir",
")",
"header_len",
"=",
"len",
"(",
"'sem-ver:'",
")",
"commands",
"=",
"[",
"line",
"[",
"header_len",
":",
"]",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"changelog",
".",
"split",
"(",
"'\\n'",
")",
"if",
"line",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'sem-ver:'",
")",
"]",
"symbols",
"=",
"set",
"(",
")",
"for",
"command",
"in",
"commands",
":",
"symbols",
".",
"update",
"(",
"[",
"symbol",
".",
"strip",
"(",
")",
"for",
"symbol",
"in",
"command",
".",
"split",
"(",
"','",
")",
"]",
")",
"def",
"_handle_symbol",
"(",
"symbol",
",",
"symbols",
",",
"impact",
")",
":",
"if",
"symbol",
"in",
"symbols",
":",
"result",
"[",
"impact",
"]",
"=",
"True",
"symbols",
".",
"discard",
"(",
"symbol",
")",
"_handle_symbol",
"(",
"'bugfix'",
",",
"symbols",
",",
"'patch'",
")",
"_handle_symbol",
"(",
"'feature'",
",",
"symbols",
",",
"'minor'",
")",
"_handle_symbol",
"(",
"'deprecation'",
",",
"symbols",
",",
"'minor'",
")",
"_handle_symbol",
"(",
"'api-break'",
",",
"symbols",
",",
"'major'",
")",
"for",
"symbol",
"in",
"symbols",
":",
"log",
".",
"info",
"(",
"'[pbr] Unknown Sem-Ver symbol %r'",
"%",
"symbol",
")",
"# We don't want patch in the kwargs since it is not a keyword argument -",
"# its the default minimum increment.",
"result",
".",
"pop",
"(",
"'patch'",
",",
"None",
")",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/packaging.py#L612-L650 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/jinja2/utils.py | python | import_string | (import_name, silent=False) | Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object | Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``). | [
"Imports",
"an",
"object",
"based",
"on",
"a",
"string",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"to",
"use",
"import",
"paths",
"as",
"endpoints",
"or",
"something",
"similar",
".",
"An",
"import",
"path",
"can",
"be",
"specified",
"either",
"in",
"dotted",
"notation",
"(",
"xml",
".",
"sax",
".",
"saxutils",
".",
"escape",
")",
"or",
"with",
"a",
"colon",
"as",
"object",
"delimiter",
"(",
"xml",
".",
"sax",
".",
"saxutils",
":",
"escape",
")",
"."
] | def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
"""
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
items = import_name.split('.')
module = '.'.join(items[:-1])
obj = items[-1]
else:
return __import__(import_name)
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, AttributeError):
if not silent:
raise | [
"def",
"import_string",
"(",
"import_name",
",",
"silent",
"=",
"False",
")",
":",
"try",
":",
"if",
"':'",
"in",
"import_name",
":",
"module",
",",
"obj",
"=",
"import_name",
".",
"split",
"(",
"':'",
",",
"1",
")",
"elif",
"'.'",
"in",
"import_name",
":",
"items",
"=",
"import_name",
".",
"split",
"(",
"'.'",
")",
"module",
"=",
"'.'",
".",
"join",
"(",
"items",
"[",
":",
"-",
"1",
"]",
")",
"obj",
"=",
"items",
"[",
"-",
"1",
"]",
"else",
":",
"return",
"__import__",
"(",
"import_name",
")",
"return",
"getattr",
"(",
"__import__",
"(",
"module",
",",
"None",
",",
"None",
",",
"[",
"obj",
"]",
")",
",",
"obj",
")",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
":",
"if",
"not",
"silent",
":",
"raise"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/utils.py#L119-L142 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/automate/automate-git.py | python | read_config_file | (path) | return eval(read_file(path), {'__builtins__': None}, None) | Read a configuration file. | Read a configuration file. | [
"Read",
"a",
"configuration",
"file",
"."
] | def read_config_file(path):
""" Read a configuration file. """
# Parse the contents.
return eval(read_file(path), {'__builtins__': None}, None) | [
"def",
"read_config_file",
"(",
"path",
")",
":",
"# Parse the contents.",
"return",
"eval",
"(",
"read_file",
"(",
"path",
")",
",",
"{",
"'__builtins__'",
":",
"None",
"}",
",",
"None",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/automate/automate-git.py#L182-L185 | |
Kitware/kwiver | 7ed70308905698b6e88d27ae3dc028c9b016ca0a | python/kwiver/sprokit/processes/simple_homog_tracker.py | python | convert_homographies | () | Create a Transformer that converts frame-to-frame homographies to
homographies to the previous frame, or None if not possible. The
.step call expects one argument:
- a HomographyF2F (from this frame to reference frame)
and returns a Homography. | Create a Transformer that converts frame-to-frame homographies to
homographies to the previous frame, or None if not possible. The
.step call expects one argument:
- a HomographyF2F (from this frame to reference frame)
and returns a Homography. | [
"Create",
"a",
"Transformer",
"that",
"converts",
"frame",
"-",
"to",
"-",
"frame",
"homographies",
"to",
"homographies",
"to",
"the",
"previous",
"frame",
"or",
"None",
"if",
"not",
"possible",
".",
"The",
".",
"step",
"call",
"expects",
"one",
"argument",
":",
"-",
"a",
"HomographyF2F",
"(",
"from",
"this",
"frame",
"to",
"reference",
"frame",
")",
"and",
"returns",
"a",
"Homography",
"."
] | def convert_homographies():
"""Create a Transformer that converts frame-to-frame homographies to
homographies to the previous frame, or None if not possible. The
.step call expects one argument:
- a HomographyF2F (from this frame to reference frame)
and returns a Homography.
"""
output = None
prev = None
while True:
curr, = yield output
if prev is not None and prev.to_id == curr.to_id:
homog = Homography(np.matmul(np.linalg.inv(prev.homog.matrix), curr.homog.matrix))
else:
homog = None
prev = curr
output = homog | [
"def",
"convert_homographies",
"(",
")",
":",
"output",
"=",
"None",
"prev",
"=",
"None",
"while",
"True",
":",
"curr",
",",
"=",
"yield",
"output",
"if",
"prev",
"is",
"not",
"None",
"and",
"prev",
".",
"to_id",
"==",
"curr",
".",
"to_id",
":",
"homog",
"=",
"Homography",
"(",
"np",
".",
"matmul",
"(",
"np",
".",
"linalg",
".",
"inv",
"(",
"prev",
".",
"homog",
".",
"matrix",
")",
",",
"curr",
".",
"homog",
".",
"matrix",
")",
")",
"else",
":",
"homog",
"=",
"None",
"prev",
"=",
"curr",
"output",
"=",
"homog"
] | https://github.com/Kitware/kwiver/blob/7ed70308905698b6e88d27ae3dc028c9b016ca0a/python/kwiver/sprokit/processes/simple_homog_tracker.py#L204-L221 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/train/model.py | python | Model._get_scaling_sens | (self) | return scaling_sens | get the scaling sens | get the scaling sens | [
"get",
"the",
"scaling",
"sens"
] | def _get_scaling_sens(self):
"""get the scaling sens"""
scaling_sens = 1
if self._loss_scale_manager is not None:
scaling_sens = self._loss_scale_manager.get_loss_scale()
if self._parallel_mode == ParallelMode.DATA_PARALLEL:
scaling_sens /= self._device_number
return scaling_sens | [
"def",
"_get_scaling_sens",
"(",
"self",
")",
":",
"scaling_sens",
"=",
"1",
"if",
"self",
".",
"_loss_scale_manager",
"is",
"not",
"None",
":",
"scaling_sens",
"=",
"self",
".",
"_loss_scale_manager",
".",
"get_loss_scale",
"(",
")",
"if",
"self",
".",
"_parallel_mode",
"==",
"ParallelMode",
".",
"DATA_PARALLEL",
":",
"scaling_sens",
"/=",
"self",
".",
"_device_number",
"return",
"scaling_sens"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/model.py#L376-L383 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/filters.py | python | do_sum | (environment, iterable, attribute=None, start=0) | return sum(iterable, start) | Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode:: jinja
Total: {{ items|sum(attribute='price') }}
.. versionchanged:: 2.6
The `attribute` parameter was added to allow suming up over
attributes. Also the `start` parameter was moved on to the right. | Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start. | [
"Returns",
"the",
"sum",
"of",
"a",
"sequence",
"of",
"numbers",
"plus",
"the",
"value",
"of",
"parameter",
"start",
"(",
"which",
"defaults",
"to",
"0",
")",
".",
"When",
"the",
"sequence",
"is",
"empty",
"it",
"returns",
"start",
"."
] | def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode:: jinja
Total: {{ items|sum(attribute='price') }}
.. versionchanged:: 2.6
The `attribute` parameter was added to allow suming up over
attributes. Also the `start` parameter was moved on to the right.
"""
if attribute is not None:
iterable = imap(make_attrgetter(environment, attribute), iterable)
return sum(iterable, start) | [
"def",
"do_sum",
"(",
"environment",
",",
"iterable",
",",
"attribute",
"=",
"None",
",",
"start",
"=",
"0",
")",
":",
"if",
"attribute",
"is",
"not",
"None",
":",
"iterable",
"=",
"imap",
"(",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
",",
"iterable",
")",
"return",
"sum",
"(",
"iterable",
",",
"start",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/filters.py#L716-L733 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py | python | TurtleScreenBase._drawimage | (self, item, pos, image) | Configure image item as to draw image object
at position (x,y) on canvas) | Configure image item as to draw image object
at position (x,y) on canvas) | [
"Configure",
"image",
"item",
"as",
"to",
"draw",
"image",
"object",
"at",
"position",
"(",
"x",
"y",
")",
"on",
"canvas",
")"
] | def _drawimage(self, item, pos, image):
"""Configure image item as to draw image object
at position (x,y) on canvas)
"""
x, y = pos
self.cv.coords(item, (x * self.xscale, -y * self.yscale))
self.cv.itemconfig(item, image=image) | [
"def",
"_drawimage",
"(",
"self",
",",
"item",
",",
"pos",
",",
"image",
")",
":",
"x",
",",
"y",
"=",
"pos",
"self",
".",
"cv",
".",
"coords",
"(",
"item",
",",
"(",
"x",
"*",
"self",
".",
"xscale",
",",
"-",
"y",
"*",
"self",
".",
"yscale",
")",
")",
"self",
".",
"cv",
".",
"itemconfig",
"(",
"item",
",",
"image",
"=",
"image",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py#L725-L731 | ||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/bindings/python/clang/cindex.py | python | Cursor.availability | (self) | return AvailabilityKind.from_id(self._availability) | Retrieves the availability of the entity pointed at by the cursor. | Retrieves the availability of the entity pointed at by the cursor. | [
"Retrieves",
"the",
"availability",
"of",
"the",
"entity",
"pointed",
"at",
"by",
"the",
"cursor",
"."
] | def availability(self):
"""
Retrieves the availability of the entity pointed at by the cursor.
"""
if not hasattr(self, '_availability'):
self._availability = conf.lib.clang_getCursorAvailability(self)
return AvailabilityKind.from_id(self._availability) | [
"def",
"availability",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_availability'",
")",
":",
"self",
".",
"_availability",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorAvailability",
"(",
"self",
")",
"return",
"AvailabilityKind",
".",
"from_id",
"(",
"self",
".",
"_availability",
")"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L1620-L1627 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/Operation/PhactoriClipPlaneOperation.py | python | PhactoriClipPlaneOperation.UpdateClip | (self, inIncomingPvFilter, ioOutgoingPvFilter) | using the current info on the clip, get all the paraview stuff
set up correctly | using the current info on the clip, get all the paraview stuff
set up correctly | [
"using",
"the",
"current",
"info",
"on",
"the",
"clip",
"get",
"all",
"the",
"paraview",
"stuff",
"set",
"up",
"correctly"
] | def UpdateClip(self, inIncomingPvFilter, ioOutgoingPvFilter):
"""using the current info on the clip, get all the paraview stuff
set up correctly"""
if PhactoriDbg():
myDebugPrint3("PhactoriClipPlaneOperation::UpdateClip entered\n")
originToUse = [0,0,0]
normalToUse = [0,1,0]
self.CalculateUpdatedOriginAndNormal(
inIncomingPvFilter, originToUse, normalToUse)
if PhactoriDbg():
myDebugPrint3(' updateclip using normal: ' + \
str(normalToUse) + '\n')
ioOutgoingPvFilter.ClipType.Normal = normalToUse
if PhactoriDbg():
myDebugPrint3(' updateclip using origin: ' + str(originToUse) + '\n')
ioOutgoingPvFilter.ClipType.Origin = originToUse
#these aren't changing yet
ioOutgoingPvFilter.Crinkleclip = self.mCrinkleSetting
if gParaViewCatalystVersionFlag < 50502:
ioOutgoingPvFilter.InsideOut = self.mInsideOut
else:
ioOutgoingPvFilter.Invert = self.mInvert
if PhactoriDbg():
myDebugPrint3("PhactoriClipPlaneOperation::UpdateClip returning\n") | [
"def",
"UpdateClip",
"(",
"self",
",",
"inIncomingPvFilter",
",",
"ioOutgoingPvFilter",
")",
":",
"if",
"PhactoriDbg",
"(",
")",
":",
"myDebugPrint3",
"(",
"\"PhactoriClipPlaneOperation::UpdateClip entered\\n\"",
")",
"originToUse",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"normalToUse",
"=",
"[",
"0",
",",
"1",
",",
"0",
"]",
"self",
".",
"CalculateUpdatedOriginAndNormal",
"(",
"inIncomingPvFilter",
",",
"originToUse",
",",
"normalToUse",
")",
"if",
"PhactoriDbg",
"(",
")",
":",
"myDebugPrint3",
"(",
"' updateclip using normal: '",
"+",
"str",
"(",
"normalToUse",
")",
"+",
"'\\n'",
")",
"ioOutgoingPvFilter",
".",
"ClipType",
".",
"Normal",
"=",
"normalToUse",
"if",
"PhactoriDbg",
"(",
")",
":",
"myDebugPrint3",
"(",
"' updateclip using origin: '",
"+",
"str",
"(",
"originToUse",
")",
"+",
"'\\n'",
")",
"ioOutgoingPvFilter",
".",
"ClipType",
".",
"Origin",
"=",
"originToUse",
"#these aren't changing yet",
"ioOutgoingPvFilter",
".",
"Crinkleclip",
"=",
"self",
".",
"mCrinkleSetting",
"if",
"gParaViewCatalystVersionFlag",
"<",
"50502",
":",
"ioOutgoingPvFilter",
".",
"InsideOut",
"=",
"self",
".",
"mInsideOut",
"else",
":",
"ioOutgoingPvFilter",
".",
"Invert",
"=",
"self",
".",
"mInvert",
"if",
"PhactoriDbg",
"(",
")",
":",
"myDebugPrint3",
"(",
"\"PhactoriClipPlaneOperation::UpdateClip returning\\n\"",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/Operation/PhactoriClipPlaneOperation.py#L163-L192 | ||
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | examples/python/gdbremote.py | python | TerminalColors.inverse | (self, on=True) | return '' | Enable or disable inverse depending on the "on" parameter. | Enable or disable inverse depending on the "on" parameter. | [
"Enable",
"or",
"disable",
"inverse",
"depending",
"on",
"the",
"on",
"parameter",
"."
] | def inverse(self, on=True):
'''Enable or disable inverse depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[7m"
else:
return "\x1b[27m"
return '' | [
"def",
"inverse",
"(",
"self",
",",
"on",
"=",
"True",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"on",
":",
"return",
"\"\\x1b[7m\"",
"else",
":",
"return",
"\"\\x1b[27m\"",
"return",
"''"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/examples/python/gdbremote.py#L82-L89 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.