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
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Configuration/DataProcessing/python/Utils.py
python
stepSKIMPRODUCER
(PhysicsSkims)
return step
_stepSKIMPRODUCER_ Creates and returns the configuration string for the SKIM step starting from the list of skims to be run.
_stepSKIMPRODUCER_
[ "_stepSKIMPRODUCER_" ]
def stepSKIMPRODUCER(PhysicsSkims): """ _stepSKIMPRODUCER_ Creates and returns the configuration string for the SKIM step starting from the list of skims to be run. """ step = '' if len(PhysicsSkims) >0 : step = ',SKIM:'+('+'.join(PhysicsSkims)) return step
[ "def", "stepSKIMPRODUCER", "(", "PhysicsSkims", ")", ":", "step", "=", "''", "if", "len", "(", "PhysicsSkims", ")", ">", "0", ":", "step", "=", "',SKIM:'", "+", "(", "'+'", ".", "join", "(", "PhysicsSkims", ")", ")", "return", "step" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Configuration/DataProcessing/python/Utils.py#L24-L36
google/tink
59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14
python/tink/jwt/_raw_jwt.py
python
raw_jwt_from_json
(type_header: Optional[str], payload: str)
return RawJwt._from_json(type_header, payload)
Internal function used to verify JWT token.
Internal function used to verify JWT token.
[ "Internal", "function", "used", "to", "verify", "JWT", "token", "." ]
def raw_jwt_from_json(type_header: Optional[str], payload: str) -> RawJwt: """Internal function used to verify JWT token.""" return RawJwt._from_json(type_header, payload)
[ "def", "raw_jwt_from_json", "(", "type_header", ":", "Optional", "[", "str", "]", ",", "payload", ":", "str", ")", "->", "RawJwt", ":", "return", "RawJwt", ".", "_from_json", "(", "type_header", ",", "payload", ")" ]
https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/jwt/_raw_jwt.py#L263-L265
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_psosx.py
python
net_if_stats
()
return ret
Get NIC stats (isup, duplex, speed, mtu).
Get NIC stats (isup, duplex, speed, mtu).
[ "Get", "NIC", "stats", "(", "isup", "duplex", "speed", "mtu", ")", "." ]
def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" names = net_io_counters().keys() ret = {} for name in names: try: mtu = cext_posix.net_if_mtu(name) isup = cext_posix.net_if_flags(name) duplex, speed = cext_posix.net_if_duplex_speed(name) except OSError as err: # https://github.com/giampaolo/psutil/issues/1279 if err.errno != errno.ENODEV: raise else: if hasattr(_common, 'NicDuplex'): duplex = _common.NicDuplex(duplex) ret[name] = _common.snicstats(isup, duplex, speed, mtu) return ret
[ "def", "net_if_stats", "(", ")", ":", "names", "=", "net_io_counters", "(", ")", ".", "keys", "(", ")", "ret", "=", "{", "}", "for", "name", "in", "names", ":", "try", ":", "mtu", "=", "cext_posix", ".", "net_if_mtu", "(", "name", ")", "isup", "=", "cext_posix", ".", "net_if_flags", "(", "name", ")", "duplex", ",", "speed", "=", "cext_posix", ".", "net_if_duplex_speed", "(", "name", ")", "except", "OSError", "as", "err", ":", "# https://github.com/giampaolo/psutil/issues/1279", "if", "err", ".", "errno", "!=", "errno", ".", "ENODEV", ":", "raise", "else", ":", "if", "hasattr", "(", "_common", ",", "'NicDuplex'", ")", ":", "duplex", "=", "_common", ".", "NicDuplex", "(", "duplex", ")", "ret", "[", "name", "]", "=", "_common", ".", "snicstats", "(", "isup", ",", "duplex", ",", "speed", ",", "mtu", ")", "return", "ret" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_psosx.py#L258-L275
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.WriteMacInfoPlist
(self, partial_info_plist, bundle_depends)
Write build rules for bundle Info.plist files.
Write build rules for bundle Info.plist files.
[ "Write", "build", "rules", "for", "bundle", "Info", ".", "plist", "files", "." ]
def WriteMacInfoPlist(self, partial_info_plist, bundle_depends): """Write build rules for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, self.GypPathToNinja) if not info_plist: return out = self.ExpandSpecial(out) if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = self.GypPathToUniqueOutput( os.path.basename(info_plist)) defines = ' '.join([Define(d, self.flavor) for d in defines]) info_plist = self.ninja.build( intermediate_plist, 'preprocess_infoplist', info_plist, variables=[('defines',defines)]) env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) if partial_info_plist: intermediate_plist = self.GypPathToUniqueOutput('merged_info.plist') info_plist = self.ninja.build( intermediate_plist, 'merge_infoplist', [partial_info_plist, info_plist]) keys = self.xcode_settings.GetExtraPlistItems(self.config_name) keys = QuoteShellArgument(json.dumps(keys), self.flavor) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(out, 'copy_infoplist', info_plist, variables=[('env', env), ('keys', keys), ('binary', isBinary)]) bundle_depends.append(out)
[ "def", "WriteMacInfoPlist", "(", "self", ",", "partial_info_plist", ",", "bundle_depends", ")", ":", "info_plist", ",", "out", ",", "defines", ",", "extra_env", "=", "gyp", ".", "xcode_emulation", ".", "GetMacInfoPlist", "(", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ",", "self", ".", "xcode_settings", ",", "self", ".", "GypPathToNinja", ")", "if", "not", "info_plist", ":", "return", "out", "=", "self", ".", "ExpandSpecial", "(", "out", ")", "if", "defines", ":", "# Create an intermediate file to store preprocessed results.", "intermediate_plist", "=", "self", ".", "GypPathToUniqueOutput", "(", "os", ".", "path", ".", "basename", "(", "info_plist", ")", ")", "defines", "=", "' '", ".", "join", "(", "[", "Define", "(", "d", ",", "self", ".", "flavor", ")", "for", "d", "in", "defines", "]", ")", "info_plist", "=", "self", ".", "ninja", ".", "build", "(", "intermediate_plist", ",", "'preprocess_infoplist'", ",", "info_plist", ",", "variables", "=", "[", "(", "'defines'", ",", "defines", ")", "]", ")", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", "additional_settings", "=", "extra_env", ")", "env", "=", "self", ".", "ComputeExportEnvString", "(", "env", ")", "if", "partial_info_plist", ":", "intermediate_plist", "=", "self", ".", "GypPathToUniqueOutput", "(", "'merged_info.plist'", ")", "info_plist", "=", "self", ".", "ninja", ".", "build", "(", "intermediate_plist", ",", "'merge_infoplist'", ",", "[", "partial_info_plist", ",", "info_plist", "]", ")", "keys", "=", "self", ".", "xcode_settings", ".", "GetExtraPlistItems", "(", "self", ".", "config_name", ")", "keys", "=", "QuoteShellArgument", "(", "json", ".", "dumps", "(", "keys", ")", ",", "self", ".", "flavor", ")", "isBinary", "=", "self", ".", "xcode_settings", ".", "IsBinaryOutputFormat", "(", "self", ".", "config_name", ")", "self", ".", "ninja", ".", "build", "(", "out", ",", "'copy_infoplist'", ",", "info_plist", ",", "variables", "=", "[", "(", "'env'", ",", "env", ")", ",", "(", "'keys'", ",", "keys", ")", ",", "(", "'binary'", ",", "isBinary", ")", "]", ")", "bundle_depends", ".", "append", "(", "out", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L832-L864
LiXizhi/NPLRuntime
a42720e5fe9a6960e0a9ce40bbbcd809192906be
Client/trunk/externals/assimp-4.0.0/port/PyAssimp/scripts/transformations.py
python
unit_vector
(data, axis=None, out=None)
Return ndarray normalized by length, i.e. eucledian norm, along axis. >>> v0 = numpy.random.random(3) >>> v1 = unit_vector(v0) >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) True >>> v0 = numpy.random.rand(5, 4, 3) >>> v1 = unit_vector(v0, axis=-1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2) >>> numpy.allclose(v1, v2) True >>> v1 = unit_vector(v0, axis=1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1) >>> numpy.allclose(v1, v2) True >>> v1 = numpy.empty((5, 4, 3), dtype=numpy.float64) >>> unit_vector(v0, axis=1, out=v1) >>> numpy.allclose(v1, v2) True >>> list(unit_vector([])) [] >>> list(unit_vector([1.0])) [1.0]
Return ndarray normalized by length, i.e. eucledian norm, along axis.
[ "Return", "ndarray", "normalized", "by", "length", "i", ".", "e", ".", "eucledian", "norm", "along", "axis", "." ]
def unit_vector(data, axis=None, out=None): """Return ndarray normalized by length, i.e. eucledian norm, along axis. >>> v0 = numpy.random.random(3) >>> v1 = unit_vector(v0) >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) True >>> v0 = numpy.random.rand(5, 4, 3) >>> v1 = unit_vector(v0, axis=-1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2) >>> numpy.allclose(v1, v2) True >>> v1 = unit_vector(v0, axis=1) >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1) >>> numpy.allclose(v1, v2) True >>> v1 = numpy.empty((5, 4, 3), dtype=numpy.float64) >>> unit_vector(v0, axis=1, out=v1) >>> numpy.allclose(v1, v2) True >>> list(unit_vector([])) [] >>> list(unit_vector([1.0])) [1.0] """ if out is None: data = numpy.array(data, dtype=numpy.float64, copy=True) if data.ndim == 1: data /= math.sqrt(numpy.dot(data, data)) return data else: if out is not data: out[:] = numpy.array(data, copy=False) data = out length = numpy.atleast_1d(numpy.sum(data*data, axis)) numpy.sqrt(length, length) if axis is not None: length = numpy.expand_dims(length, axis) data /= length if out is None: return data
[ "def", "unit_vector", "(", "data", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "data", "=", "numpy", ".", "array", "(", "data", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "if", "data", ".", "ndim", "==", "1", ":", "data", "/=", "math", ".", "sqrt", "(", "numpy", ".", "dot", "(", "data", ",", "data", ")", ")", "return", "data", "else", ":", "if", "out", "is", "not", "data", ":", "out", "[", ":", "]", "=", "numpy", ".", "array", "(", "data", ",", "copy", "=", "False", ")", "data", "=", "out", "length", "=", "numpy", ".", "atleast_1d", "(", "numpy", ".", "sum", "(", "data", "*", "data", ",", "axis", ")", ")", "numpy", ".", "sqrt", "(", "length", ",", "length", ")", "if", "axis", "is", "not", "None", ":", "length", "=", "numpy", ".", "expand_dims", "(", "length", ",", "axis", ")", "data", "/=", "length", "if", "out", "is", "None", ":", "return", "data" ]
https://github.com/LiXizhi/NPLRuntime/blob/a42720e5fe9a6960e0a9ce40bbbcd809192906be/Client/trunk/externals/assimp-4.0.0/port/PyAssimp/scripts/transformations.py#L1574-L1615
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py
python
TensorArray.write
(self, index, value, name=None)
Write `value` into index `index` of the TensorArray. Args: index: 0-D. int32 scalar with the index to write to. value: N-D. Tensor of type `dtype`. The Tensor to write to this index. name: A name for the operation (optional). Returns: A new TensorArray object with flow that ensures the write occurs. Use this object all for subsequent operations. Raises: ValueError: if there are more writers than specified.
Write `value` into index `index` of the TensorArray.
[ "Write", "value", "into", "index", "index", "of", "the", "TensorArray", "." ]
def write(self, index, value, name=None): """Write `value` into index `index` of the TensorArray. Args: index: 0-D. int32 scalar with the index to write to. value: N-D. Tensor of type `dtype`. The Tensor to write to this index. name: A name for the operation (optional). Returns: A new TensorArray object with flow that ensures the write occurs. Use this object all for subsequent operations. Raises: ValueError: if there are more writers than specified. """ with ops.colocate_with(self._handle): flow_out = gen_data_flow_ops._tensor_array_write( handle=self._handle, index=index, value=value, flow_in=self._flow, name=name) ta = TensorArray(dtype=self._dtype, handle=self._handle) ta._flow = flow_out ta._infer_shape = self._infer_shape ta._elem_shape = self._elem_shape if ta._infer_shape: val_shape = flow_out.op.inputs[2].get_shape() if ta._elem_shape: if not val_shape == ta._elem_shape[0]: raise ValueError( "Inconsistent shapes: saw %s but expected %s " "(and infer_shape=True)" % (val_shape, ta._elem_shape[0])) else: ta._elem_shape.append(val_shape) return ta
[ "def", "write", "(", "self", ",", "index", ",", "value", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "colocate_with", "(", "self", ".", "_handle", ")", ":", "flow_out", "=", "gen_data_flow_ops", ".", "_tensor_array_write", "(", "handle", "=", "self", ".", "_handle", ",", "index", "=", "index", ",", "value", "=", "value", ",", "flow_in", "=", "self", ".", "_flow", ",", "name", "=", "name", ")", "ta", "=", "TensorArray", "(", "dtype", "=", "self", ".", "_dtype", ",", "handle", "=", "self", ".", "_handle", ")", "ta", ".", "_flow", "=", "flow_out", "ta", ".", "_infer_shape", "=", "self", ".", "_infer_shape", "ta", ".", "_elem_shape", "=", "self", ".", "_elem_shape", "if", "ta", ".", "_infer_shape", ":", "val_shape", "=", "flow_out", ".", "op", ".", "inputs", "[", "2", "]", ".", "get_shape", "(", ")", "if", "ta", ".", "_elem_shape", ":", "if", "not", "val_shape", "==", "ta", ".", "_elem_shape", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Inconsistent shapes: saw %s but expected %s \"", "\"(and infer_shape=True)\"", "%", "(", "val_shape", ",", "ta", ".", "_elem_shape", "[", "0", "]", ")", ")", "else", ":", "ta", ".", "_elem_shape", ".", "append", "(", "val_shape", ")", "return", "ta" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py#L196-L228
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/contact.py
python
ContactPoint.fromlist
(self,v)
Reads the values x,n, and kFriction from the 7-list v.
Reads the values x,n, and kFriction from the 7-list v.
[ "Reads", "the", "values", "x", "n", "and", "kFriction", "from", "the", "7", "-", "list", "v", "." ]
def fromlist(self,v): """Reads the values x,n, and kFriction from the 7-list v.""" if len(v) != 7: raise ValueError("ContactPoint can only be converted from a 7-element list") self.x = v[0:3] self.n = v[3:6] self.kFriction = v[6]
[ "def", "fromlist", "(", "self", ",", "v", ")", ":", "if", "len", "(", "v", ")", "!=", "7", ":", "raise", "ValueError", "(", "\"ContactPoint can only be converted from a 7-element list\"", ")", "self", ".", "x", "=", "v", "[", "0", ":", "3", "]", "self", ".", "n", "=", "v", "[", "3", ":", "6", "]", "self", ".", "kFriction", "=", "v", "[", "6", "]" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/contact.py#L69-L74
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/middle/InterpolateSequenceToInterpolate.py
python
replace_sequence
(seq: List[Node], graph: Graph)
This function replaces a sequence of consecutive Interpolate layers with one Interpolate layer, if modes of all nodes of a sequence are the same. :param seq: sequence of Interpolate layers :param graph: graph to which nodes of seq belong :return: Nothing
This function replaces a sequence of consecutive Interpolate layers with one Interpolate layer, if modes of all nodes of a sequence are the same. :param seq: sequence of Interpolate layers :param graph: graph to which nodes of seq belong :return: Nothing
[ "This", "function", "replaces", "a", "sequence", "of", "consecutive", "Interpolate", "layers", "with", "one", "Interpolate", "layer", "if", "modes", "of", "all", "nodes", "of", "a", "sequence", "are", "the", "same", ".", ":", "param", "seq", ":", "sequence", "of", "Interpolate", "layers", ":", "param", "graph", ":", "graph", "to", "which", "nodes", "of", "seq", "belong", ":", "return", ":", "Nothing" ]
def replace_sequence(seq: List[Node], graph: Graph): """ This function replaces a sequence of consecutive Interpolate layers with one Interpolate layer, if modes of all nodes of a sequence are the same. :param seq: sequence of Interpolate layers :param graph: graph to which nodes of seq belong :return: Nothing """ if not seq: return if len(seq) == 1: return modes = set([n.mode for n in seq]) if len(modes) != 1: return dims_and_scales_ = [] # Each element of the list dims_and_scales_ is a pair # (axis, output size for this axis) (opset1) # or # (axis, output size for this axis, output scales for this axis) (opset4) if seq[0].get_opset() == 'opset1': for interp in seq: dims_and_scales_.extend(zip(Interpolate.get_axes(interp), interp.in_port(1).get_connection().get_source().data.get_value())) axis_to_size = sorted(list(dict(dims_and_scales_).items()), key=lambda x: x[0]) axes_of_node = int64_array([z[0] for z in axis_to_size]) sizes = shape_array([z[1] for z in axis_to_size]) scales = np.ones(len(axis_to_size), dtype=np.float32) else: for interp in seq: dims_and_scales_.extend(zip(Interpolate.get_axes(interp), interp.in_port(1).get_connection().get_source().data.get_value(), interp.in_port(2).get_connection().get_source().data.get_value())) axis_to_size = sorted(dims_and_scales_, key=lambda x: x[0]) axes_of_node = int64_array([z[0] for z in axis_to_size]) sizes = shape_array([z[1] for z in axis_to_size]) scales = mo_array([z[2] for z in axis_to_size]) fst_interp_node = seq[0] last_interp_node = seq[-1] last_interp_node_name = last_interp_node.soft_get('name', last_interp_node.id) attributes = get_interpolate_attributes(fst_interp_node) opset = fst_interp_node.get_opset() if opset == 'opset1': attributes['axes'] = axes_of_node interp_node = create_op_with_const_inputs(graph, Interpolate, {1: sizes}, attributes) fst_interp_connection = fst_interp_node.in_port(0).get_connection() fst_interp_connection.set_destination(interp_node.in_port(0)) last_interp_node.out_port(0).get_connection().set_source(interp_node.out_port(0)) else: attributes['in_ports_count'] = 4 interp_node = create_op_with_const_inputs(graph, Interpolate, {1: sizes, 2: scales, 3: axes_of_node}, attributes) fst_interp_connection = fst_interp_node.in_port(0).get_connection() fst_interp_connection.set_destination(interp_node.in_port(0)) last_interp_node.out_port(0).get_connection().set_source(interp_node.out_port(0)) rename_nodes([(last_interp_node, last_interp_node_name + '/delete'), (interp_node, last_interp_node_name)])
[ "def", "replace_sequence", "(", "seq", ":", "List", "[", "Node", "]", ",", "graph", ":", "Graph", ")", ":", "if", "not", "seq", ":", "return", "if", "len", "(", "seq", ")", "==", "1", ":", "return", "modes", "=", "set", "(", "[", "n", ".", "mode", "for", "n", "in", "seq", "]", ")", "if", "len", "(", "modes", ")", "!=", "1", ":", "return", "dims_and_scales_", "=", "[", "]", "# Each element of the list dims_and_scales_ is a pair", "# (axis, output size for this axis) (opset1)", "# or", "# (axis, output size for this axis, output scales for this axis) (opset4)", "if", "seq", "[", "0", "]", ".", "get_opset", "(", ")", "==", "'opset1'", ":", "for", "interp", "in", "seq", ":", "dims_and_scales_", ".", "extend", "(", "zip", "(", "Interpolate", ".", "get_axes", "(", "interp", ")", ",", "interp", ".", "in_port", "(", "1", ")", ".", "get_connection", "(", ")", ".", "get_source", "(", ")", ".", "data", ".", "get_value", "(", ")", ")", ")", "axis_to_size", "=", "sorted", "(", "list", "(", "dict", "(", "dims_and_scales_", ")", ".", "items", "(", ")", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "axes_of_node", "=", "int64_array", "(", "[", "z", "[", "0", "]", "for", "z", "in", "axis_to_size", "]", ")", "sizes", "=", "shape_array", "(", "[", "z", "[", "1", "]", "for", "z", "in", "axis_to_size", "]", ")", "scales", "=", "np", ".", "ones", "(", "len", "(", "axis_to_size", ")", ",", "dtype", "=", "np", ".", "float32", ")", "else", ":", "for", "interp", "in", "seq", ":", "dims_and_scales_", ".", "extend", "(", "zip", "(", "Interpolate", ".", "get_axes", "(", "interp", ")", ",", "interp", ".", "in_port", "(", "1", ")", ".", "get_connection", "(", ")", ".", "get_source", "(", ")", ".", "data", ".", "get_value", "(", ")", ",", "interp", ".", "in_port", "(", "2", ")", ".", "get_connection", "(", ")", ".", "get_source", "(", ")", ".", "data", ".", "get_value", "(", ")", ")", ")", "axis_to_size", "=", "sorted", "(", "dims_and_scales_", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "axes_of_node", "=", "int64_array", "(", "[", "z", "[", "0", "]", "for", "z", "in", "axis_to_size", "]", ")", "sizes", "=", "shape_array", "(", "[", "z", "[", "1", "]", "for", "z", "in", "axis_to_size", "]", ")", "scales", "=", "mo_array", "(", "[", "z", "[", "2", "]", "for", "z", "in", "axis_to_size", "]", ")", "fst_interp_node", "=", "seq", "[", "0", "]", "last_interp_node", "=", "seq", "[", "-", "1", "]", "last_interp_node_name", "=", "last_interp_node", ".", "soft_get", "(", "'name'", ",", "last_interp_node", ".", "id", ")", "attributes", "=", "get_interpolate_attributes", "(", "fst_interp_node", ")", "opset", "=", "fst_interp_node", ".", "get_opset", "(", ")", "if", "opset", "==", "'opset1'", ":", "attributes", "[", "'axes'", "]", "=", "axes_of_node", "interp_node", "=", "create_op_with_const_inputs", "(", "graph", ",", "Interpolate", ",", "{", "1", ":", "sizes", "}", ",", "attributes", ")", "fst_interp_connection", "=", "fst_interp_node", ".", "in_port", "(", "0", ")", ".", "get_connection", "(", ")", "fst_interp_connection", ".", "set_destination", "(", "interp_node", ".", "in_port", "(", "0", ")", ")", "last_interp_node", ".", "out_port", "(", "0", ")", ".", "get_connection", "(", ")", ".", "set_source", "(", "interp_node", ".", "out_port", "(", "0", ")", ")", "else", ":", "attributes", "[", "'in_ports_count'", "]", "=", "4", "interp_node", "=", "create_op_with_const_inputs", "(", "graph", ",", "Interpolate", ",", "{", "1", ":", "sizes", ",", "2", ":", "scales", ",", "3", ":", "axes_of_node", "}", ",", "attributes", ")", "fst_interp_connection", "=", "fst_interp_node", ".", "in_port", "(", "0", ")", ".", "get_connection", "(", ")", "fst_interp_connection", ".", "set_destination", "(", "interp_node", ".", "in_port", "(", "0", ")", ")", "last_interp_node", ".", "out_port", "(", "0", ")", ".", "get_connection", "(", ")", ".", "set_source", "(", "interp_node", ".", "out_port", "(", "0", ")", ")", "rename_nodes", "(", "[", "(", "last_interp_node", ",", "last_interp_node_name", "+", "'/delete'", ")", ",", "(", "interp_node", ",", "last_interp_node_name", ")", "]", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/middle/InterpolateSequenceToInterpolate.py#L176-L243
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/datasets/shapenet_single.py
python
shapenet_single._get_default_path
(self)
return os.path.join(datasets.ROOT_DIR, 'data', 'ShapeNetSingle')
Return the default path where KITTI is expected to be installed.
Return the default path where KITTI is expected to be installed.
[ "Return", "the", "default", "path", "where", "KITTI", "is", "expected", "to", "be", "installed", "." ]
def _get_default_path(self): """ Return the default path where KITTI is expected to be installed. """ return os.path.join(datasets.ROOT_DIR, 'data', 'ShapeNetSingle')
[ "def", "_get_default_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "datasets", ".", "ROOT_DIR", ",", "'data'", ",", "'ShapeNetSingle'", ")" ]
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/shapenet_single.py#L130-L134
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/xSitAugment.py
python
xSitAugment.OnControlKeyEvent
(self,controlKey,activeFlag)
Control key events... anything we're interested in?
Control key events... anything we're interested in?
[ "Control", "key", "events", "...", "anything", "we", "re", "interested", "in?" ]
def OnControlKeyEvent(self,controlKey,activeFlag): "Control key events... anything we're interested in?" PtDebugPrint("Got controlKey event %d and its activeFlage is %d" % (controlKey,activeFlag)) if controlKey == PlasmaControlKeys.kKeyExitMode: self.IQuitDialog()
[ "def", "OnControlKeyEvent", "(", "self", ",", "controlKey", ",", "activeFlag", ")", ":", "PtDebugPrint", "(", "\"Got controlKey event %d and its activeFlage is %d\"", "%", "(", "controlKey", ",", "activeFlag", ")", ")", "if", "controlKey", "==", "PlasmaControlKeys", ".", "kKeyExitMode", ":", "self", ".", "IQuitDialog", "(", ")" ]
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/xSitAugment.py#L121-L125
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py
python
DocComment.IsInvalidated
(self)
return self.invalidated
Test whether Invalidate() has been called.
Test whether Invalidate() has been called.
[ "Test", "whether", "Invalidate", "()", "has", "been", "called", "." ]
def IsInvalidated(self): """Test whether Invalidate() has been called.""" return self.invalidated
[ "def", "IsInvalidated", "(", "self", ")", ":", "return", "self", ".", "invalidated" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py#L346-L348
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/message.py
python
Message.ListFields
(self)
Returns a list of (FieldDescriptor, value) tuples for all fields in the message which are not empty. A singular field is non-empty if HasField() would return true, and a repeated field is non-empty if it contains at least one element. The fields are ordered by field number
Returns a list of (FieldDescriptor, value) tuples for all fields in the message which are not empty. A singular field is non-empty if HasField() would return true, and a repeated field is non-empty if it contains at least one element. The fields are ordered by field number
[ "Returns", "a", "list", "of", "(", "FieldDescriptor", "value", ")", "tuples", "for", "all", "fields", "in", "the", "message", "which", "are", "not", "empty", ".", "A", "singular", "field", "is", "non", "-", "empty", "if", "HasField", "()", "would", "return", "true", "and", "a", "repeated", "field", "is", "non", "-", "empty", "if", "it", "contains", "at", "least", "one", "element", ".", "The", "fields", "are", "ordered", "by", "field", "number" ]
def ListFields(self): """Returns a list of (FieldDescriptor, value) tuples for all fields in the message which are not empty. A singular field is non-empty if HasField() would return true, and a repeated field is non-empty if it contains at least one element. The fields are ordered by field number""" raise NotImplementedError
[ "def", "ListFields", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/message.py#L223-L229
cathywu/Sentiment-Analysis
eb501fd1375c0c3f3ab430f963255f1bb858e659
PyML-0.7.9/PyML/containers/ker.py
python
expandKernel
(inKernelFile, referenceKernelFile, outKernelFile, **args)
Given a kernel matrix that might have missing entries, fill those as 0 on the basis of the patterns in a reference kernel (it is checked that the reference kernel is sorted). :Parameters: - `inKernelFile` - input kernel file name - `referenceKernelFile` - file name for the reference kernel - `outKernelFile` - file name to output expanded kernel
Given a kernel matrix that might have missing entries, fill those as 0 on the basis of the patterns in a reference kernel (it is checked that the reference kernel is sorted). :Parameters: - `inKernelFile` - input kernel file name - `referenceKernelFile` - file name for the reference kernel - `outKernelFile` - file name to output expanded kernel
[ "Given", "a", "kernel", "matrix", "that", "might", "have", "missing", "entries", "fill", "those", "as", "0", "on", "the", "basis", "of", "the", "patterns", "in", "a", "reference", "kernel", "(", "it", "is", "checked", "that", "the", "reference", "kernel", "is", "sorted", ")", ".", ":", "Parameters", ":", "-", "inKernelFile", "-", "input", "kernel", "file", "name", "-", "referenceKernelFile", "-", "file", "name", "for", "the", "reference", "kernel", "-", "outKernelFile", "-", "file", "name", "to", "output", "expanded", "kernel" ]
def expandKernel(inKernelFile, referenceKernelFile, outKernelFile, **args) : """ Given a kernel matrix that might have missing entries, fill those as 0 on the basis of the patterns in a reference kernel (it is checked that the reference kernel is sorted). :Parameters: - `inKernelFile` - input kernel file name - `referenceKernelFile` - file name for the reference kernel - `outKernelFile` - file name to output expanded kernel """ if 'format' in args : format = args['format'] else : format = 'gist' delim = '\t' from datafunc import KernelData import misc import numpy inKernel = KernelData(inKernelFile) refKernel = KernelData(referenceKernelFile) print 'loaded data' ids = refKernel.labels.patternID[:] ids.sort() if ids != refKernel.labels.patternID : raise ValueError, 'reference kernel not sorted' idDict = misc.list2dict(inKernel.labels.patternID) outKernel = open(outKernelFile, 'w') if format == 'gist' : outKernel.write(outKernelFile + delim) outKernel.write(delim.join(ids) + '\n') for i in range(len(refKernel)) : outKernel.write(id1 + delim) for j in range(len(refKernel)) : values = numpy.zeros(len(refKernel), numpy.float_) if ids[i] in idDict and ids[j] in idDict : values[j] = inKernel.kernel.eval(inKernel, idDict[ids[i]],idDict[ids[j]]) tokens = [str(value) for value in values] outKernel.write(delim.join(tokens) + '\n')
[ "def", "expandKernel", "(", "inKernelFile", ",", "referenceKernelFile", ",", "outKernelFile", ",", "*", "*", "args", ")", ":", "if", "'format'", "in", "args", ":", "format", "=", "args", "[", "'format'", "]", "else", ":", "format", "=", "'gist'", "delim", "=", "'\\t'", "from", "datafunc", "import", "KernelData", "import", "misc", "import", "numpy", "inKernel", "=", "KernelData", "(", "inKernelFile", ")", "refKernel", "=", "KernelData", "(", "referenceKernelFile", ")", "print", "'loaded data'", "ids", "=", "refKernel", ".", "labels", ".", "patternID", "[", ":", "]", "ids", ".", "sort", "(", ")", "if", "ids", "!=", "refKernel", ".", "labels", ".", "patternID", ":", "raise", "ValueError", ",", "'reference kernel not sorted'", "idDict", "=", "misc", ".", "list2dict", "(", "inKernel", ".", "labels", ".", "patternID", ")", "outKernel", "=", "open", "(", "outKernelFile", ",", "'w'", ")", "if", "format", "==", "'gist'", ":", "outKernel", ".", "write", "(", "outKernelFile", "+", "delim", ")", "outKernel", ".", "write", "(", "delim", ".", "join", "(", "ids", ")", "+", "'\\n'", ")", "for", "i", "in", "range", "(", "len", "(", "refKernel", ")", ")", ":", "outKernel", ".", "write", "(", "id1", "+", "delim", ")", "for", "j", "in", "range", "(", "len", "(", "refKernel", ")", ")", ":", "values", "=", "numpy", ".", "zeros", "(", "len", "(", "refKernel", ")", ",", "numpy", ".", "float_", ")", "if", "ids", "[", "i", "]", "in", "idDict", "and", "ids", "[", "j", "]", "in", "idDict", ":", "values", "[", "j", "]", "=", "inKernel", ".", "kernel", ".", "eval", "(", "inKernel", ",", "idDict", "[", "ids", "[", "i", "]", "]", ",", "idDict", "[", "ids", "[", "j", "]", "]", ")", "tokens", "=", "[", "str", "(", "value", ")", "for", "value", "in", "values", "]", "outKernel", ".", "write", "(", "delim", ".", "join", "(", "tokens", ")", "+", "'\\n'", ")" ]
https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/containers/ker.py#L448-L493
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc.winfo_reqheight
(self)
return getint( self.tk.call('winfo', 'reqheight', self._w))
Return requested height of this widget.
Return requested height of this widget.
[ "Return", "requested", "height", "of", "this", "widget", "." ]
def winfo_reqheight(self): """Return requested height of this widget.""" return getint( self.tk.call('winfo', 'reqheight', self._w))
[ "def", "winfo_reqheight", "(", "self", ")", ":", "return", "getint", "(", "self", ".", "tk", ".", "call", "(", "'winfo'", ",", "'reqheight'", ",", "self", ".", "_w", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L825-L828
ptrkrysik/gr-gsm
2de47e28ce1fb9a518337bfc0add36c8e3cff5eb
python/receiver/chirpz.py
python
CZT.__call__
(self, x, axis=-1)
return y.transpose(*trnsp)
Parameters: ---------- x: array The signal to transform. axis: int Array dimension to operate over. The default is the final dimension. Returns: ------- An array of the same dimensions as x, but with the length of the transformed axis set to m. Note that this is a view on a much larger array. To save space, you may want to call it as y = czt(x).copy()
Parameters: ---------- x: array The signal to transform. axis: int Array dimension to operate over. The default is the final dimension.
[ "Parameters", ":", "----------", "x", ":", "array", "The", "signal", "to", "transform", ".", "axis", ":", "int", "Array", "dimension", "to", "operate", "over", ".", "The", "default", "is", "the", "final", "dimension", "." ]
def __call__(self, x, axis=-1): """ Parameters: ---------- x: array The signal to transform. axis: int Array dimension to operate over. The default is the final dimension. Returns: ------- An array of the same dimensions as x, but with the length of the transformed axis set to m. Note that this is a view on a much larger array. To save space, you may want to call it as y = czt(x).copy() """ x = np.asarray(x) if x.shape[axis] != self.n: raise ValueError("CZT defined for length %d, not %d" % (self.n, x.shape[axis])) # Calculate transpose coordinates, to allow operation on any given axis trnsp = np.arange(x.ndim) trnsp[[axis, -1]] = [-1, axis] x = x.transpose(*trnsp) y = ifft(self._Fwk2 * fft(x*self._Awk2, self._nfft)) y = y[..., self._yidx] * self._wk2 return y.transpose(*trnsp)
[ "def", "__call__", "(", "self", ",", "x", ",", "axis", "=", "-", "1", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "if", "x", ".", "shape", "[", "axis", "]", "!=", "self", ".", "n", ":", "raise", "ValueError", "(", "\"CZT defined for length %d, not %d\"", "%", "(", "self", ".", "n", ",", "x", ".", "shape", "[", "axis", "]", ")", ")", "# Calculate transpose coordinates, to allow operation on any given axis", "trnsp", "=", "np", ".", "arange", "(", "x", ".", "ndim", ")", "trnsp", "[", "[", "axis", ",", "-", "1", "]", "]", "=", "[", "-", "1", ",", "axis", "]", "x", "=", "x", ".", "transpose", "(", "*", "trnsp", ")", "y", "=", "ifft", "(", "self", ".", "_Fwk2", "*", "fft", "(", "x", "*", "self", ".", "_Awk2", ",", "self", ".", "_nfft", ")", ")", "y", "=", "y", "[", "...", ",", "self", ".", "_yidx", "]", "*", "self", ".", "_wk2", "return", "y", ".", "transpose", "(", "*", "trnsp", ")" ]
https://github.com/ptrkrysik/gr-gsm/blob/2de47e28ce1fb9a518337bfc0add36c8e3cff5eb/python/receiver/chirpz.py#L96-L123
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/stats/_multivariate.py
python
matrix_normal_frozen.__init__
(self, mean=None, rowcov=1, colcov=1, seed=None)
Create a frozen matrix normal distribution. Parameters ---------- %(_matnorm_doc_default_callparams)s seed : None or int or np.random.RandomState instance, optional If int or RandomState, use it for drawing the random variates. If None (or np.random), the global np.random state is used. Default is None. Examples -------- >>> from scipy.stats import matrix_normal >>> distn = matrix_normal(mean=np.zeros((3,3))) >>> X = distn.rvs(); X array([[-0.02976962, 0.93339138, -0.09663178], [ 0.67405524, 0.28250467, -0.93308929], [-0.31144782, 0.74535536, 1.30412916]]) >>> distn.pdf(X) 2.5160642368346784e-05 >>> distn.logpdf(X) -10.590229595124615
Create a frozen matrix normal distribution.
[ "Create", "a", "frozen", "matrix", "normal", "distribution", "." ]
def __init__(self, mean=None, rowcov=1, colcov=1, seed=None): """ Create a frozen matrix normal distribution. Parameters ---------- %(_matnorm_doc_default_callparams)s seed : None or int or np.random.RandomState instance, optional If int or RandomState, use it for drawing the random variates. If None (or np.random), the global np.random state is used. Default is None. Examples -------- >>> from scipy.stats import matrix_normal >>> distn = matrix_normal(mean=np.zeros((3,3))) >>> X = distn.rvs(); X array([[-0.02976962, 0.93339138, -0.09663178], [ 0.67405524, 0.28250467, -0.93308929], [-0.31144782, 0.74535536, 1.30412916]]) >>> distn.pdf(X) 2.5160642368346784e-05 >>> distn.logpdf(X) -10.590229595124615 """ self._dist = matrix_normal_gen(seed) self.dims, self.mean, self.rowcov, self.colcov = \ self._dist._process_parameters(mean, rowcov, colcov) self.rowpsd = _PSD(self.rowcov, allow_singular=False) self.colpsd = _PSD(self.colcov, allow_singular=False)
[ "def", "__init__", "(", "self", ",", "mean", "=", "None", ",", "rowcov", "=", "1", ",", "colcov", "=", "1", ",", "seed", "=", "None", ")", ":", "self", ".", "_dist", "=", "matrix_normal_gen", "(", "seed", ")", "self", ".", "dims", ",", "self", ".", "mean", ",", "self", ".", "rowcov", ",", "self", ".", "colcov", "=", "self", ".", "_dist", ".", "_process_parameters", "(", "mean", ",", "rowcov", ",", "colcov", ")", "self", ".", "rowpsd", "=", "_PSD", "(", "self", ".", "rowcov", ",", "allow_singular", "=", "False", ")", "self", ".", "colpsd", "=", "_PSD", "(", "self", ".", "colcov", ",", "allow_singular", "=", "False", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_multivariate.py#L994-L1024
taichi-dev/taichi
973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6
python/taichi/_snode/fields_builder.py
python
FieldsBuilder.finalized_roots
(cls)
return roots_ptr
Gets all the roots of the finalized SNodeTree. Returns: A list of the roots of the finalized SNodeTree.
Gets all the roots of the finalized SNodeTree.
[ "Gets", "all", "the", "roots", "of", "the", "finalized", "SNodeTree", "." ]
def finalized_roots(cls): """Gets all the roots of the finalized SNodeTree. Returns: A list of the roots of the finalized SNodeTree. """ roots_ptr = [] size = impl.get_runtime().prog.get_snode_tree_size() for i in range(size): res = impl.get_runtime().prog.get_snode_root(i) roots_ptr.append(snode.SNode(res)) return roots_ptr
[ "def", "finalized_roots", "(", "cls", ")", ":", "roots_ptr", "=", "[", "]", "size", "=", "impl", ".", "get_runtime", "(", ")", ".", "prog", ".", "get_snode_tree_size", "(", ")", "for", "i", "in", "range", "(", "size", ")", ":", "res", "=", "impl", ".", "get_runtime", "(", ")", ".", "prog", ".", "get_snode_root", "(", "i", ")", "roots_ptr", ".", "append", "(", "snode", ".", "SNode", "(", "res", ")", ")", "return", "roots_ptr" ]
https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/_snode/fields_builder.py#L44-L55
sonyxperiadev/WebGL
0299b38196f78c6d5f74bcf6fa312a3daee6de60
Tools/Scripts/webkitpy/thirdparty/simplejson/encoder.py
python
JSONEncoder.encode
(self, o)
return ''.join(chunks)
Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo":["bar", "baz"]}'
Return a JSON string representation of a Python data structure.
[ "Return", "a", "JSON", "string", "representation", "of", "a", "Python", "data", "structure", "." ]
def encode(self, o): """ Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo":["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks... if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8' and _need_utf8)): o = o.decode(_encoding) return encode_basestring_ascii(o) # This doesn't pass the iterator directly to ''.join() because it # sucks at reporting exceptions. It's going to do this internally # anyway because it uses PySequence_Fast or similar. chunks = list(self.iterencode(o)) return ''.join(chunks)
[ "def", "encode", "(", "self", ",", "o", ")", ":", "# This is for extremely simple cases and benchmarks...", "if", "isinstance", "(", "o", ",", "basestring", ")", ":", "if", "isinstance", "(", "o", ",", "str", ")", ":", "_encoding", "=", "self", ".", "encoding", "if", "(", "_encoding", "is", "not", "None", "and", "not", "(", "_encoding", "==", "'utf-8'", "and", "_need_utf8", ")", ")", ":", "o", "=", "o", ".", "decode", "(", "_encoding", ")", "return", "encode_basestring_ascii", "(", "o", ")", "# This doesn't pass the iterator directly to ''.join() because it", "# sucks at reporting exceptions. It's going to do this internally", "# anyway because it uses PySequence_Fast or similar.", "chunks", "=", "list", "(", "self", ".", "iterencode", "(", "o", ")", ")", "return", "''", ".", "join", "(", "chunks", ")" ]
https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/thirdparty/simplejson/encoder.py#L334-L353
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/pytables.py
python
GenericFixed.validate_read
(self, columns, where)
raise if any keywords are passed which are not-None
raise if any keywords are passed which are not-None
[ "raise", "if", "any", "keywords", "are", "passed", "which", "are", "not", "-", "None" ]
def validate_read(self, columns, where): """ raise if any keywords are passed which are not-None """ if columns is not None: raise TypeError( "cannot pass a column specification when reading " "a Fixed format store. this store must be selected in its entirety" ) if where is not None: raise TypeError( "cannot pass a where specification when reading " "from a Fixed format store. this store must be selected in its entirety" )
[ "def", "validate_read", "(", "self", ",", "columns", ",", "where", ")", ":", "if", "columns", "is", "not", "None", ":", "raise", "TypeError", "(", "\"cannot pass a column specification when reading \"", "\"a Fixed format store. this store must be selected in its entirety\"", ")", "if", "where", "is", "not", "None", ":", "raise", "TypeError", "(", "\"cannot pass a where specification when reading \"", "\"from a Fixed format store. this store must be selected in its entirety\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/pytables.py#L2820-L2833
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenu.DrawSelection
(self, dc, oldSelection=-1)
Redraws the menu. :param `dc`: an instance of :class:`DC`; :param integer `oldSelection`: if non-negative, the index representing the previous selected menu item.
Redraws the menu.
[ "Redraws", "the", "menu", "." ]
def DrawSelection(self, dc, oldSelection=-1): """ Redraws the menu. :param `dc`: an instance of :class:`DC`; :param integer `oldSelection`: if non-negative, the index representing the previous selected menu item. """ self.Refresh()
[ "def", "DrawSelection", "(", "self", ",", "dc", ",", "oldSelection", "=", "-", "1", ")", ":", "self", ".", "Refresh", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L5803-L5812
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/google/protobuf/internal/encoder.py
python
MessageEncoder
(field_number, is_repeated, is_packed)
Returns an encoder for a message field.
Returns an encoder for a message field.
[ "Returns", "an", "encoder", "for", "a", "message", "field", "." ]
def MessageEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a message field.""" tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint assert not is_packed if is_repeated: def EncodeRepeatedField(write, value): for element in value: write(tag) local_EncodeVarint(write, element.ByteSize()) element._InternalSerialize(write) return EncodeRepeatedField else: def EncodeField(write, value): write(tag) local_EncodeVarint(write, value.ByteSize()) return value._InternalSerialize(write) return EncodeField
[ "def", "MessageEncoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "tag", "=", "TagBytes", "(", "field_number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMITED", ")", "local_EncodeVarint", "=", "_EncodeVarint", "assert", "not", "is_packed", "if", "is_repeated", ":", "def", "EncodeRepeatedField", "(", "write", ",", "value", ")", ":", "for", "element", "in", "value", ":", "write", "(", "tag", ")", "local_EncodeVarint", "(", "write", ",", "element", ".", "ByteSize", "(", ")", ")", "element", ".", "_InternalSerialize", "(", "write", ")", "return", "EncodeRepeatedField", "else", ":", "def", "EncodeField", "(", "write", ",", "value", ")", ":", "write", "(", "tag", ")", "local_EncodeVarint", "(", "write", ",", "value", ".", "ByteSize", "(", ")", ")", "return", "value", ".", "_InternalSerialize", "(", "write", ")", "return", "EncodeField" ]
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/encoder.py#L719-L737
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/experiments/python/net_construct_bench.py
python
AddMomentumParameterUpdate
(train_model, LR)
Add the momentum-SGD update.
Add the momentum-SGD update.
[ "Add", "the", "momentum", "-", "SGD", "update", "." ]
def AddMomentumParameterUpdate(train_model, LR): ''' Add the momentum-SGD update. ''' params = train_model.GetParams() assert(len(params) > 0) ONE = train_model.param_init_net.ConstantFill( [], "ONE", shape=[1], value=1.0, ) NEGONE = train_model.param_init_net.ConstantFill( [], 'NEGONE', shape=[1], value=-1.0, ) for param in params: param_grad = train_model.param_to_grad[param] param_momentum = train_model.param_init_net.ConstantFill( [param], param + '_momentum', value=0.0 ) # Update param_grad and param_momentum in place train_model.net.MomentumSGD( [param_grad, param_momentum, LR], [param_grad, param_momentum], momentum=0.9, nesterov=1 ) # Update parameters by applying the moment-adjusted gradient train_model.WeightedSum( [param, ONE, param_grad, NEGONE], param )
[ "def", "AddMomentumParameterUpdate", "(", "train_model", ",", "LR", ")", ":", "params", "=", "train_model", ".", "GetParams", "(", ")", "assert", "(", "len", "(", "params", ")", ">", "0", ")", "ONE", "=", "train_model", ".", "param_init_net", ".", "ConstantFill", "(", "[", "]", ",", "\"ONE\"", ",", "shape", "=", "[", "1", "]", ",", "value", "=", "1.0", ",", ")", "NEGONE", "=", "train_model", ".", "param_init_net", ".", "ConstantFill", "(", "[", "]", ",", "'NEGONE'", ",", "shape", "=", "[", "1", "]", ",", "value", "=", "-", "1.0", ",", ")", "for", "param", "in", "params", ":", "param_grad", "=", "train_model", ".", "param_to_grad", "[", "param", "]", "param_momentum", "=", "train_model", ".", "param_init_net", ".", "ConstantFill", "(", "[", "param", "]", ",", "param", "+", "'_momentum'", ",", "value", "=", "0.0", ")", "# Update param_grad and param_momentum in place", "train_model", ".", "net", ".", "MomentumSGD", "(", "[", "param_grad", ",", "param_momentum", ",", "LR", "]", ",", "[", "param_grad", ",", "param_momentum", "]", ",", "momentum", "=", "0.9", ",", "nesterov", "=", "1", ")", "# Update parameters by applying the moment-adjusted gradient", "train_model", ".", "WeightedSum", "(", "[", "param", ",", "ONE", ",", "param_grad", ",", "NEGONE", "]", ",", "param", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/experiments/python/net_construct_bench.py#L43-L74
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py
python
python_2_unicode_compatible
(klass)
return klass
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing.
[ "A", "decorator", "that", "defines", "__unicode__", "and", "__str__", "methods", "under", "Python", "2", ".", "Under", "Python", "3", "it", "does", "nothing", "." ]
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if "__str__" not in klass.__dict__: raise ValueError( "@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__ ) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode("utf-8") return klass
[ "def", "python_2_unicode_compatible", "(", "klass", ")", ":", "if", "PY2", ":", "if", "\"__str__\"", "not", "in", "klass", ".", "__dict__", ":", "raise", "ValueError", "(", "\"@python_2_unicode_compatible cannot be applied \"", "\"to %s because it doesn't define __str__().\"", "%", "klass", ".", "__name__", ")", "klass", ".", "__unicode__", "=", "klass", ".", "__str__", "klass", ".", "__str__", "=", "lambda", "self", ":", "self", ".", "__unicode__", "(", ")", ".", "encode", "(", "\"utf-8\"", ")", "return", "klass" ]
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/urllib3/packages/six.py#L978-L994
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/tools/grokdump.py
python
InspectionShell.do_search
(self, word)
Search for a given word in available memory regions. The given word is expanded to full pointer size and searched at aligned as well as un-aligned memory locations. Use 'sa' to search aligned locations only.
Search for a given word in available memory regions.
[ "Search", "for", "a", "given", "word", "in", "available", "memory", "regions", "." ]
def do_search(self, word): """ Search for a given word in available memory regions. The given word is expanded to full pointer size and searched at aligned as well as un-aligned memory locations. Use 'sa' to search aligned locations only. """ try: word = self.ParseAddressExpr(word) except ValueError: print("Malformed word, prefix with '0x' to use hexadecimal format.") return print( "Searching for word %d/0x%s:" % (word, self.reader.FormatIntPtr(word))) self.reader.FindWord(word)
[ "def", "do_search", "(", "self", ",", "word", ")", ":", "try", ":", "word", "=", "self", ".", "ParseAddressExpr", "(", "word", ")", "except", "ValueError", ":", "print", "(", "\"Malformed word, prefix with '0x' to use hexadecimal format.\"", ")", "return", "print", "(", "\"Searching for word %d/0x%s:\"", "%", "(", "word", ",", "self", ".", "reader", ".", "FormatIntPtr", "(", "word", ")", ")", ")", "self", ".", "reader", ".", "FindWord", "(", "word", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/grokdump.py#L3714-L3729
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
If
(a, b, c, ctx=None)
Create a Z3 if-then-else expression. >>> x = Int('x') >>> y = Int('y') >>> max = If(x > y, x, y) >>> max If(x > y, x, y) >>> simplify(max) If(x <= y, y, x)
Create a Z3 if-then-else expression.
[ "Create", "a", "Z3", "if", "-", "then", "-", "else", "expression", "." ]
def If(a, b, c, ctx=None): """Create a Z3 if-then-else expression. >>> x = Int('x') >>> y = Int('y') >>> max = If(x > y, x, y) >>> max If(x > y, x, y) >>> simplify(max) If(x <= y, y, x) """ if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic): return Cond(a, b, c, ctx) else: ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx)) s = BoolSort(ctx) a = s.cast(a) b, c = _coerce_exprs(b, c, ctx) if z3_debug(): _z3_assert(a.ctx == b.ctx, "Context mismatch") return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
[ "def", "If", "(", "a", ",", "b", ",", "c", ",", "ctx", "=", "None", ")", ":", "if", "isinstance", "(", "a", ",", "Probe", ")", "or", "isinstance", "(", "b", ",", "Tactic", ")", "or", "isinstance", "(", "c", ",", "Tactic", ")", ":", "return", "Cond", "(", "a", ",", "b", ",", "c", ",", "ctx", ")", "else", ":", "ctx", "=", "_get_ctx", "(", "_ctx_from_ast_arg_list", "(", "[", "a", ",", "b", ",", "c", "]", ",", "ctx", ")", ")", "s", "=", "BoolSort", "(", "ctx", ")", "a", "=", "s", ".", "cast", "(", "a", ")", "b", ",", "c", "=", "_coerce_exprs", "(", "b", ",", "c", ",", "ctx", ")", "if", "z3_debug", "(", ")", ":", "_z3_assert", "(", "a", ".", "ctx", "==", "b", ".", "ctx", ",", "\"Context mismatch\"", ")", "return", "_to_expr_ref", "(", "Z3_mk_ite", "(", "ctx", ".", "ref", "(", ")", ",", "a", ".", "as_ast", "(", ")", ",", "b", ".", "as_ast", "(", ")", ",", "c", ".", "as_ast", "(", ")", ")", ",", "ctx", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L1353-L1373
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
elle/drake/src/drake/go/__init__.py
python
Toolkit.__init__
(self, tk = None, path = None, root = None, os = None, arch = None, cxx_toolkit = drake.cxx.Toolkit())
Create a toolkit or clone an existing one. :param tk: The toolkit to clone. If specified, other arguments must be None :type tk: Toolkit :param path: The home of your go environment (override GOPATH). :type path: str :param root: The root of your go installation (override GOROOT). :type root: str :param os: The target os for cross-compilation (override GOOS). :type os: str :param arch: The target arch for cross-compilation (override GOARCH). :type arch: str Example: t = Toolkit(os = "windows", arch = "amd64") print(t.os) > "windows" print(t.env) {"GOOS": "windows", "GOARCH": "amd64"} t2 = Toolkit(t) print(t2.arch) > "amd64"
Create a toolkit or clone an existing one.
[ "Create", "a", "toolkit", "or", "clone", "an", "existing", "one", "." ]
def __init__(self, tk = None, path = None, root = None, os = None, arch = None, cxx_toolkit = drake.cxx.Toolkit()): """ Create a toolkit or clone an existing one. :param tk: The toolkit to clone. If specified, other arguments must be None :type tk: Toolkit :param path: The home of your go environment (override GOPATH). :type path: str :param root: The root of your go installation (override GOROOT). :type root: str :param os: The target os for cross-compilation (override GOOS). :type os: str :param arch: The target arch for cross-compilation (override GOARCH). :type arch: str Example: t = Toolkit(os = "windows", arch = "amd64") print(t.os) > "windows" print(t.env) {"GOOS": "windows", "GOARCH": "amd64"} t2 = Toolkit(t) print(t2.arch) > "amd64" """ if isinstance(tk, Toolkit): assert all(a is None for a in [path, root, os, arch]) return super().__init__(path = tk.path, root = tk.root, os = tk.os, arch = tk.arch) else: self.__arch = arch self.__go = tk or which('go') self.__path = path self.__os = os self.__root = root self.__version = None self.__env = False self.__cxx_toolkit = cxx_toolkit if self.go is None: raise Exception('go executable is undefined. Check its installation') try: self.run(['help']) except FileNotFoundError: raise Exception('go executable not found')
[ "def", "__init__", "(", "self", ",", "tk", "=", "None", ",", "path", "=", "None", ",", "root", "=", "None", ",", "os", "=", "None", ",", "arch", "=", "None", ",", "cxx_toolkit", "=", "drake", ".", "cxx", ".", "Toolkit", "(", ")", ")", ":", "if", "isinstance", "(", "tk", ",", "Toolkit", ")", ":", "assert", "all", "(", "a", "is", "None", "for", "a", "in", "[", "path", ",", "root", ",", "os", ",", "arch", "]", ")", "return", "super", "(", ")", ".", "__init__", "(", "path", "=", "tk", ".", "path", ",", "root", "=", "tk", ".", "root", ",", "os", "=", "tk", ".", "os", ",", "arch", "=", "tk", ".", "arch", ")", "else", ":", "self", ".", "__arch", "=", "arch", "self", ".", "__go", "=", "tk", "or", "which", "(", "'go'", ")", "self", ".", "__path", "=", "path", "self", ".", "__os", "=", "os", "self", ".", "__root", "=", "root", "self", ".", "__version", "=", "None", "self", ".", "__env", "=", "False", "self", ".", "__cxx_toolkit", "=", "cxx_toolkit", "if", "self", ".", "go", "is", "None", ":", "raise", "Exception", "(", "'go executable is undefined. Check its installation'", ")", "try", ":", "self", ".", "run", "(", "[", "'help'", "]", ")", "except", "FileNotFoundError", ":", "raise", "Exception", "(", "'go executable not found'", ")" ]
https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/go/__init__.py#L168-L221
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/perf/metrics/speedindex.py
python
SpeedIndexImpl.CalculateSpeedIndex
(self, tab)
return int(speed_index)
Calculate the speed index. The speed index number conceptually represents the number of milliseconds that the page was "visually incomplete". If the page were 0% complete for 1000 ms, then the score would be 1000; if it were 0% complete for 100 ms then 90% complete (ie 10% incomplete) for 900 ms, then the score would be 1.0*100 + 0.1*900 = 190. Returns: A single number, milliseconds of visual incompleteness.
Calculate the speed index.
[ "Calculate", "the", "speed", "index", "." ]
def CalculateSpeedIndex(self, tab): """Calculate the speed index. The speed index number conceptually represents the number of milliseconds that the page was "visually incomplete". If the page were 0% complete for 1000 ms, then the score would be 1000; if it were 0% complete for 100 ms then 90% complete (ie 10% incomplete) for 900 ms, then the score would be 1.0*100 + 0.1*900 = 190. Returns: A single number, milliseconds of visual incompleteness. """ time_completeness_list = self.GetTimeCompletenessList(tab) prev_completeness = 0.0 speed_index = 0.0 prev_time = time_completeness_list[0][0] for time, completeness in time_completeness_list: # Add the incremental value for the interval just before this event. elapsed_time = time - prev_time incompleteness = (1.0 - prev_completeness) speed_index += elapsed_time * incompleteness # Update variables for next iteration. prev_completeness = completeness prev_time = time return int(speed_index)
[ "def", "CalculateSpeedIndex", "(", "self", ",", "tab", ")", ":", "time_completeness_list", "=", "self", ".", "GetTimeCompletenessList", "(", "tab", ")", "prev_completeness", "=", "0.0", "speed_index", "=", "0.0", "prev_time", "=", "time_completeness_list", "[", "0", "]", "[", "0", "]", "for", "time", ",", "completeness", "in", "time_completeness_list", ":", "# Add the incremental value for the interval just before this event.", "elapsed_time", "=", "time", "-", "prev_time", "incompleteness", "=", "(", "1.0", "-", "prev_completeness", ")", "speed_index", "+=", "elapsed_time", "*", "incompleteness", "# Update variables for next iteration.", "prev_completeness", "=", "completeness", "prev_time", "=", "time", "return", "int", "(", "speed_index", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/perf/metrics/speedindex.py#L116-L141
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/stats.py
python
tvar
(a, limits=None, inclusive=(True, True), axis=0, ddof=1)
return np.ma.var(am, ddof=ddof, axis=axis)
Compute the trimmed variance. This function computes the sample variance of an array of values, while ignoring values which are outside of given `limits`. Parameters ---------- a : array_like Array of values. limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None, then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. The default value is None. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Delta degrees of freedom. Default is 1. Returns ------- tvar : float Trimmed variance. Notes ----- `tvar` computes the unbiased sample variance, i.e. it uses a correction factor ``n / (n - 1)``. Examples -------- >>> from scipy import stats >>> x = np.arange(20) >>> stats.tvar(x) 35.0 >>> stats.tvar(x, (3,17)) 20.0
Compute the trimmed variance.
[ "Compute", "the", "trimmed", "variance", "." ]
def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1): """ Compute the trimmed variance. This function computes the sample variance of an array of values, while ignoring values which are outside of given `limits`. Parameters ---------- a : array_like Array of values. limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None, then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. The default value is None. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Delta degrees of freedom. Default is 1. Returns ------- tvar : float Trimmed variance. Notes ----- `tvar` computes the unbiased sample variance, i.e. it uses a correction factor ``n / (n - 1)``. Examples -------- >>> from scipy import stats >>> x = np.arange(20) >>> stats.tvar(x) 35.0 >>> stats.tvar(x, (3,17)) 20.0 """ a = asarray(a) a = a.astype(float).ravel() if limits is None: n = len(a) return a.var() * n / (n - 1.) am = _mask_to_limits(a, limits, inclusive) return np.ma.var(am, ddof=ddof, axis=axis)
[ "def", "tvar", "(", "a", ",", "limits", "=", "None", ",", "inclusive", "=", "(", "True", ",", "True", ")", ",", "axis", "=", "0", ",", "ddof", "=", "1", ")", ":", "a", "=", "asarray", "(", "a", ")", "a", "=", "a", ".", "astype", "(", "float", ")", ".", "ravel", "(", ")", "if", "limits", "is", "None", ":", "n", "=", "len", "(", "a", ")", "return", "a", ".", "var", "(", ")", "*", "n", "/", "(", "n", "-", "1.", ")", "am", "=", "_mask_to_limits", "(", "a", ",", "limits", ",", "inclusive", ")", "return", "np", ".", "ma", ".", "var", "(", "am", ",", "ddof", "=", "ddof", ",", "axis", "=", "axis", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/stats.py#L574-L626
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
BusyCursor.__init__
(self, *args, **kwargs)
__init__(self, Cursor cursor=wxHOURGLASS_CURSOR) -> BusyCursor
__init__(self, Cursor cursor=wxHOURGLASS_CURSOR) -> BusyCursor
[ "__init__", "(", "self", "Cursor", "cursor", "=", "wxHOURGLASS_CURSOR", ")", "-", ">", "BusyCursor" ]
def __init__(self, *args, **kwargs): """__init__(self, Cursor cursor=wxHOURGLASS_CURSOR) -> BusyCursor""" _misc_.BusyCursor_swiginit(self,_misc_.new_BusyCursor(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "BusyCursor_swiginit", "(", "self", ",", "_misc_", ".", "new_BusyCursor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L826-L828
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/transforms.py
python
_cfg_nodes_in_region
(cfg, region_begin, region_end)
return region_nodes
Find the set of CFG nodes that are in the given region
Find the set of CFG nodes that are in the given region
[ "Find", "the", "set", "of", "CFG", "nodes", "that", "are", "in", "the", "given", "region" ]
def _cfg_nodes_in_region(cfg, region_begin, region_end): """Find the set of CFG nodes that are in the given region """ region_nodes = set() stack = [region_begin] while stack: tos = stack.pop() succs, _ = zip(*cfg.successors(tos)) nodes = set([node for node in succs if node not in region_nodes and node != region_end]) stack.extend(nodes) region_nodes |= nodes return region_nodes
[ "def", "_cfg_nodes_in_region", "(", "cfg", ",", "region_begin", ",", "region_end", ")", ":", "region_nodes", "=", "set", "(", ")", "stack", "=", "[", "region_begin", "]", "while", "stack", ":", "tos", "=", "stack", ".", "pop", "(", ")", "succs", ",", "_", "=", "zip", "(", "*", "cfg", ".", "successors", "(", "tos", ")", ")", "nodes", "=", "set", "(", "[", "node", "for", "node", "in", "succs", "if", "node", "not", "in", "region_nodes", "and", "node", "!=", "region_end", "]", ")", "stack", ".", "extend", "(", "nodes", ")", "region_nodes", "|=", "nodes", "return", "region_nodes" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/transforms.py#L460-L474
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
WithImages.AssignImageList
(*args, **kwargs)
return _core_.WithImages_AssignImageList(*args, **kwargs)
AssignImageList(self, ImageList imageList)
AssignImageList(self, ImageList imageList)
[ "AssignImageList", "(", "self", "ImageList", "imageList", ")" ]
def AssignImageList(*args, **kwargs): """AssignImageList(self, ImageList imageList)""" return _core_.WithImages_AssignImageList(*args, **kwargs)
[ "def", "AssignImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "WithImages_AssignImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13502-L13504
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
benchmarks/functional_autograd_benchmark/torchvision_models.py
python
accuracy
(output, target, topk=(1,))
return res
Computes the precision@k for the specified values of k
Computes the precision
[ "Computes", "the", "precision" ]
def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" if target.numel() == 0: return [torch.zeros([], device=output.device)] maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res
[ "def", "accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", ")", ")", ":", "if", "target", ".", "numel", "(", ")", "==", "0", ":", "return", "[", "torch", ".", "zeros", "(", "[", "]", ",", "device", "=", "output", ".", "device", ")", "]", "maxk", "=", "max", "(", "topk", ")", "batch_size", "=", "target", ".", "size", "(", "0", ")", "_", ",", "pred", "=", "output", ".", "topk", "(", "maxk", ",", "1", ",", "True", ",", "True", ")", "pred", "=", "pred", ".", "t", "(", ")", "correct", "=", "pred", ".", "eq", "(", "target", ".", "view", "(", "1", ",", "-", "1", ")", ".", "expand_as", "(", "pred", ")", ")", "res", "=", "[", "]", "for", "k", "in", "topk", ":", "correct_k", "=", "correct", "[", ":", "k", "]", ".", "view", "(", "-", "1", ")", ".", "float", "(", ")", ".", "sum", "(", "0", ")", "res", ".", "append", "(", "correct_k", ".", "mul_", "(", "100.0", "/", "batch_size", ")", ")", "return", "res" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/functional_autograd_benchmark/torchvision_models.py#L544-L559
Yaafe/Yaafe
f5ed847bdbf540b47e8fe1980dddfb5509ae7f9d
src_python/yaafelib/dataflow.py
python
DataFlow.loads
(self, buf)
return False
Build DataFlow from buf read from a :ref:`dataflow file <dataflow-file>`. :param buf: buffer read from a dataflow file :type buf: string :return: True on success, False on fail.
Build DataFlow from buf read from a :ref:`dataflow file <dataflow-file>`.
[ "Build", "DataFlow", "from", "buf", "read", "from", "a", ":", "ref", ":", "dataflow", "file", "<dataflow", "-", "file", ">", "." ]
def loads(self, buf): """ Build DataFlow from buf read from a :ref:`dataflow file <dataflow-file>`. :param buf: buffer read from a dataflow file :type buf: string :return: True on success, False on fail. """ if yc.dataflow_loads(self.ptr, to_char(buf)): self.update_state() return True return False
[ "def", "loads", "(", "self", ",", "buf", ")", ":", "if", "yc", ".", "dataflow_loads", "(", "self", ".", "ptr", ",", "to_char", "(", "buf", ")", ")", ":", "self", ".", "update_state", "(", ")", "return", "True", "return", "False" ]
https://github.com/Yaafe/Yaafe/blob/f5ed847bdbf540b47e8fe1980dddfb5509ae7f9d/src_python/yaafelib/dataflow.py#L116-L128
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/templates/gr-newmod/docs/doxygen/other/doxypy.py
python
Doxypy.__docstringSummaryToBrief
(self, line)
Adds \\brief to the docstrings summary line. A \\brief is prepended, provided no other doxygen command is at the start of the line.
Adds \\brief to the docstrings summary line.
[ "Adds", "\\\\", "brief", "to", "the", "docstrings", "summary", "line", "." ]
def __docstringSummaryToBrief(self, line): """Adds \\brief to the docstrings summary line. A \\brief is prepended, provided no other doxygen command is at the start of the line. """ stripped = line.strip() if stripped and not stripped[0] in ('@', '\\'): return "\\brief " + line else: return line
[ "def", "__docstringSummaryToBrief", "(", "self", ",", "line", ")", ":", "stripped", "=", "line", ".", "strip", "(", ")", "if", "stripped", "and", "not", "stripped", "[", "0", "]", "in", "(", "'@'", ",", "'\\\\'", ")", ":", "return", "\"\\\\brief \"", "+", "line", "else", ":", "return", "line" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/other/doxypy.py#L227-L237
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
SaveFileSelector
(*args, **kwargs)
return _misc_.SaveFileSelector(*args, **kwargs)
SaveFileSelector(String what, String extension, String default_name=EmptyString, Window parent=None) -> String
SaveFileSelector(String what, String extension, String default_name=EmptyString, Window parent=None) -> String
[ "SaveFileSelector", "(", "String", "what", "String", "extension", "String", "default_name", "=", "EmptyString", "Window", "parent", "=", "None", ")", "-", ">", "String" ]
def SaveFileSelector(*args, **kwargs): """ SaveFileSelector(String what, String extension, String default_name=EmptyString, Window parent=None) -> String """ return _misc_.SaveFileSelector(*args, **kwargs)
[ "def", "SaveFileSelector", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "SaveFileSelector", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L439-L444
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PGProperty.GetMainParent
(*args, **kwargs)
return _propgrid.PGProperty_GetMainParent(*args, **kwargs)
GetMainParent(self) -> PGProperty
GetMainParent(self) -> PGProperty
[ "GetMainParent", "(", "self", ")", "-", ">", "PGProperty" ]
def GetMainParent(*args, **kwargs): """GetMainParent(self) -> PGProperty""" return _propgrid.PGProperty_GetMainParent(*args, **kwargs)
[ "def", "GetMainParent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_GetMainParent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L523-L525
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/cognito/identity/__init__.py
python
regions
()
return get_regions('cognito-identity', connection_cls=CognitoIdentityConnection)
Get all available regions for the Amazon Cognito Identity service. :rtype: list :return: A list of :class:`boto.regioninfo.RegionInfo`
Get all available regions for the Amazon Cognito Identity service.
[ "Get", "all", "available", "regions", "for", "the", "Amazon", "Cognito", "Identity", "service", "." ]
def regions(): """ Get all available regions for the Amazon Cognito Identity service. :rtype: list :return: A list of :class:`boto.regioninfo.RegionInfo` """ from boto.cognito.identity.layer1 import CognitoIdentityConnection return get_regions('cognito-identity', connection_cls=CognitoIdentityConnection)
[ "def", "regions", "(", ")", ":", "from", "boto", ".", "cognito", ".", "identity", ".", "layer1", "import", "CognitoIdentityConnection", "return", "get_regions", "(", "'cognito-identity'", ",", "connection_cls", "=", "CognitoIdentityConnection", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cognito/identity/__init__.py#L26-L35
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/module/module.py
python
Module._sync_params_from_devices
(self)
Synchronizes parameters from devices to CPU. This function should be called after calling `update` that updates the parameters on the devices, before one can read the latest parameters from ``self._arg_params`` and ``self._aux_params``. For row_sparse parameters on devices, ther are pulled from KVStore with all row ids.
Synchronizes parameters from devices to CPU. This function should be called after calling `update` that updates the parameters on the devices, before one can read the latest parameters from ``self._arg_params`` and ``self._aux_params``.
[ "Synchronizes", "parameters", "from", "devices", "to", "CPU", ".", "This", "function", "should", "be", "called", "after", "calling", "update", "that", "updates", "the", "parameters", "on", "the", "devices", "before", "one", "can", "read", "the", "latest", "parameters", "from", "self", ".", "_arg_params", "and", "self", ".", "_aux_params", "." ]
def _sync_params_from_devices(self): """Synchronizes parameters from devices to CPU. This function should be called after calling `update` that updates the parameters on the devices, before one can read the latest parameters from ``self._arg_params`` and ``self._aux_params``. For row_sparse parameters on devices, ther are pulled from KVStore with all row ids. """ self._exec_group.get_params(self._arg_params, self._aux_params) if self._kvstore and self._update_on_kvstore: for param_name, param_val in sorted(self._arg_params.items()): if param_val.stype == 'row_sparse': row_ids = nd.arange(0, param_val.shape[0], dtype='int64') self._kvstore.row_sparse_pull(param_name, param_val, row_ids=row_ids) self._params_dirty = False
[ "def", "_sync_params_from_devices", "(", "self", ")", ":", "self", ".", "_exec_group", ".", "get_params", "(", "self", ".", "_arg_params", ",", "self", ".", "_aux_params", ")", "if", "self", ".", "_kvstore", "and", "self", ".", "_update_on_kvstore", ":", "for", "param_name", ",", "param_val", "in", "sorted", "(", "self", ".", "_arg_params", ".", "items", "(", ")", ")", ":", "if", "param_val", ".", "stype", "==", "'row_sparse'", ":", "row_ids", "=", "nd", ".", "arange", "(", "0", ",", "param_val", ".", "shape", "[", "0", "]", ",", "dtype", "=", "'int64'", ")", "self", ".", "_kvstore", ".", "row_sparse_pull", "(", "param_name", ",", "param_val", ",", "row_ids", "=", "row_ids", ")", "self", ".", "_params_dirty", "=", "False" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/module/module.py#L777-L791
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/model.py
python
_update_params_on_kvstore
(param_arrays, grad_arrays, kvstore, param_names)
Perform update of param_arrays from grad_arrays on kvstore.
Perform update of param_arrays from grad_arrays on kvstore.
[ "Perform", "update", "of", "param_arrays", "from", "grad_arrays", "on", "kvstore", "." ]
def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue name = param_names[index] # push gradient, priority is negative index # pull back the weights if grad_list[0].stype == 'default' and arg_list[0].stype == 'default': kvstore.pushpull(name, grad_list, out=arg_list, priority=-index) else: kvstore.push(name, grad_list, priority=-index) kvstore.pull(name, out=arg_list, priority=-index)
[ "def", "_update_params_on_kvstore", "(", "param_arrays", ",", "grad_arrays", ",", "kvstore", ",", "param_names", ")", ":", "for", "index", ",", "pair", "in", "enumerate", "(", "zip", "(", "param_arrays", ",", "grad_arrays", ")", ")", ":", "arg_list", ",", "grad_list", "=", "pair", "if", "grad_list", "[", "0", "]", "is", "None", ":", "continue", "name", "=", "param_names", "[", "index", "]", "# push gradient, priority is negative index", "# pull back the weights", "if", "grad_list", "[", "0", "]", ".", "stype", "==", "'default'", "and", "arg_list", "[", "0", "]", ".", "stype", "==", "'default'", ":", "kvstore", ".", "pushpull", "(", "name", ",", "grad_list", ",", "out", "=", "arg_list", ",", "priority", "=", "-", "index", ")", "else", ":", "kvstore", ".", "push", "(", "name", ",", "grad_list", ",", "priority", "=", "-", "index", ")", "kvstore", ".", "pull", "(", "name", ",", "out", "=", "arg_list", ",", "priority", "=", "-", "index", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/model.py#L144-L157
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextCtrl.CalcScrolledPosition
(*args)
return _richtext.RichTextCtrl_CalcScrolledPosition(*args)
CalcScrolledPosition(self, Point pt) -> Point CalcScrolledPosition(int x, int y) -> (sx, sy) Translate between scrolled and unscrolled coordinates.
CalcScrolledPosition(self, Point pt) -> Point CalcScrolledPosition(int x, int y) -> (sx, sy)
[ "CalcScrolledPosition", "(", "self", "Point", "pt", ")", "-", ">", "Point", "CalcScrolledPosition", "(", "int", "x", "int", "y", ")", "-", ">", "(", "sx", "sy", ")" ]
def CalcScrolledPosition(*args): """ CalcScrolledPosition(self, Point pt) -> Point CalcScrolledPosition(int x, int y) -> (sx, sy) Translate between scrolled and unscrolled coordinates. """ return _richtext.RichTextCtrl_CalcScrolledPosition(*args)
[ "def", "CalcScrolledPosition", "(", "*", "args", ")", ":", "return", "_richtext", ".", "RichTextCtrl_CalcScrolledPosition", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L4180-L4187
Tencent/ncnn
6f824c57a1f8ee6dd3902fb13bef947cf4e6a73f
python/ncnn/utils/functional.py
python
nms
(boxes, scores, iou_threshold, top_k=-1, candidate_size=200)
return picked
Args: box_scores (N, 5): boxes in corner-form(x1, y1, x2, y2) and probabilities. iou_threshold: intersection over union threshold. top_k: keep top_k results. If k <= 0, keep all the results. candidate_size: only consider the candidates with the highest scores. Returns: picked: a list of indexes of the kept boxes
[]
def nms(boxes, scores, iou_threshold, top_k=-1, candidate_size=200): """ Args: box_scores (N, 5): boxes in corner-form(x1, y1, x2, y2) and probabilities. iou_threshold: intersection over union threshold. top_k: keep top_k results. If k <= 0, keep all the results. candidate_size: only consider the candidates with the highest scores. Returns: picked: a list of indexes of the kept boxes """ picked = [] indexes = np.argsort(scores) indexes = indexes[-candidate_size:] while len(indexes) > 0: current = indexes[-1] picked.append(current) if 0 < top_k == len(picked) or len(indexes) == 1: break current_box = boxes[current, :] indexes = indexes[:-1] rest_boxes = boxes[indexes, :] iou = iou_of( rest_boxes, np.expand_dims(current_box, axis=0), ) indexes = indexes[iou <= iou_threshold] return picked
[ "def", "nms", "(", "boxes", ",", "scores", ",", "iou_threshold", ",", "top_k", "=", "-", "1", ",", "candidate_size", "=", "200", ")", ":", "picked", "=", "[", "]", "indexes", "=", "np", ".", "argsort", "(", "scores", ")", "indexes", "=", "indexes", "[", "-", "candidate_size", ":", "]", "while", "len", "(", "indexes", ")", ">", "0", ":", "current", "=", "indexes", "[", "-", "1", "]", "picked", ".", "append", "(", "current", ")", "if", "0", "<", "top_k", "==", "len", "(", "picked", ")", "or", "len", "(", "indexes", ")", "==", "1", ":", "break", "current_box", "=", "boxes", "[", "current", ",", ":", "]", "indexes", "=", "indexes", "[", ":", "-", "1", "]", "rest_boxes", "=", "boxes", "[", "indexes", ",", ":", "]", "iou", "=", "iou_of", "(", "rest_boxes", ",", "np", ".", "expand_dims", "(", "current_box", ",", "axis", "=", "0", ")", ",", ")", "indexes", "=", "indexes", "[", "iou", "<=", "iou_threshold", "]", "return", "picked" ]
https://github.com/Tencent/ncnn/blob/6f824c57a1f8ee6dd3902fb13bef947cf4e6a73f/python/ncnn/utils/functional.py#L90-L120
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/nest/lib/hl_api_spatial.py
python
DumpLayerNodes
(layer, outname)
Write `node ID` and position data of `layer` to file. Write `node ID` and position data to `outname` file. For each node in `layer`, a line with the following information is written: :: node ID x-position y-position [z-position] If `layer` contains several `node IDs`, data for all nodes in `layer` will be written to a single file. Parameters ---------- layer : NodeCollection `NodeCollection` of spatially distributed node IDs outname : str Name of file to write to (existing files are overwritten) See also -------- DumpLayerConnections: Write connectivity information to file. GetPosition: Return the spatial locations of nodes. Notes ----- * If calling this function from a distributed simulation, this function will write to one file per MPI rank. * File names are formed by adding the MPI Rank into the file name before the file name suffix. * Each file stores data for nodes local to that file. Example ------- :: import nest # create a spatial population s_nodes = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid(shape=[5, 5])) # write layer node positions to file nest.DumpLayerNodes(s_nodes, 'positions.txt')
Write `node ID` and position data of `layer` to file.
[ "Write", "node", "ID", "and", "position", "data", "of", "layer", "to", "file", "." ]
def DumpLayerNodes(layer, outname): """ Write `node ID` and position data of `layer` to file. Write `node ID` and position data to `outname` file. For each node in `layer`, a line with the following information is written: :: node ID x-position y-position [z-position] If `layer` contains several `node IDs`, data for all nodes in `layer` will be written to a single file. Parameters ---------- layer : NodeCollection `NodeCollection` of spatially distributed node IDs outname : str Name of file to write to (existing files are overwritten) See also -------- DumpLayerConnections: Write connectivity information to file. GetPosition: Return the spatial locations of nodes. Notes ----- * If calling this function from a distributed simulation, this function will write to one file per MPI rank. * File names are formed by adding the MPI Rank into the file name before the file name suffix. * Each file stores data for nodes local to that file. Example ------- :: import nest # create a spatial population s_nodes = nest.Create('iaf_psc_alpha', positions=nest.spatial.grid(shape=[5, 5])) # write layer node positions to file nest.DumpLayerNodes(s_nodes, 'positions.txt') """ if not isinstance(layer, NodeCollection): raise TypeError("layer must be a NodeCollection") sli_func(""" (w) file exch DumpLayerNodes close """, layer, _rank_specific_filename(outname))
[ "def", "DumpLayerNodes", "(", "layer", ",", "outname", ")", ":", "if", "not", "isinstance", "(", "layer", ",", "NodeCollection", ")", ":", "raise", "TypeError", "(", "\"layer must be a NodeCollection\"", ")", "sli_func", "(", "\"\"\"\n (w) file exch DumpLayerNodes close\n \"\"\"", ",", "layer", ",", "_rank_specific_filename", "(", "outname", ")", ")" ]
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/lib/hl_api_spatial.py#L486-L538
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py
python
_count_monitors
(raw_file)
Returns the number of monitors and if they're at the start or end of the file
Returns the number of monitors and if they're at the start or end of the file
[ "Returns", "the", "number", "of", "monitors", "and", "if", "they", "re", "at", "the", "start", "or", "end", "of", "the", "file" ]
def _count_monitors(raw_file): """ Returns the number of monitors and if they're at the start or end of the file """ raw_file = mtd[raw_file] num_hist = raw_file.getNumberHistograms() mon_count = 1 spectrumInfo = raw_file.spectrumInfo() if spectrumInfo.isMonitor(0): # Monitors are at the start for i in range(1, num_hist): if spectrumInfo.isMonitor(i): mon_count += 1 else: break return mon_count, True else: # Monitors are at the end if not spectrumInfo.isMonitor(num_hist): #if it's not, we don't have any monitors! return 0, True for i in range(num_hist, 0, -1): if spectrumInfo.isMonitor(i): mon_count += 1 else: break return mon_count, False
[ "def", "_count_monitors", "(", "raw_file", ")", ":", "raw_file", "=", "mtd", "[", "raw_file", "]", "num_hist", "=", "raw_file", ".", "getNumberHistograms", "(", ")", "mon_count", "=", "1", "spectrumInfo", "=", "raw_file", ".", "spectrumInfo", "(", ")", "if", "spectrumInfo", ".", "isMonitor", "(", "0", ")", ":", "# Monitors are at the start", "for", "i", "in", "range", "(", "1", ",", "num_hist", ")", ":", "if", "spectrumInfo", ".", "isMonitor", "(", "i", ")", ":", "mon_count", "+=", "1", "else", ":", "break", "return", "mon_count", ",", "True", "else", ":", "# Monitors are at the end", "if", "not", "spectrumInfo", ".", "isMonitor", "(", "num_hist", ")", ":", "#if it's not, we don't have any monitors!", "return", "0", ",", "True", "for", "i", "in", "range", "(", "num_hist", ",", "0", ",", "-", "1", ")", ":", "if", "spectrumInfo", ".", "isMonitor", "(", "i", ")", ":", "mon_count", "+=", "1", "else", ":", "break", "return", "mon_count", ",", "False" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py#L15-L46
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/_version.py
python
run_command
(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None)
return stdout, p.returncode
Call the given command(s).
Call the given command(s).
[ "Call", "the", "given", "command", "(", "s", ")", "." ]
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode
[ "def", "run_command", "(", "commands", ",", "args", ",", "cwd", "=", "None", ",", "verbose", "=", "False", ",", "hide_stderr", "=", "False", ",", "env", "=", "None", ")", ":", "assert", "isinstance", "(", "commands", ",", "list", ")", "p", "=", "None", "for", "c", "in", "commands", ":", "try", ":", "dispcmd", "=", "str", "(", "[", "c", "]", "+", "args", ")", "# remember shell=False, so use git.cmd on windows, not just git", "p", "=", "subprocess", ".", "Popen", "(", "[", "c", "]", "+", "args", ",", "cwd", "=", "cwd", ",", "env", "=", "env", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "(", "subprocess", ".", "PIPE", "if", "hide_stderr", "else", "None", ")", ")", "break", "except", "EnvironmentError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "continue", "if", "verbose", ":", "print", "(", "\"unable to run %s\"", "%", "dispcmd", ")", "print", "(", "e", ")", "return", "None", ",", "None", "else", ":", "if", "verbose", ":", "print", "(", "\"unable to find command, tried %s\"", "%", "(", "commands", ",", ")", ")", "return", "None", ",", "None", "stdout", "=", "p", ".", "communicate", "(", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "stdout", "=", "stdout", ".", "decode", "(", ")", "if", "p", ".", "returncode", "!=", "0", ":", "if", "verbose", ":", "print", "(", "\"unable to run %s (error)\"", "%", "dispcmd", ")", "print", "(", "\"stdout was %s\"", "%", "stdout", ")", "return", "None", ",", "p", ".", "returncode", "return", "stdout", ",", "p", ".", "returncode" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/_version.py#L70-L104
google/flatbuffers
b3006913369e0a7550795e477011ac5bebb93497
python/flatbuffers/builder.py
python
Builder.assertStructIsInline
(self, obj)
Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere.
Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere.
[ "Structs", "are", "always", "stored", "inline", "so", "need", "to", "be", "created", "right", "where", "they", "are", "used", ".", "You", "ll", "get", "this", "error", "if", "you", "created", "it", "elsewhere", "." ]
def assertStructIsInline(self, obj): """ Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere. """ N.enforce_number(obj, N.UOffsetTFlags) if obj != self.Offset(): msg = ("flatbuffers: Tried to write a Struct at an Offset that " "is different from the current Offset of the Builder.") raise StructIsNotInlineError(msg)
[ "def", "assertStructIsInline", "(", "self", ",", "obj", ")", ":", "N", ".", "enforce_number", "(", "obj", ",", "N", ".", "UOffsetTFlags", ")", "if", "obj", "!=", "self", ".", "Offset", "(", ")", ":", "msg", "=", "(", "\"flatbuffers: Tried to write a Struct at an Offset that \"", "\"is different from the current Offset of the Builder.\"", ")", "raise", "StructIsNotInlineError", "(", "msg", ")" ]
https://github.com/google/flatbuffers/blob/b3006913369e0a7550795e477011ac5bebb93497/python/flatbuffers/builder.py#L495-L506
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.GetTextRange
(*args, **kwargs)
return _stc.StyledTextCtrl_GetTextRange(*args, **kwargs)
GetTextRange(self, int startPos, int endPos) -> String Retrieve a range of text.
GetTextRange(self, int startPos, int endPos) -> String
[ "GetTextRange", "(", "self", "int", "startPos", "int", "endPos", ")", "-", ">", "String" ]
def GetTextRange(*args, **kwargs): """ GetTextRange(self, int startPos, int endPos) -> String Retrieve a range of text. """ return _stc.StyledTextCtrl_GetTextRange(*args, **kwargs)
[ "def", "GetTextRange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetTextRange", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L3585-L3591
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Locale.GetLanguage
(*args, **kwargs)
return _gdi_.Locale_GetLanguage(*args, **kwargs)
GetLanguage(self) -> int
GetLanguage(self) -> int
[ "GetLanguage", "(", "self", ")", "-", ">", "int" ]
def GetLanguage(*args, **kwargs): """GetLanguage(self) -> int""" return _gdi_.Locale_GetLanguage(*args, **kwargs)
[ "def", "GetLanguage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Locale_GetLanguage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3021-L3023
ros-drivers/rosserial
c169ae2173dcfda7cee567d64beae45198459400
rosserial_python/src/rosserial_python/SerialClient.py
python
SerialClient.setupSubscriber
(self, data)
Register a new subscriber.
Register a new subscriber.
[ "Register", "a", "new", "subscriber", "." ]
def setupSubscriber(self, data): """ Register a new subscriber. """ try: msg = TopicInfo() msg.deserialize(data) if not msg.topic_name in list(self.subscribers.keys()): sub = Subscriber(msg, self) self.subscribers[msg.topic_name] = sub self.setSubscribeSize(msg.buffer_size) rospy.loginfo("Setup subscriber on %s [%s]" % (msg.topic_name, msg.message_type) ) elif msg.message_type != self.subscribers[msg.topic_name].message._type: old_message_type = self.subscribers[msg.topic_name].message._type self.subscribers[msg.topic_name].unregister() sub = Subscriber(msg, self) self.subscribers[msg.topic_name] = sub self.setSubscribeSize(msg.buffer_size) rospy.loginfo("Change the message type of subscriber on %s from [%s] to [%s]" % (msg.topic_name, old_message_type, msg.message_type) ) except Exception as e: rospy.logerr("Creation of subscriber failed: %s", e)
[ "def", "setupSubscriber", "(", "self", ",", "data", ")", ":", "try", ":", "msg", "=", "TopicInfo", "(", ")", "msg", ".", "deserialize", "(", "data", ")", "if", "not", "msg", ".", "topic_name", "in", "list", "(", "self", ".", "subscribers", ".", "keys", "(", ")", ")", ":", "sub", "=", "Subscriber", "(", "msg", ",", "self", ")", "self", ".", "subscribers", "[", "msg", ".", "topic_name", "]", "=", "sub", "self", ".", "setSubscribeSize", "(", "msg", ".", "buffer_size", ")", "rospy", ".", "loginfo", "(", "\"Setup subscriber on %s [%s]\"", "%", "(", "msg", ".", "topic_name", ",", "msg", ".", "message_type", ")", ")", "elif", "msg", ".", "message_type", "!=", "self", ".", "subscribers", "[", "msg", ".", "topic_name", "]", ".", "message", ".", "_type", ":", "old_message_type", "=", "self", ".", "subscribers", "[", "msg", ".", "topic_name", "]", ".", "message", ".", "_type", "self", ".", "subscribers", "[", "msg", ".", "topic_name", "]", ".", "unregister", "(", ")", "sub", "=", "Subscriber", "(", "msg", ",", "self", ")", "self", ".", "subscribers", "[", "msg", ".", "topic_name", "]", "=", "sub", "self", ".", "setSubscribeSize", "(", "msg", ".", "buffer_size", ")", "rospy", ".", "loginfo", "(", "\"Change the message type of subscriber on %s from [%s] to [%s]\"", "%", "(", "msg", ".", "topic_name", ",", "old_message_type", ",", "msg", ".", "message_type", ")", ")", "except", "Exception", "as", "e", ":", "rospy", ".", "logerr", "(", "\"Creation of subscriber failed: %s\"", ",", "e", ")" ]
https://github.com/ros-drivers/rosserial/blob/c169ae2173dcfda7cee567d64beae45198459400/rosserial_python/src/rosserial_python/SerialClient.py#L582-L600
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/core.py
python
publish_parts
(source, source_path=None, source_class=io.StringInput, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=False)
return pub.writer.parts
Set up & run a `Publisher`, and return a dictionary of document parts. Dictionary keys are the names of parts, and values are Unicode strings; encoding is up to the client. For programmatic use with string I/O. For encoded string input, be sure to set the 'input_encoding' setting to the desired encoding. Set it to 'unicode' for unencoded Unicode string input. Here's how:: publish_parts(..., settings_overrides={'input_encoding': 'unicode'}) Parameters: see `publish_programmatically`.
Set up & run a `Publisher`, and return a dictionary of document parts. Dictionary keys are the names of parts, and values are Unicode strings; encoding is up to the client. For programmatic use with string I/O.
[ "Set", "up", "&", "run", "a", "Publisher", "and", "return", "a", "dictionary", "of", "document", "parts", ".", "Dictionary", "keys", "are", "the", "names", "of", "parts", "and", "values", "are", "Unicode", "strings", ";", "encoding", "is", "up", "to", "the", "client", ".", "For", "programmatic", "use", "with", "string", "I", "/", "O", "." ]
def publish_parts(source, source_path=None, source_class=io.StringInput, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=False): """ Set up & run a `Publisher`, and return a dictionary of document parts. Dictionary keys are the names of parts, and values are Unicode strings; encoding is up to the client. For programmatic use with string I/O. For encoded string input, be sure to set the 'input_encoding' setting to the desired encoding. Set it to 'unicode' for unencoded Unicode string input. Here's how:: publish_parts(..., settings_overrides={'input_encoding': 'unicode'}) Parameters: see `publish_programmatically`. """ output, pub = publish_programmatically( source=source, source_path=source_path, source_class=source_class, destination_class=io.StringOutput, destination=None, destination_path=destination_path, reader=reader, reader_name=reader_name, parser=parser, parser_name=parser_name, writer=writer, writer_name=writer_name, settings=settings, settings_spec=settings_spec, settings_overrides=settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return pub.writer.parts
[ "def", "publish_parts", "(", "source", ",", "source_path", "=", "None", ",", "source_class", "=", "io", ".", "StringInput", ",", "destination_path", "=", "None", ",", "reader", "=", "None", ",", "reader_name", "=", "'standalone'", ",", "parser", "=", "None", ",", "parser_name", "=", "'restructuredtext'", ",", "writer", "=", "None", ",", "writer_name", "=", "'pseudoxml'", ",", "settings", "=", "None", ",", "settings_spec", "=", "None", ",", "settings_overrides", "=", "None", ",", "config_section", "=", "None", ",", "enable_exit_status", "=", "False", ")", ":", "output", ",", "pub", "=", "publish_programmatically", "(", "source", "=", "source", ",", "source_path", "=", "source_path", ",", "source_class", "=", "source_class", ",", "destination_class", "=", "io", ".", "StringOutput", ",", "destination", "=", "None", ",", "destination_path", "=", "destination_path", ",", "reader", "=", "reader", ",", "reader_name", "=", "reader_name", ",", "parser", "=", "parser", ",", "parser_name", "=", "parser_name", ",", "writer", "=", "writer", ",", "writer_name", "=", "writer_name", ",", "settings", "=", "settings", ",", "settings_spec", "=", "settings_spec", ",", "settings_overrides", "=", "settings_overrides", ",", "config_section", "=", "config_section", ",", "enable_exit_status", "=", "enable_exit_status", ")", "return", "pub", ".", "writer", ".", "parts" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/core.py#L419-L451
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
Solver.help
(self)
Display a string describing all available options.
Display a string describing all available options.
[ "Display", "a", "string", "describing", "all", "available", "options", "." ]
def help(self): """Display a string describing all available options.""" print(Z3_solver_get_help(self.ctx.ref(), self.solver))
[ "def", "help", "(", "self", ")", ":", "print", "(", "Z3_solver_get_help", "(", "self", ".", "ctx", ".", "ref", "(", ")", ",", "self", ".", "solver", ")", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L7246-L7248
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/framework/ops.py
python
SparseTensor.shape
(self)
return self._shape
A 1-D Tensor of int64 representing the shape of the dense tensor.
A 1-D Tensor of int64 representing the shape of the dense tensor.
[ "A", "1", "-", "D", "Tensor", "of", "int64", "representing", "the", "shape", "of", "the", "dense", "tensor", "." ]
def shape(self): """A 1-D Tensor of int64 representing the shape of the dense tensor.""" return self._shape
[ "def", "shape", "(", "self", ")", ":", "return", "self", ".", "_shape" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/ops.py#L1026-L1028
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
ComboBox.__init__
(self, *args, **kwargs)
__init__(Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, List choices=EmptyList, long style=0, Validator validator=DefaultValidator, String name=ComboBoxNameStr) -> ComboBox Constructor, creates and shows a ComboBox control.
__init__(Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, List choices=EmptyList, long style=0, Validator validator=DefaultValidator, String name=ComboBoxNameStr) -> ComboBox
[ "__init__", "(", "Window", "parent", "int", "id", "=", "-", "1", "String", "value", "=", "EmptyString", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "List", "choices", "=", "EmptyList", "long", "style", "=", "0", "Validator", "validator", "=", "DefaultValidator", "String", "name", "=", "ComboBoxNameStr", ")", "-", ">", "ComboBox" ]
def __init__(self, *args, **kwargs): """ __init__(Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, List choices=EmptyList, long style=0, Validator validator=DefaultValidator, String name=ComboBoxNameStr) -> ComboBox Constructor, creates and shows a ComboBox control. """ _controls_.ComboBox_swiginit(self,_controls_.new_ComboBox(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "ComboBox_swiginit", "(", "self", ",", "_controls_", ".", "new_ComboBox", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L588-L598
zachriggle/ida-splode
a4aee3be415b318a0e051a523ebd0a8d6d5e0026
py/idasplode/color.py
python
ColorHit
(IP, Count=-1)
Color a single instruction
Color a single instruction
[ "Color", "a", "single", "instruction" ]
def ColorHit(IP, Count=-1): """Color a single instruction""" Hit = query.GetHitInstructions({'IP':IP}) Enhanced = query.GetEnhancedInstructions({'IP':IP}) if Enhanced: SetColor(IP, settings.COLOR_INS_ENHANCED) elif Hit: SetColor(IP, settings.COLOR_INS_EXECUTED) else: SetColor(IP, settings.COLOR_INS_RESET)
[ "def", "ColorHit", "(", "IP", ",", "Count", "=", "-", "1", ")", ":", "Hit", "=", "query", ".", "GetHitInstructions", "(", "{", "'IP'", ":", "IP", "}", ")", "Enhanced", "=", "query", ".", "GetEnhancedInstructions", "(", "{", "'IP'", ":", "IP", "}", ")", "if", "Enhanced", ":", "SetColor", "(", "IP", ",", "settings", ".", "COLOR_INS_ENHANCED", ")", "elif", "Hit", ":", "SetColor", "(", "IP", ",", "settings", ".", "COLOR_INS_EXECUTED", ")", "else", ":", "SetColor", "(", "IP", ",", "settings", ".", "COLOR_INS_RESET", ")" ]
https://github.com/zachriggle/ida-splode/blob/a4aee3be415b318a0e051a523ebd0a8d6d5e0026/py/idasplode/color.py#L22-L29
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/aicpu/topk.py
python
_top_k_aicpu
()
return
TopK aicpu register
TopK aicpu register
[ "TopK", "aicpu", "register" ]
def _top_k_aicpu(): """TopK aicpu register""" return
[ "def", "_top_k_aicpu", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/aicpu/topk.py#L32-L34
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/compiler/pycodegen.py
python
findOp
(node)
return v.op
Find the op (DELETE, LOAD, STORE) in an AssTuple tree
Find the op (DELETE, LOAD, STORE) in an AssTuple tree
[ "Find", "the", "op", "(", "DELETE", "LOAD", "STORE", ")", "in", "an", "AssTuple", "tree" ]
def findOp(node): """Find the op (DELETE, LOAD, STORE) in an AssTuple tree""" v = OpFinder() walk(node, v, verbose=0) return v.op
[ "def", "findOp", "(", "node", ")", ":", "v", "=", "OpFinder", "(", ")", "walk", "(", "node", ",", "v", ",", "verbose", "=", "0", ")", "return", "v", ".", "op" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/compiler/pycodegen.py#L1497-L1501
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/template.py
python
Template.global_variables
(self)
Returns the list of global variables created by the Template.
Returns the list of global variables created by the Template.
[ "Returns", "the", "list", "of", "global", "variables", "created", "by", "the", "Template", "." ]
def global_variables(self): """Returns the list of global variables created by the Template.""" if self._variables_created: return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, self.variable_scope_name) else: return []
[ "def", "global_variables", "(", "self", ")", ":", "if", "self", ".", "_variables_created", ":", "return", "ops", ".", "get_collection", "(", "ops", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ",", "self", ".", "variable_scope_name", ")", "else", ":", "return", "[", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/template.py#L305-L311
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
onnxruntime/python/tools/quantization/quantize.py
python
optimize_model
(model_path: Path)
return optimized_model
Generate model that applies graph optimization (constant folding,etc.) parameter model_path: path to the original onnx model return: optimized onnx model
Generate model that applies graph optimization (constant folding,etc.) parameter model_path: path to the original onnx model return: optimized onnx model
[ "Generate", "model", "that", "applies", "graph", "optimization", "(", "constant", "folding", "etc", ".", ")", "parameter", "model_path", ":", "path", "to", "the", "original", "onnx", "model", "return", ":", "optimized", "onnx", "model" ]
def optimize_model(model_path: Path): ''' Generate model that applies graph optimization (constant folding,etc.) parameter model_path: path to the original onnx model return: optimized onnx model ''' opt_model_path = generate_identified_filename(model_path, "-opt") sess_option = SessionOptions() sess_option.optimized_model_filepath = opt_model_path.as_posix() sess_option.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_BASIC _ = InferenceSession(model_path.as_posix(), sess_option, providers=['CPUExecutionProvider']) optimized_model = onnx.load(opt_model_path.as_posix()) return optimized_model
[ "def", "optimize_model", "(", "model_path", ":", "Path", ")", ":", "opt_model_path", "=", "generate_identified_filename", "(", "model_path", ",", "\"-opt\"", ")", "sess_option", "=", "SessionOptions", "(", ")", "sess_option", ".", "optimized_model_filepath", "=", "opt_model_path", ".", "as_posix", "(", ")", "sess_option", ".", "graph_optimization_level", "=", "GraphOptimizationLevel", ".", "ORT_ENABLE_BASIC", "_", "=", "InferenceSession", "(", "model_path", ".", "as_posix", "(", ")", ",", "sess_option", ",", "providers", "=", "[", "'CPUExecutionProvider'", "]", ")", "optimized_model", "=", "onnx", ".", "load", "(", "opt_model_path", ".", "as_posix", "(", ")", ")", "return", "optimized_model" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/quantization/quantize.py#L30-L42
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
RegionFromBitmapColour
(*args, **kwargs)
return val
RegionFromBitmapColour(Bitmap bmp, Colour transColour, int tolerance=0) -> Region
RegionFromBitmapColour(Bitmap bmp, Colour transColour, int tolerance=0) -> Region
[ "RegionFromBitmapColour", "(", "Bitmap", "bmp", "Colour", "transColour", "int", "tolerance", "=", "0", ")", "-", ">", "Region" ]
def RegionFromBitmapColour(*args, **kwargs): """RegionFromBitmapColour(Bitmap bmp, Colour transColour, int tolerance=0) -> Region""" val = _gdi_.new_RegionFromBitmapColour(*args, **kwargs) return val
[ "def", "RegionFromBitmapColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_gdi_", ".", "new_RegionFromBitmapColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L1659-L1662
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py
python
MaildirMessage.__init__
(self, message=None)
Initialize a MaildirMessage instance.
Initialize a MaildirMessage instance.
[ "Initialize", "a", "MaildirMessage", "instance", "." ]
def __init__(self, message=None): """Initialize a MaildirMessage instance.""" self._subdir = 'new' self._info = '' self._date = time.time() Message.__init__(self, message)
[ "def", "__init__", "(", "self", ",", "message", "=", "None", ")", ":", "self", ".", "_subdir", "=", "'new'", "self", ".", "_info", "=", "''", "self", ".", "_date", "=", "time", ".", "time", "(", ")", "Message", ".", "__init__", "(", "self", ",", "message", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L1474-L1479
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py
python
Checker.report_invalid_syntax
(self)
Check if the syntax is valid.
Check if the syntax is valid.
[ "Check", "if", "the", "syntax", "is", "valid", "." ]
def report_invalid_syntax(self): """Check if the syntax is valid.""" (exc_type, exc) = sys.exc_info()[:2] if len(exc.args) > 1: offset = exc.args[1] if len(offset) > 2: offset = offset[1:3] else: offset = (1, 0) self.report_error(offset[0], offset[1] or 0, 'E901 %s: %s' % (exc_type.__name__, exc.args[0]), self.report_invalid_syntax)
[ "def", "report_invalid_syntax", "(", "self", ")", ":", "(", "exc_type", ",", "exc", ")", "=", "sys", ".", "exc_info", "(", ")", "[", ":", "2", "]", "if", "len", "(", "exc", ".", "args", ")", ">", "1", ":", "offset", "=", "exc", ".", "args", "[", "1", "]", "if", "len", "(", "offset", ")", ">", "2", ":", "offset", "=", "offset", "[", "1", ":", "3", "]", "else", ":", "offset", "=", "(", "1", ",", "0", ")", "self", ".", "report_error", "(", "offset", "[", "0", "]", ",", "offset", "[", "1", "]", "or", "0", ",", "'E901 %s: %s'", "%", "(", "exc_type", ".", "__name__", ",", "exc", ".", "args", "[", "0", "]", ")", ",", "self", ".", "report_invalid_syntax", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py#L1250-L1261
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/random.py
python
Random.randint
(self, a, b)
return self.randrange(a, b+1)
Return random integer in range [a, b], including both end points.
Return random integer in range [a, b], including both end points.
[ "Return", "random", "integer", "in", "range", "[", "a", "b", "]", "including", "both", "end", "points", "." ]
def randint(self, a, b): """Return random integer in range [a, b], including both end points. """ return self.randrange(a, b+1)
[ "def", "randint", "(", "self", ",", "a", ",", "b", ")", ":", "return", "self", ".", "randrange", "(", "a", ",", "b", "+", "1", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/random.py#L237-L241
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/_multivariate.py
python
invwishart_gen.var
(self, df, scale)
return _squeeze_output(out) if out is not None else out
Variance of the inverse Wishart distribution Only valid if the degrees of freedom are greater than the dimension of the scale matrix plus three. Parameters ---------- %(_doc_default_callparams)s Returns ------- var : float The variance of the distribution
Variance of the inverse Wishart distribution
[ "Variance", "of", "the", "inverse", "Wishart", "distribution" ]
def var(self, df, scale): """ Variance of the inverse Wishart distribution Only valid if the degrees of freedom are greater than the dimension of the scale matrix plus three. Parameters ---------- %(_doc_default_callparams)s Returns ------- var : float The variance of the distribution """ dim, df, scale = self._process_parameters(df, scale) out = self._var(dim, df, scale) return _squeeze_output(out) if out is not None else out
[ "def", "var", "(", "self", ",", "df", ",", "scale", ")", ":", "dim", ",", "df", ",", "scale", "=", "self", ".", "_process_parameters", "(", "df", ",", "scale", ")", "out", "=", "self", ".", "_var", "(", "dim", ",", "df", ",", "scale", ")", "return", "_squeeze_output", "(", "out", ")", "if", "out", "is", "not", "None", "else", "out" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_multivariate.py#L2666-L2684
magazino/move_base_flex
a8ca484e354a0196b5e9fbda5f0eae311d9b72d3
git-clang-format.py
python
temporary_index_file
(tree=None)
Context manager for setting GIT_INDEX_FILE to a temporary file and deleting the file afterward.
Context manager for setting GIT_INDEX_FILE to a temporary file and deleting the file afterward.
[ "Context", "manager", "for", "setting", "GIT_INDEX_FILE", "to", "a", "temporary", "file", "and", "deleting", "the", "file", "afterward", "." ]
def temporary_index_file(tree=None): """Context manager for setting GIT_INDEX_FILE to a temporary file and deleting the file afterward.""" index_path = create_temporary_index(tree) old_index_path = os.environ.get('GIT_INDEX_FILE') os.environ['GIT_INDEX_FILE'] = index_path try: yield finally: if old_index_path is None: del os.environ['GIT_INDEX_FILE'] else: os.environ['GIT_INDEX_FILE'] = old_index_path os.remove(index_path)
[ "def", "temporary_index_file", "(", "tree", "=", "None", ")", ":", "index_path", "=", "create_temporary_index", "(", "tree", ")", "old_index_path", "=", "os", ".", "environ", ".", "get", "(", "'GIT_INDEX_FILE'", ")", "os", ".", "environ", "[", "'GIT_INDEX_FILE'", "]", "=", "index_path", "try", ":", "yield", "finally", ":", "if", "old_index_path", "is", "None", ":", "del", "os", ".", "environ", "[", "'GIT_INDEX_FILE'", "]", "else", ":", "os", ".", "environ", "[", "'GIT_INDEX_FILE'", "]", "=", "old_index_path", "os", ".", "remove", "(", "index_path", ")" ]
https://github.com/magazino/move_base_flex/blob/a8ca484e354a0196b5e9fbda5f0eae311d9b72d3/git-clang-format.py#L451-L464
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
IsErrorSuppressedByNolint
(category, linenum)
return (_global_error_suppressions.get(category, False) or linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment or global suppression.
Returns true if the specified error category is suppressed on this line.
[ "Returns", "true", "if", "the", "specified", "error", "category", "is", "suppressed", "on", "this", "line", "." ]
def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment or global suppression. """ return (_global_error_suppressions.get(category, False) or linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
[ "def", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "(", "_global_error_suppressions", ".", "get", "(", "category", ",", "False", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "category", ",", "set", "(", ")", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "None", ",", "set", "(", ")", ")", ")" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L639-L654
rootm0s/Protectors
5b3f4d11687a5955caf9c3af30666c4bfc2c19ab
OWASP-ZSC/module/readline_windows/pyreadline/lineeditor/history.py
python
LineHistory.write_history_file
(self, filename=None)
Save a readline history file.
Save a readline history file.
[ "Save", "a", "readline", "history", "file", "." ]
def write_history_file(self, filename=None): '''Save a readline history file.''' if filename is None: filename = self.history_filename fp = open(filename, 'wb') for line in self.history[-self.history_length:]: fp.write(ensure_str(line.get_line_text())) fp.write('\n'.encode('ascii')) fp.close()
[ "def", "write_history_file", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "history_filename", "fp", "=", "open", "(", "filename", ",", "'wb'", ")", "for", "line", "in", "self", ".", "history", "[", "-", "self", ".", "history_length", ":", "]", ":", "fp", ".", "write", "(", "ensure_str", "(", "line", ".", "get_line_text", "(", ")", ")", ")", "fp", ".", "write", "(", "'\\n'", ".", "encode", "(", "'ascii'", ")", ")", "fp", ".", "close", "(", ")" ]
https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/lineeditor/history.py#L94-L102
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/sysconfig.py
python
get_platform
()
return "%s-%s-%s" % (osname, release, machine)
Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; on Linux, the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'.
Return a string that identifies the current platform.
[ "Return", "a", "string", "that", "identifies", "the", "current", "platform", "." ]
def get_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; on Linux, the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'. """ if os.name == 'nt': if 'amd64' in sys.version.lower(): return 'win-amd64' return sys.platform if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha return sys.platform # Set for cross builds explicitly if "_PYTHON_HOST_PLATFORM" in os.environ: return os.environ["_PYTHON_HOST_PLATFORM"] # Try to distinguish various flavours of Unix osname, host, release, version, machine = os.uname() # Convert the OS name to lowercase, remove '/' characters, and translate # spaces (for "Power Macintosh") osname = osname.lower().replace('/', '') machine = machine.replace(' ', '_') machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # We can't use "platform.architecture()[0]" because a # bootstrap problem. We use a dict to get an error # if some suspicious happens. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} machine += ".%s" % bitness[sys.maxsize] # fall through to standard osname-release-machine representation elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" import re rel_re = re.compile(r'[\d.]+') m = rel_re.match(release) if m: release = m.group() elif osname[:6] == "darwin": import _osx_support osname, release, machine = _osx_support.get_platform_osx( get_config_vars(), osname, release, machine) return "%s-%s-%s" % (osname, release, machine)
[ "def", "get_platform", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "if", "'amd64'", "in", "sys", ".", "version", ".", "lower", "(", ")", ":", "return", "'win-amd64'", "return", "sys", ".", "platform", "if", "os", ".", "name", "!=", "\"posix\"", "or", "not", "hasattr", "(", "os", ",", "'uname'", ")", ":", "# XXX what about the architecture? NT is Intel or Alpha", "return", "sys", ".", "platform", "# Set for cross builds explicitly", "if", "\"_PYTHON_HOST_PLATFORM\"", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "\"_PYTHON_HOST_PLATFORM\"", "]", "# Try to distinguish various flavours of Unix", "osname", ",", "host", ",", "release", ",", "version", ",", "machine", "=", "os", ".", "uname", "(", ")", "# Convert the OS name to lowercase, remove '/' characters, and translate", "# spaces (for \"Power Macintosh\")", "osname", "=", "osname", ".", "lower", "(", ")", ".", "replace", "(", "'/'", ",", "''", ")", "machine", "=", "machine", ".", "replace", "(", "' '", ",", "'_'", ")", "machine", "=", "machine", ".", "replace", "(", "'/'", ",", "'-'", ")", "if", "osname", "[", ":", "5", "]", "==", "\"linux\"", ":", "# At least on Linux/Intel, 'machine' is the processor --", "# i386, etc.", "# XXX what about Alpha, SPARC, etc?", "return", "\"%s-%s\"", "%", "(", "osname", ",", "machine", ")", "elif", "osname", "[", ":", "5", "]", "==", "\"sunos\"", ":", "if", "release", "[", "0", "]", ">=", "\"5\"", ":", "# SunOS 5 == Solaris 2", "osname", "=", "\"solaris\"", "release", "=", "\"%d.%s\"", "%", "(", "int", "(", "release", "[", "0", "]", ")", "-", "3", ",", "release", "[", "2", ":", "]", ")", "# We can't use \"platform.architecture()[0]\" because a", "# bootstrap problem. We use a dict to get an error", "# if some suspicious happens.", "bitness", "=", "{", "2147483647", ":", "\"32bit\"", ",", "9223372036854775807", ":", "\"64bit\"", "}", "machine", "+=", "\".%s\"", "%", "bitness", "[", "sys", ".", "maxsize", "]", "# fall through to standard osname-release-machine representation", "elif", "osname", "[", ":", "3", "]", "==", "\"aix\"", ":", "return", "\"%s-%s.%s\"", "%", "(", "osname", ",", "version", ",", "release", ")", "elif", "osname", "[", ":", "6", "]", "==", "\"cygwin\"", ":", "osname", "=", "\"cygwin\"", "import", "re", "rel_re", "=", "re", ".", "compile", "(", "r'[\\d.]+'", ")", "m", "=", "rel_re", ".", "match", "(", "release", ")", "if", "m", ":", "release", "=", "m", ".", "group", "(", ")", "elif", "osname", "[", ":", "6", "]", "==", "\"darwin\"", ":", "import", "_osx_support", "osname", ",", "release", ",", "machine", "=", "_osx_support", ".", "get_platform_osx", "(", "get_config_vars", "(", ")", ",", "osname", ",", "release", ",", "machine", ")", "return", "\"%s-%s-%s\"", "%", "(", "osname", ",", "release", ",", "machine", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/sysconfig.py#L605-L678
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pluggy/py2/pluggy/manager.py
python
PluginManager.enable_tracing
(self)
return self.add_hookcall_monitoring(before, after)
enable tracing of hook calls and return an undo function.
enable tracing of hook calls and return an undo function.
[ "enable", "tracing", "of", "hook", "calls", "and", "return", "an", "undo", "function", "." ]
def enable_tracing(self): """ enable tracing of hook calls and return an undo function. """ hooktrace = self.trace.root.get("hook") def before(hook_name, methods, kwargs): hooktrace.root.indent += 1 hooktrace(hook_name, kwargs) def after(outcome, hook_name, methods, kwargs): if outcome.excinfo is None: hooktrace("finish", hook_name, "-->", outcome.get_result()) hooktrace.root.indent -= 1 return self.add_hookcall_monitoring(before, after)
[ "def", "enable_tracing", "(", "self", ")", ":", "hooktrace", "=", "self", ".", "trace", ".", "root", ".", "get", "(", "\"hook\"", ")", "def", "before", "(", "hook_name", ",", "methods", ",", "kwargs", ")", ":", "hooktrace", ".", "root", ".", "indent", "+=", "1", "hooktrace", "(", "hook_name", ",", "kwargs", ")", "def", "after", "(", "outcome", ",", "hook_name", ",", "methods", ",", "kwargs", ")", ":", "if", "outcome", ".", "excinfo", "is", "None", ":", "hooktrace", "(", "\"finish\"", ",", "hook_name", ",", "\"-->\"", ",", "outcome", ".", "get_result", "(", ")", ")", "hooktrace", ".", "root", ".", "indent", "-=", "1", "return", "self", ".", "add_hookcall_monitoring", "(", "before", ",", "after", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pluggy/py2/pluggy/manager.py#L346-L359
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
GeneralizedIKSolver.setTolerance
(self, res)
return _robotsim.GeneralizedIKSolver_setTolerance(self, res)
setTolerance(GeneralizedIKSolver self, double res) Sets the constraint solve tolerance (default 1e-3)
setTolerance(GeneralizedIKSolver self, double res)
[ "setTolerance", "(", "GeneralizedIKSolver", "self", "double", "res", ")" ]
def setTolerance(self, res): """ setTolerance(GeneralizedIKSolver self, double res) Sets the constraint solve tolerance (default 1e-3) """ return _robotsim.GeneralizedIKSolver_setTolerance(self, res)
[ "def", "setTolerance", "(", "self", ",", "res", ")", ":", "return", "_robotsim", ".", "GeneralizedIKSolver_setTolerance", "(", "self", ",", "res", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L7037-L7046
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/typeannotation.py
python
TypeAnnotation.IterIdentifiers
(self)
Iterates over all identifiers in this type and its subtypes.
Iterates over all identifiers in this type and its subtypes.
[ "Iterates", "over", "all", "identifiers", "in", "this", "type", "and", "its", "subtypes", "." ]
def IterIdentifiers(self): """Iterates over all identifiers in this type and its subtypes.""" if self.identifier: yield self.identifier for subtype in self.IterTypes(): for identifier in subtype.IterIdentifiers(): yield identifier
[ "def", "IterIdentifiers", "(", "self", ")", ":", "if", "self", ".", "identifier", ":", "yield", "self", ".", "identifier", "for", "subtype", "in", "self", ".", "IterTypes", "(", ")", ":", "for", "identifier", "in", "subtype", ".", "IterIdentifiers", "(", ")", ":", "yield", "identifier" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/typeannotation.py#L154-L160
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
trace
(a, offset=0, axis1=0, axis2=1, out=None)
return _mx_nd_np.trace(a, offset, axis1, axis2, out)
Return the sum along diagonals of the array. If `a` is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i. If `a` has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of `a` with `axis1` and `axis2` removed. Parameters ---------- a : ndarray Input array, from which the diagonals are taken. offset : int, optional Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0. axis1, axis2 : int, optional Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of `a`. out : ndarray, optional Array into which the output is placed. It must be of the right shape and right type to hold the output. Returns ------- sum_along_diagonals : ndarray If `a` is 2-D, the sum along the diagonal is returned. If `a` has larger dimensions, then an array of sums along diagonals is returned. Examples -------- >>> a = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> np.trace(a) array(3.) >>> a = np.arange(8).reshape((2, 2, 2)) >>> np.trace(a) array([6., 8.]) >>> a = np.arange(24).reshape((2, 2, 2, 3)) >>> np.trace(a).shape (2, 3)
Return the sum along diagonals of the array. If `a` is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i. If `a` has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of `a` with `axis1` and `axis2` removed.
[ "Return", "the", "sum", "along", "diagonals", "of", "the", "array", ".", "If", "a", "is", "2", "-", "D", "the", "sum", "along", "its", "diagonal", "with", "the", "given", "offset", "is", "returned", "i", ".", "e", ".", "the", "sum", "of", "elements", "a", "[", "i", "i", "+", "offset", "]", "for", "all", "i", ".", "If", "a", "has", "more", "than", "two", "dimensions", "then", "the", "axes", "specified", "by", "axis1", "and", "axis2", "are", "used", "to", "determine", "the", "2", "-", "D", "sub", "-", "arrays", "whose", "traces", "are", "returned", ".", "The", "shape", "of", "the", "resulting", "array", "is", "the", "same", "as", "that", "of", "a", "with", "axis1", "and", "axis2", "removed", "." ]
def trace(a, offset=0, axis1=0, axis2=1, out=None): """ Return the sum along diagonals of the array. If `a` is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i. If `a` has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of `a` with `axis1` and `axis2` removed. Parameters ---------- a : ndarray Input array, from which the diagonals are taken. offset : int, optional Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0. axis1, axis2 : int, optional Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of `a`. out : ndarray, optional Array into which the output is placed. It must be of the right shape and right type to hold the output. Returns ------- sum_along_diagonals : ndarray If `a` is 2-D, the sum along the diagonal is returned. If `a` has larger dimensions, then an array of sums along diagonals is returned. Examples -------- >>> a = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> np.trace(a) array(3.) >>> a = np.arange(8).reshape((2, 2, 2)) >>> np.trace(a) array([6., 8.]) >>> a = np.arange(24).reshape((2, 2, 2, 3)) >>> np.trace(a).shape (2, 3) """ return _mx_nd_np.trace(a, offset, axis1, axis2, out)
[ "def", "trace", "(", "a", ",", "offset", "=", "0", ",", "axis1", "=", "0", ",", "axis2", "=", "1", ",", "out", "=", "None", ")", ":", "return", "_mx_nd_np", ".", "trace", "(", "a", ",", "offset", ",", "axis1", ",", "axis2", ",", "out", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L6544-L6587
ArmageddonGames/ZeldaClassic
c244ae6c1d361d24a5529b1c0394e656f1f5d965
allegro/demos/skater/blender/ademo_export.py
python
upper
(i1, i2)
return v
Given two vertex ids, determine if the edge is an upper face.
Given two vertex ids, determine if the edge is an upper face.
[ "Given", "two", "vertex", "ids", "determine", "if", "the", "edge", "is", "an", "upper", "face", "." ]
def upper(i1, i2): """ Given two vertex ids, determine if the edge is an upper face. """ v = V[i2][0] - V[i1][0] return v
[ "def", "upper", "(", "i1", ",", "i2", ")", ":", "v", "=", "V", "[", "i2", "]", "[", "0", "]", "-", "V", "[", "i1", "]", "[", "0", "]", "return", "v" ]
https://github.com/ArmageddonGames/ZeldaClassic/blob/c244ae6c1d361d24a5529b1c0394e656f1f5d965/allegro/demos/skater/blender/ademo_export.py#L143-L148
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
ListCtrl.Create
(*args, **kwargs)
return _controls_.ListCtrl_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LC_ICON, Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool Do the 2nd phase and create the GUI control.
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LC_ICON, Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "LC_ICON", "Validator", "validator", "=", "DefaultValidator", "String", "name", "=", "ListCtrlNameStr", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LC_ICON, Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool Do the 2nd phase and create the GUI control. """ return _controls_.ListCtrl_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4452-L4460
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/difflib.py
python
restore
(delta, which)
r""" Generate one of the two sequences that generated a delta. Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract lines originating from file 1 or 2 (parameter `which`), stripping off line prefixes. Examples: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> diff = list(diff) >>> print ''.join(restore(diff, 1)), one two three >>> print ''.join(restore(diff, 2)), ore tree emu
r""" Generate one of the two sequences that generated a delta.
[ "r", "Generate", "one", "of", "the", "two", "sequences", "that", "generated", "a", "delta", "." ]
def restore(delta, which): r""" Generate one of the two sequences that generated a delta. Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract lines originating from file 1 or 2 (parameter `which`), stripping off line prefixes. Examples: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> diff = list(diff) >>> print ''.join(restore(diff, 1)), one two three >>> print ''.join(restore(diff, 2)), ore tree emu """ try: tag = {1: "- ", 2: "+ "}[int(which)] except KeyError: raise ValueError, ('unknown delta choice (must be 1 or 2): %r' % which) prefixes = (" ", tag) for line in delta: if line[:2] in prefixes: yield line[2:]
[ "def", "restore", "(", "delta", ",", "which", ")", ":", "try", ":", "tag", "=", "{", "1", ":", "\"- \"", ",", "2", ":", "\"+ \"", "}", "[", "int", "(", "which", ")", "]", "except", "KeyError", ":", "raise", "ValueError", ",", "(", "'unknown delta choice (must be 1 or 2): %r'", "%", "which", ")", "prefixes", "=", "(", "\" \"", ",", "tag", ")", "for", "line", "in", "delta", ":", "if", "line", "[", ":", "2", "]", "in", "prefixes", ":", "yield", "line", "[", "2", ":", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/difflib.py#L2020-L2050
jsupancic/deep_hand_pose
22cbeae1a8410ff5d37c060c7315719d0a5d608f
scripts/cpp_lint.py
python
_VerboseLevel
()
return _cpplint_state.verbose_level
Returns the module's verbosity setting.
Returns the module's verbosity setting.
[ "Returns", "the", "module", "s", "verbosity", "setting", "." ]
def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level
[ "def", "_VerboseLevel", "(", ")", ":", "return", "_cpplint_state", ".", "verbose_level" ]
https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/scripts/cpp_lint.py#L777-L779
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
TopLevelWindow.Maximize
(*args, **kwargs)
return _windows_.TopLevelWindow_Maximize(*args, **kwargs)
Maximize(self, bool maximize=True)
Maximize(self, bool maximize=True)
[ "Maximize", "(", "self", "bool", "maximize", "=", "True", ")" ]
def Maximize(*args, **kwargs): """Maximize(self, bool maximize=True)""" return _windows_.TopLevelWindow_Maximize(*args, **kwargs)
[ "def", "Maximize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "TopLevelWindow_Maximize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L405-L407
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/datasets/shapenet_scene.py
python
shapenet_scene.label_path_at
(self, i)
return self.label_path_from_index(self.image_index[i])
Return the absolute path to metadata i in the image sequence.
Return the absolute path to metadata i in the image sequence.
[ "Return", "the", "absolute", "path", "to", "metadata", "i", "in", "the", "image", "sequence", "." ]
def label_path_at(self, i): """ Return the absolute path to metadata i in the image sequence. """ return self.label_path_from_index(self.image_index[i])
[ "def", "label_path_at", "(", "self", ",", "i", ")", ":", "return", "self", ".", "label_path_from_index", "(", "self", ".", "image_index", "[", "i", "]", ")" ]
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/shapenet_scene.py#L66-L70
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption2.py
python
IndirectFlatPlateAbsorption.validateInputs
(self)
return issues
Validate algorithm options.
Validate algorithm options.
[ "Validate", "algorithm", "options", "." ]
def validateInputs(self): """ Validate algorithm options. """ self._setup() issues = dict() if self._use_can_corrections and self._can_chemical_formula == '': issues['CanChemicalFormula'] = 'Must be set to use can corrections' if self._use_can_corrections and self._can_ws_name is None: issues['CanWorkspace'] = 'Must specify a can workspace to use can corrections' return issues
[ "def", "validateInputs", "(", "self", ")", ":", "self", ".", "_setup", "(", ")", "issues", "=", "dict", "(", ")", "if", "self", ".", "_use_can_corrections", "and", "self", ".", "_can_chemical_formula", "==", "''", ":", "issues", "[", "'CanChemicalFormula'", "]", "=", "'Must be set to use can corrections'", "if", "self", ".", "_use_can_corrections", "and", "self", ".", "_can_ws_name", "is", "None", ":", "issues", "[", "'CanWorkspace'", "]", "=", "'Must specify a can workspace to use can corrections'", "return", "issues" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption2.py#L394-L408
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xmlTextReader.Close
(self)
return ret
This method releases any resources allocated by the current instance changes the state to Closed and close any underlying input.
This method releases any resources allocated by the current instance changes the state to Closed and close any underlying input.
[ "This", "method", "releases", "any", "resources", "allocated", "by", "the", "current", "instance", "changes", "the", "state", "to", "Closed", "and", "close", "any", "underlying", "input", "." ]
def Close(self): """This method releases any resources allocated by the current instance changes the state to Closed and close any underlying input. """ ret = libxml2mod.xmlTextReaderClose(self._o) return ret
[ "def", "Close", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlTextReaderClose", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L6498-L6503
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/special/basic.py
python
lpn
(n, z)
return pn[:(n+1)], pd[:(n+1)]
Legendre functions of the first kind, Pn(z). Compute sequence of Legendre functions of the first kind (polynomials), Pn(z) and derivatives for all degrees from 0 to n (inclusive). See also special.legendre for polynomial class. References ---------- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special Functions", John Wiley and Sons, 1996. http://jin.ece.illinois.edu/specfunc.html
Legendre functions of the first kind, Pn(z).
[ "Legendre", "functions", "of", "the", "first", "kind", "Pn", "(", "z", ")", "." ]
def lpn(n, z): """Legendre functions of the first kind, Pn(z). Compute sequence of Legendre functions of the first kind (polynomials), Pn(z) and derivatives for all degrees from 0 to n (inclusive). See also special.legendre for polynomial class. References ---------- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special Functions", John Wiley and Sons, 1996. http://jin.ece.illinois.edu/specfunc.html """ if not (isscalar(n) and isscalar(z)): raise ValueError("arguments must be scalars.") if (n != floor(n)) or (n < 0): raise ValueError("n must be a non-negative integer.") if (n < 1): n1 = 1 else: n1 = n if iscomplex(z): pn, pd = specfun.clpn(n1, z) else: pn, pd = specfun.lpn(n1, z) return pn[:(n+1)], pd[:(n+1)]
[ "def", "lpn", "(", "n", ",", "z", ")", ":", "if", "not", "(", "isscalar", "(", "n", ")", "and", "isscalar", "(", "z", ")", ")", ":", "raise", "ValueError", "(", "\"arguments must be scalars.\"", ")", "if", "(", "n", "!=", "floor", "(", "n", ")", ")", "or", "(", "n", "<", "0", ")", ":", "raise", "ValueError", "(", "\"n must be a non-negative integer.\"", ")", "if", "(", "n", "<", "1", ")", ":", "n1", "=", "1", "else", ":", "n1", "=", "n", "if", "iscomplex", "(", "z", ")", ":", "pn", ",", "pd", "=", "specfun", ".", "clpn", "(", "n1", ",", "z", ")", "else", ":", "pn", ",", "pd", "=", "specfun", ".", "lpn", "(", "n1", ",", "z", ")", "return", "pn", "[", ":", "(", "n", "+", "1", ")", "]", ",", "pd", "[", ":", "(", "n", "+", "1", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/special/basic.py#L1590-L1617
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/text_datasets.py
python
maybe_download_dbpedia
(data_dir)
Download if DBpedia data is not present.
Download if DBpedia data is not present.
[ "Download", "if", "DBpedia", "data", "is", "not", "present", "." ]
def maybe_download_dbpedia(data_dir): """Download if DBpedia data is not present.""" train_path = os.path.join(data_dir, 'dbpedia_csv/train.csv') test_path = os.path.join(data_dir, 'dbpedia_csv/test.csv') if not (gfile.Exists(train_path) and gfile.Exists(test_path)): archive_path = base.maybe_download( 'dbpedia_csv.tar.gz', data_dir, DBPEDIA_URL) tfile = tarfile.open(archive_path, 'r:*') tfile.extractall(data_dir)
[ "def", "maybe_download_dbpedia", "(", "data_dir", ")", ":", "train_path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'dbpedia_csv/train.csv'", ")", "test_path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'dbpedia_csv/test.csv'", ")", "if", "not", "(", "gfile", ".", "Exists", "(", "train_path", ")", "and", "gfile", ".", "Exists", "(", "test_path", ")", ")", ":", "archive_path", "=", "base", ".", "maybe_download", "(", "'dbpedia_csv.tar.gz'", ",", "data_dir", ",", "DBPEDIA_URL", ")", "tfile", "=", "tarfile", ".", "open", "(", "archive_path", ",", "'r:*'", ")", "tfile", ".", "extractall", "(", "data_dir", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/text_datasets.py#L33-L41
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
applications/nlp/transformer/subgraph/dataset.py
python
detokenize
(indices)
return text
Convert token indices to string. Stops at the first EOS token. All other special tokens are ignored.
Convert token indices to string.
[ "Convert", "token", "indices", "to", "string", "." ]
def detokenize(indices): """Convert token indices to string. Stops at the first EOS token. All other special tokens are ignored. """ text = '' for index in indices: if index == eos_index: break elif index in (unk_index, bos_index, pad_index): continue else: text += f' {tokens[index]}' return text
[ "def", "detokenize", "(", "indices", ")", ":", "text", "=", "''", "for", "index", "in", "indices", ":", "if", "index", "==", "eos_index", ":", "break", "elif", "index", "in", "(", "unk_index", ",", "bos_index", ",", "pad_index", ")", ":", "continue", "else", ":", "text", "+=", "f' {tokens[index]}'", "return", "text" ]
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/applications/nlp/transformer/subgraph/dataset.py#L78-L93
floooh/oryol
eb08cffe1b1cb6b05ed14ec692bca9372cef064e
fips-files/generators/util/png.py
python
Test.testPNMsbit
(self)
Test that PNM files can generates sBIT chunk.
Test that PNM files can generates sBIT chunk.
[ "Test", "that", "PNM", "files", "can", "generates", "sBIT", "chunk", "." ]
def testPNMsbit(self): """Test that PNM files can generates sBIT chunk.""" def do(): return _main(['testPNMsbit']) s = BytesIO() s.write(strtobytes('P6 8 1 1\n')) for pixel in range(8): s.write(struct.pack('<I', (0x4081*pixel)&0x10101)[:3]) s.flush() s.seek(0) o = BytesIO() testWithIO(s, o, do) r = Reader(bytes=o.getvalue()) sbit = r.chunk('sBIT')[1] self.assertEqual(sbit, strtobytes('\x01\x01\x01'))
[ "def", "testPNMsbit", "(", "self", ")", ":", "def", "do", "(", ")", ":", "return", "_main", "(", "[", "'testPNMsbit'", "]", ")", "s", "=", "BytesIO", "(", ")", "s", ".", "write", "(", "strtobytes", "(", "'P6 8 1 1\\n'", ")", ")", "for", "pixel", "in", "range", "(", "8", ")", ":", "s", ".", "write", "(", "struct", ".", "pack", "(", "'<I'", ",", "(", "0x4081", "*", "pixel", ")", "&", "0x10101", ")", "[", ":", "3", "]", ")", "s", ".", "flush", "(", ")", "s", ".", "seek", "(", "0", ")", "o", "=", "BytesIO", "(", ")", "testWithIO", "(", "s", ",", "o", ",", "do", ")", "r", "=", "Reader", "(", "bytes", "=", "o", ".", "getvalue", "(", ")", ")", "sbit", "=", "r", ".", "chunk", "(", "'sBIT'", ")", "[", "1", "]", "self", ".", "assertEqual", "(", "sbit", ",", "strtobytes", "(", "'\\x01\\x01\\x01'", ")", ")" ]
https://github.com/floooh/oryol/blob/eb08cffe1b1cb6b05ed14ec692bca9372cef064e/fips-files/generators/util/png.py#L2578-L2592
MichalBusta/E2E-MLT
2f0b54e31ebb414cd2daad824d7d474062ebe834
data_gen.py
python
random_rotation
(img, word_gto)
return dst
for i in range(0, len(word_gto) - 1): draw_box_points(dst, word_gto[i]) cv2.imshow('dst', dst) cv2.waitKey(0)
for i in range(0, len(word_gto) - 1): draw_box_points(dst, word_gto[i]) cv2.imshow('dst', dst) cv2.waitKey(0)
[ "for", "i", "in", "range", "(", "0", "len", "(", "word_gto", ")", "-", "1", ")", ":", "draw_box_points", "(", "dst", "word_gto", "[", "i", "]", ")", "cv2", ".", "imshow", "(", "dst", "dst", ")", "cv2", ".", "waitKey", "(", "0", ")" ]
def random_rotation(img, word_gto): center = (img.shape[1] / 2, img.shape[0] / 2) angle = random.uniform(-1900, 1900) / 10 M = cv2.getRotationMatrix2D(center, angle, 1) dst_size = (img.shape[1], img.shape[0]) dst = cv2.warpAffine(img, M, dst_size) angle_rad = - angle * math.pi / 180 wor = np.copy(word_gto) word_gto[:, 0, 0] = ((wor[:, 0, 0] - center[0]) * math.cos(angle_rad)) - ((wor[:, 0, 1] - center[1]) * math.sin(angle_rad)) + center[0] word_gto[:, 0, 1] = ((wor[:, 0, 0] - center[0]) * math.sin(angle_rad)) + ((wor[:, 0, 1] - center[1]) * math.cos(angle_rad)) + center[1] word_gto[:, 1, 0] = ((wor[:, 1, 0] - center[0]) * math.cos(angle_rad)) - ((wor[:, 1, 1] - center[1]) * math.sin(angle_rad)) + center[0] word_gto[:, 1, 1] = ((wor[:, 1, 0] - center[0]) * math.sin(angle_rad)) + ((wor[:, 1, 1] - center[1]) * math.cos(angle_rad)) + center[1] word_gto[:, 2, 0] = ((wor[:, 2, 0] - center[0]) * math.cos(angle_rad)) - ((wor[:, 2, 1] - center[1]) * math.sin(angle_rad)) + center[0] word_gto[:, 2, 1] = ((wor[:, 2, 0] - center[0]) * math.sin(angle_rad)) + ((wor[:, 2, 1] - center[1]) * math.cos(angle_rad)) + center[1] word_gto[:, 3, 0] = ((wor[:, 3, 0] - center[0]) * math.cos(angle_rad)) - ((wor[:, 3, 1] - center[1]) * math.sin(angle_rad)) + center[0] word_gto[:, 3, 1] = ((wor[:, 3, 0] - center[0]) * math.sin(angle_rad)) + ((wor[:, 3, 1] - center[1]) * math.cos(angle_rad)) + center[1] ''' for i in range(0, len(word_gto) - 1): draw_box_points(dst, word_gto[i]) cv2.imshow('dst', dst) cv2.waitKey(0) ''' return dst
[ "def", "random_rotation", "(", "img", ",", "word_gto", ")", ":", "center", "=", "(", "img", ".", "shape", "[", "1", "]", "/", "2", ",", "img", ".", "shape", "[", "0", "]", "/", "2", ")", "angle", "=", "random", ".", "uniform", "(", "-", "1900", ",", "1900", ")", "/", "10", "M", "=", "cv2", ".", "getRotationMatrix2D", "(", "center", ",", "angle", ",", "1", ")", "dst_size", "=", "(", "img", ".", "shape", "[", "1", "]", ",", "img", ".", "shape", "[", "0", "]", ")", "dst", "=", "cv2", ".", "warpAffine", "(", "img", ",", "M", ",", "dst_size", ")", "angle_rad", "=", "-", "angle", "*", "math", ".", "pi", "/", "180", "wor", "=", "np", ".", "copy", "(", "word_gto", ")", "word_gto", "[", ":", ",", "0", ",", "0", "]", "=", "(", "(", "wor", "[", ":", ",", "0", ",", "0", "]", "-", "center", "[", "0", "]", ")", "*", "math", ".", "cos", "(", "angle_rad", ")", ")", "-", "(", "(", "wor", "[", ":", ",", "0", ",", "1", "]", "-", "center", "[", "1", "]", ")", "*", "math", ".", "sin", "(", "angle_rad", ")", ")", "+", "center", "[", "0", "]", "word_gto", "[", ":", ",", "0", ",", "1", "]", "=", "(", "(", "wor", "[", ":", ",", "0", ",", "0", "]", "-", "center", "[", "0", "]", ")", "*", "math", ".", "sin", "(", "angle_rad", ")", ")", "+", "(", "(", "wor", "[", ":", ",", "0", ",", "1", "]", "-", "center", "[", "1", "]", ")", "*", "math", ".", "cos", "(", "angle_rad", ")", ")", "+", "center", "[", "1", "]", "word_gto", "[", ":", ",", "1", ",", "0", "]", "=", "(", "(", "wor", "[", ":", ",", "1", ",", "0", "]", "-", "center", "[", "0", "]", ")", "*", "math", ".", "cos", "(", "angle_rad", ")", ")", "-", "(", "(", "wor", "[", ":", ",", "1", ",", "1", "]", "-", "center", "[", "1", "]", ")", "*", "math", ".", "sin", "(", "angle_rad", ")", ")", "+", "center", "[", "0", "]", "word_gto", "[", ":", ",", "1", ",", "1", "]", "=", "(", "(", "wor", "[", ":", ",", "1", ",", "0", "]", "-", "center", "[", "0", "]", ")", "*", "math", ".", "sin", "(", "angle_rad", ")", ")", "+", "(", "(", "wor", "[", ":", ",", "1", ",", "1", "]", "-", "center", "[", "1", "]", ")", "*", "math", ".", "cos", "(", "angle_rad", ")", ")", "+", "center", "[", "1", "]", "word_gto", "[", ":", ",", "2", ",", "0", "]", "=", "(", "(", "wor", "[", ":", ",", "2", ",", "0", "]", "-", "center", "[", "0", "]", ")", "*", "math", ".", "cos", "(", "angle_rad", ")", ")", "-", "(", "(", "wor", "[", ":", ",", "2", ",", "1", "]", "-", "center", "[", "1", "]", ")", "*", "math", ".", "sin", "(", "angle_rad", ")", ")", "+", "center", "[", "0", "]", "word_gto", "[", ":", ",", "2", ",", "1", "]", "=", "(", "(", "wor", "[", ":", ",", "2", ",", "0", "]", "-", "center", "[", "0", "]", ")", "*", "math", ".", "sin", "(", "angle_rad", ")", ")", "+", "(", "(", "wor", "[", ":", ",", "2", ",", "1", "]", "-", "center", "[", "1", "]", ")", "*", "math", ".", "cos", "(", "angle_rad", ")", ")", "+", "center", "[", "1", "]", "word_gto", "[", ":", ",", "3", ",", "0", "]", "=", "(", "(", "wor", "[", ":", ",", "3", ",", "0", "]", "-", "center", "[", "0", "]", ")", "*", "math", ".", "cos", "(", "angle_rad", ")", ")", "-", "(", "(", "wor", "[", ":", ",", "3", ",", "1", "]", "-", "center", "[", "1", "]", ")", "*", "math", ".", "sin", "(", "angle_rad", ")", ")", "+", "center", "[", "0", "]", "word_gto", "[", ":", ",", "3", ",", "1", "]", "=", "(", "(", "wor", "[", ":", ",", "3", ",", "0", "]", "-", "center", "[", "0", "]", ")", "*", "math", ".", "sin", "(", "angle_rad", ")", ")", "+", "(", "(", "wor", "[", ":", ",", "3", ",", "1", "]", "-", "center", "[", "1", "]", ")", "*", "math", ".", "cos", "(", "angle_rad", ")", ")", "+", "center", "[", "1", "]", "return", "dst" ]
https://github.com/MichalBusta/E2E-MLT/blob/2f0b54e31ebb414cd2daad824d7d474062ebe834/data_gen.py#L151-L182
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cffi/api.py
python
FFI.string
(self, cdata, maxlen=-1)
return self._backend.string(cdata, maxlen)
Return a Python string (or unicode string) from the 'cdata'. If 'cdata' is a pointer or array of characters or bytes, returns the null-terminated string. The returned string extends until the first null character, or at most 'maxlen' characters. If 'cdata' is an array then 'maxlen' defaults to its length. If 'cdata' is a pointer or array of wchar_t, returns a unicode string following the same rules. If 'cdata' is a single character or byte or a wchar_t, returns it as a string or unicode string. If 'cdata' is an enum, returns the value of the enumerator as a string, or 'NUMBER' if the value is out of range.
Return a Python string (or unicode string) from the 'cdata'. If 'cdata' is a pointer or array of characters or bytes, returns the null-terminated string. The returned string extends until the first null character, or at most 'maxlen' characters. If 'cdata' is an array then 'maxlen' defaults to its length.
[ "Return", "a", "Python", "string", "(", "or", "unicode", "string", ")", "from", "the", "cdata", ".", "If", "cdata", "is", "a", "pointer", "or", "array", "of", "characters", "or", "bytes", "returns", "the", "null", "-", "terminated", "string", ".", "The", "returned", "string", "extends", "until", "the", "first", "null", "character", "or", "at", "most", "maxlen", "characters", ".", "If", "cdata", "is", "an", "array", "then", "maxlen", "defaults", "to", "its", "length", "." ]
def string(self, cdata, maxlen=-1): """Return a Python string (or unicode string) from the 'cdata'. If 'cdata' is a pointer or array of characters or bytes, returns the null-terminated string. The returned string extends until the first null character, or at most 'maxlen' characters. If 'cdata' is an array then 'maxlen' defaults to its length. If 'cdata' is a pointer or array of wchar_t, returns a unicode string following the same rules. If 'cdata' is a single character or byte or a wchar_t, returns it as a string or unicode string. If 'cdata' is an enum, returns the value of the enumerator as a string, or 'NUMBER' if the value is out of range. """ return self._backend.string(cdata, maxlen)
[ "def", "string", "(", "self", ",", "cdata", ",", "maxlen", "=", "-", "1", ")", ":", "return", "self", ".", "_backend", ".", "string", "(", "cdata", ",", "maxlen", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cffi/api.py#L302-L318
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/polynomial/legendre.py
python
leg2poly
(c)
Convert a Legendre series to a polynomial. Convert an array representing the coefficients of a Legendre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Legendre series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2leg Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P >>> c = P.Legendre(range(4)) >>> c Legendre([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1]) >>> p = c.convert(kind=P.Polynomial) >>> p Polynomial([-1. , -3.5, 3. , 7.5], domain=[-1., 1.], window=[-1., 1.]) >>> P.leg2poly(range(4)) array([-1. , -3.5, 3. , 7.5])
Convert a Legendre series to a polynomial.
[ "Convert", "a", "Legendre", "series", "to", "a", "polynomial", "." ]
def leg2poly(c): """ Convert a Legendre series to a polynomial. Convert an array representing the coefficients of a Legendre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Legendre series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2leg Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P >>> c = P.Legendre(range(4)) >>> c Legendre([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1]) >>> p = c.convert(kind=P.Polynomial) >>> p Polynomial([-1. , -3.5, 3. , 7.5], domain=[-1., 1.], window=[-1., 1.]) >>> P.leg2poly(range(4)) array([-1. , -3.5, 3. , 7.5]) """ from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n < 3: return c else: c0 = c[-2] c1 = c[-1] # i is the current degree of c1 for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], (c1*(i - 1))/i) c1 = polyadd(tmp, (polymulx(c1)*(2*i - 1))/i) return polyadd(c0, polymulx(c1))
[ "def", "leg2poly", "(", "c", ")", ":", "from", ".", "polynomial", "import", "polyadd", ",", "polysub", ",", "polymulx", "[", "c", "]", "=", "pu", ".", "as_series", "(", "[", "c", "]", ")", "n", "=", "len", "(", "c", ")", "if", "n", "<", "3", ":", "return", "c", "else", ":", "c0", "=", "c", "[", "-", "2", "]", "c1", "=", "c", "[", "-", "1", "]", "# i is the current degree of c1", "for", "i", "in", "range", "(", "n", "-", "1", ",", "1", ",", "-", "1", ")", ":", "tmp", "=", "c0", "c0", "=", "polysub", "(", "c", "[", "i", "-", "2", "]", ",", "(", "c1", "*", "(", "i", "-", "1", ")", ")", "/", "i", ")", "c1", "=", "polyadd", "(", "tmp", ",", "(", "polymulx", "(", "c1", ")", "*", "(", "2", "*", "i", "-", "1", ")", ")", "/", "i", ")", "return", "polyadd", "(", "c0", ",", "polymulx", "(", "c1", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/legendre.py#L148-L207
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/ValidationKit/common/utils.py
python
_sudoFixArguments
(aPositionalArgs, dKeywordArgs, fInitialEnv = True)
return None
Adds 'sudo' (or similar) to the args parameter, whereever it is.
Adds 'sudo' (or similar) to the args parameter, whereever it is.
[ "Adds", "sudo", "(", "or", "similar", ")", "to", "the", "args", "parameter", "whereever", "it", "is", "." ]
def _sudoFixArguments(aPositionalArgs, dKeywordArgs, fInitialEnv = True): """ Adds 'sudo' (or similar) to the args parameter, whereever it is. """ # Are we root? fIsRoot = True; try: fIsRoot = os.getuid() == 0; # pylint: disable=E1101 except: pass; # If not, prepend sudo (non-interactive, simulate initial login). if fIsRoot is not True: asArgs = dKeywordArgs.get('args'); if asArgs is None: asArgs = aPositionalArgs[0]; # Detect old sudo. global g_fOldSudo; if g_fOldSudo is None: try: sVersion = processOutputChecked(['sudo', '-V']); except: sVersion = '1.7.0'; sVersion = sVersion.strip().split('\n')[0]; sVersion = sVersion.replace('Sudo version', '').strip(); g_fOldSudo = len(sVersion) >= 4 \ and sVersion[0] == '1' \ and sVersion[1] == '.' \ and sVersion[2] <= '6' \ and sVersion[3] == '.'; asArgs.insert(0, 'sudo'); if not g_fOldSudo: asArgs.insert(1, '-n'); if fInitialEnv and not g_fOldSudo: asArgs.insert(1, '-i'); # paranoia... if dKeywordArgs.get('args') is not None: dKeywordArgs['args'] = asArgs; else: aPositionalArgs = (asArgs,) + aPositionalArgs[1:]; return None;
[ "def", "_sudoFixArguments", "(", "aPositionalArgs", ",", "dKeywordArgs", ",", "fInitialEnv", "=", "True", ")", ":", "# Are we root?", "fIsRoot", "=", "True", "try", ":", "fIsRoot", "=", "os", ".", "getuid", "(", ")", "==", "0", "# pylint: disable=E1101", "except", ":", "pass", "# If not, prepend sudo (non-interactive, simulate initial login).", "if", "fIsRoot", "is", "not", "True", ":", "asArgs", "=", "dKeywordArgs", ".", "get", "(", "'args'", ")", "if", "asArgs", "is", "None", ":", "asArgs", "=", "aPositionalArgs", "[", "0", "]", "# Detect old sudo.", "global", "g_fOldSudo", "if", "g_fOldSudo", "is", "None", ":", "try", ":", "sVersion", "=", "processOutputChecked", "(", "[", "'sudo'", ",", "'-V'", "]", ")", "except", ":", "sVersion", "=", "'1.7.0'", "sVersion", "=", "sVersion", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "[", "0", "]", "sVersion", "=", "sVersion", ".", "replace", "(", "'Sudo version'", ",", "''", ")", ".", "strip", "(", ")", "g_fOldSudo", "=", "len", "(", "sVersion", ")", ">=", "4", "and", "sVersion", "[", "0", "]", "==", "'1'", "and", "sVersion", "[", "1", "]", "==", "'.'", "and", "sVersion", "[", "2", "]", "<=", "'6'", "and", "sVersion", "[", "3", "]", "==", "'.'", "asArgs", ".", "insert", "(", "0", ",", "'sudo'", ")", "if", "not", "g_fOldSudo", ":", "asArgs", ".", "insert", "(", "1", ",", "'-n'", ")", "if", "fInitialEnv", "and", "not", "g_fOldSudo", ":", "asArgs", ".", "insert", "(", "1", ",", "'-i'", ")", "# paranoia...", "if", "dKeywordArgs", ".", "get", "(", "'args'", ")", "is", "not", "None", ":", "dKeywordArgs", "[", "'args'", "]", "=", "asArgs", "else", ":", "aPositionalArgs", "=", "(", "asArgs", ",", ")", "+", "aPositionalArgs", "[", "1", ":", "]", "return", "None" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/common/utils.py#L599-L643
alexozer/jankdrone
c4b403eb254b41b832ab2bdfade12ba59c99e5dc
drone/lib/nanopb/generator/nanopb_generator.py
python
ExtensionField.tags
(self)
return '#define %-40s %d\n' % (identifier, self.tag)
Return the #define for the tag number of this field.
Return the #define for the tag number of this field.
[ "Return", "the", "#define", "for", "the", "tag", "number", "of", "this", "field", "." ]
def tags(self): '''Return the #define for the tag number of this field.''' identifier = '%s_tag' % self.fullname return '#define %-40s %d\n' % (identifier, self.tag)
[ "def", "tags", "(", "self", ")", ":", "identifier", "=", "'%s_tag'", "%", "self", ".", "fullname", "return", "'#define %-40s %d\\n'", "%", "(", "identifier", ",", "self", ".", "tag", ")" ]
https://github.com/alexozer/jankdrone/blob/c4b403eb254b41b832ab2bdfade12ba59c99e5dc/drone/lib/nanopb/generator/nanopb_generator.py#L652-L655
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/random.py
python
multinomial
(n=[1], p=[[1.0]], shape=_Null, dtype='float32', ctx=None, out=None, **kwargs)
return _internal._sample_multinomial(n, p, shape=shape, out=out, ctx=ctx, dtype=dtype, **kwargs)
Concurrent sampling from multiple multinomial distributions. .. note:: The input distribution must be normalized, i.e. `p` must sum to 1 along its last dimension. Parameters ---------- n : NDArray An *n* dimensional array containing the number of trials of each multinomial distribution. p : NDArray An *n+1* dimensional array containing the probabilities of each multinomial distribution. Its last dimension has length `k`, where `k` is the number of possible outcomes of each multinomial distribution. For example, p with shape `(m, n, k)` specifies `m*n` multinomial distributions each with `k` possible outcomes. shape : int or tuple of ints, optional The number of samples to draw from each distribution. If shape is empty one sample will be drawn from each distribution. out : NDArray, optional Store output to an existing NDArray. ctx : Context, optional Device context of output. Default is current context. Overridden by `n.context` when `n` is an NDArray. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `n` and `p` are a scalar and an array of length k respectively, output shape will be `(m, n, k)`. If `n` and `p` are NDArrays with shape, e.g., `(x, y)` and `(x, y, k)`, then output will have shape `(x, y, m, n, k)`, where `m*n` samples are drawn for each `[n, p)` pair. Examples -------- >>> mx.nd.random.multinomial(mx.nd.array([10]), mx.nd.array([[0.1, 0.9]])) [[ 1. 9.]] <NDArray 1x2 @cpu(0)> >>> mx.nd.random.multinomial(mx.nd.array([10]), mx.nd.array([[0.6, 0.4]]), shape=(2,)) [[[ 5. 5.] [ 6. 4.]]] <NDArray 1x2x2 @cpu(0)> >>> n = mx.nd.array([10, 2, 3]) >>> p = mx.nd.array([[0.2, 0.8], [0.3, 0.7], [0.4, 0.6]]) >>> mx.nd.random.binomial(n, p) [[ 2. 8.] [ 1. 1.] [ 1. 2.]] <NDArray 3x2 @cpu(0)>
Concurrent sampling from multiple multinomial distributions.
[ "Concurrent", "sampling", "from", "multiple", "multinomial", "distributions", "." ]
def multinomial(n=[1], p=[[1.0]], shape=_Null, dtype='float32', ctx=None, out=None, **kwargs): """Concurrent sampling from multiple multinomial distributions. .. note:: The input distribution must be normalized, i.e. `p` must sum to 1 along its last dimension. Parameters ---------- n : NDArray An *n* dimensional array containing the number of trials of each multinomial distribution. p : NDArray An *n+1* dimensional array containing the probabilities of each multinomial distribution. Its last dimension has length `k`, where `k` is the number of possible outcomes of each multinomial distribution. For example, p with shape `(m, n, k)` specifies `m*n` multinomial distributions each with `k` possible outcomes. shape : int or tuple of ints, optional The number of samples to draw from each distribution. If shape is empty one sample will be drawn from each distribution. out : NDArray, optional Store output to an existing NDArray. ctx : Context, optional Device context of output. Default is current context. Overridden by `n.context` when `n` is an NDArray. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `n` and `p` are a scalar and an array of length k respectively, output shape will be `(m, n, k)`. If `n` and `p` are NDArrays with shape, e.g., `(x, y)` and `(x, y, k)`, then output will have shape `(x, y, m, n, k)`, where `m*n` samples are drawn for each `[n, p)` pair. Examples -------- >>> mx.nd.random.multinomial(mx.nd.array([10]), mx.nd.array([[0.1, 0.9]])) [[ 1. 9.]] <NDArray 1x2 @cpu(0)> >>> mx.nd.random.multinomial(mx.nd.array([10]), mx.nd.array([[0.6, 0.4]]), shape=(2,)) [[[ 5. 5.] [ 6. 4.]]] <NDArray 1x2x2 @cpu(0)> >>> n = mx.nd.array([10, 2, 3]) >>> p = mx.nd.array([[0.2, 0.8], [0.3, 0.7], [0.4, 0.6]]) >>> mx.nd.random.binomial(n, p) [[ 2. 8.] [ 1. 1.] [ 1. 2.]] <NDArray 3x2 @cpu(0)> """ return _internal._sample_multinomial(n, p, shape=shape, out=out, ctx=ctx, dtype=dtype, **kwargs)
[ "def", "multinomial", "(", "n", "=", "[", "1", "]", ",", "p", "=", "[", "[", "1.0", "]", "]", ",", "shape", "=", "_Null", ",", "dtype", "=", "'float32'", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_internal", ".", "_sample_multinomial", "(", "n", ",", "p", ",", "shape", "=", "shape", ",", "out", "=", "out", ",", "ctx", "=", "ctx", ",", "dtype", "=", "dtype", ",", "*", "*", "kwargs", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/random.py#L617-L670
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/function_base.py
python
trim_zeros
(filt, trim='fb')
return filt[first:last]
Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb', trim zeros from both front and back of the array. Returns ------- trimmed : 1-D array or sequence The result of trimming the input. The input data type is preserved. Examples -------- >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1]) >>> np.trim_zeros(a, 'b') array([0, 0, 0, 1, 2, 3, 0, 2, 1]) The input data type is preserved, list/tuple in means list/tuple out. >>> np.trim_zeros([0, 1, 2, 0]) [1, 2]
Trim the leading and/or trailing zeros from a 1-D array or sequence.
[ "Trim", "the", "leading", "and", "/", "or", "trailing", "zeros", "from", "a", "1", "-", "D", "array", "or", "sequence", "." ]
def trim_zeros(filt, trim='fb'): """ Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb', trim zeros from both front and back of the array. Returns ------- trimmed : 1-D array or sequence The result of trimming the input. The input data type is preserved. Examples -------- >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1]) >>> np.trim_zeros(a, 'b') array([0, 0, 0, 1, 2, 3, 0, 2, 1]) The input data type is preserved, list/tuple in means list/tuple out. >>> np.trim_zeros([0, 1, 2, 0]) [1, 2] """ first = 0 trim = trim.upper() if 'F' in trim: for i in filt: if i != 0.: break else: first = first + 1 last = len(filt) if 'B' in trim: for i in filt[::-1]: if i != 0.: break else: last = last - 1 return filt[first:last]
[ "def", "trim_zeros", "(", "filt", ",", "trim", "=", "'fb'", ")", ":", "first", "=", "0", "trim", "=", "trim", ".", "upper", "(", ")", "if", "'F'", "in", "trim", ":", "for", "i", "in", "filt", ":", "if", "i", "!=", "0.", ":", "break", "else", ":", "first", "=", "first", "+", "1", "last", "=", "len", "(", "filt", ")", "if", "'B'", "in", "trim", ":", "for", "i", "in", "filt", "[", ":", ":", "-", "1", "]", ":", "if", "i", "!=", "0.", ":", "break", "else", ":", "last", "=", "last", "-", "1", "return", "filt", "[", "first", ":", "last", "]" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/function_base.py#L1211-L1255
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py
python
NaClProgram
(env, target, sources, variant_dir='obj')
return env.Program(target, program_objects)
Add a Program to env that builds its objects in the directory specified by |variant_dir|. This is slightly different than VariantDir() in that the sources can live in the same directory as the calling SConscript file. Args: env: Environment to modify. target: The target name that depends on the object files. E.g. "hello_world_x86_32.nexe" sources: The list of source files that are used to build the objects. variant_dir: The built object files are put in this directory. Default value is "obj". Returns: The Program Node.
Add a Program to env that builds its objects in the directory specified by |variant_dir|.
[ "Add", "a", "Program", "to", "env", "that", "builds", "its", "objects", "in", "the", "directory", "specified", "by", "|variant_dir|", "." ]
def NaClProgram(env, target, sources, variant_dir='obj'): '''Add a Program to env that builds its objects in the directory specified by |variant_dir|. This is slightly different than VariantDir() in that the sources can live in the same directory as the calling SConscript file. Args: env: Environment to modify. target: The target name that depends on the object files. E.g. "hello_world_x86_32.nexe" sources: The list of source files that are used to build the objects. variant_dir: The built object files are put in this directory. Default value is "obj". Returns: The Program Node. ''' program_objects = [] for src_file in sources: obj_file = os.path.splitext(src_file)[0] + env.get('OBJSUFFIX', '.o') program_objects.append(env.StaticObject( target=os.path.join(variant_dir, obj_file), source=src_file)) env.Clean('.', variant_dir) return env.Program(target, program_objects)
[ "def", "NaClProgram", "(", "env", ",", "target", ",", "sources", ",", "variant_dir", "=", "'obj'", ")", ":", "program_objects", "=", "[", "]", "for", "src_file", "in", "sources", ":", "obj_file", "=", "os", ".", "path", ".", "splitext", "(", "src_file", ")", "[", "0", "]", "+", "env", ".", "get", "(", "'OBJSUFFIX'", ",", "'.o'", ")", "program_objects", ".", "append", "(", "env", ".", "StaticObject", "(", "target", "=", "os", ".", "path", ".", "join", "(", "variant_dir", ",", "obj_file", ")", ",", "source", "=", "src_file", ")", ")", "env", ".", "Clean", "(", "'.'", ",", "variant_dir", ")", "return", "env", ".", "Program", "(", "target", ",", "program_objects", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py#L99-L124
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/__init__.py
python
IResourceProvider.resource_listdir
(resource_name)
List of resource names in the directory (like ``os.listdir()``)
List of resource names in the directory (like ``os.listdir()``)
[ "List", "of", "resource", "names", "in", "the", "directory", "(", "like", "os", ".", "listdir", "()", ")" ]
def resource_listdir(resource_name): """List of resource names in the directory (like ``os.listdir()``)"""
[ "def", "resource_listdir", "(", "resource_name", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L549-L550
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/sNMR/mrsprofile.py
python
MRSprofile.showModel
(self, showFit=0, cmap=Spectral, figsize=(13, 12), wlim=(0, 0.5), tlim=(0.05, 0.5))
return fig, ax
Show 2d model as stitched 1d models along with fit.
Show 2d model as stitched 1d models along with fit.
[ "Show", "2d", "model", "as", "stitched", "1d", "models", "along", "with", "fit", "." ]
def showModel(self, showFit=0, cmap=Spectral, figsize=(13, 12), wlim=(0, 0.5), tlim=(0.05, 0.5)): """Show 2d model as stitched 1d models along with fit.""" fig, ax = plt.subplots(nrows=2+showFit, figsize=figsize, sharex=True) self.showWC(wlim, ax=ax[-2], cmap=cmap) self.showT2(tlim, ax=ax[-1], cmap=cmap) xl = ax[-1].get_xlim() ax[0].set_xlabel('x (m)') ax[0].xaxis.set_label_position('top') ax[0].xaxis.tick_top() ax[0].set_ylabel(r'$\chi^2$ (-)') for axi in ax[-2:]: axi.set_ylabel('z (m)') if showFit > 0: self.showFits(ax[0]) ax[0].set_xlim(xl) return fig, ax
[ "def", "showModel", "(", "self", ",", "showFit", "=", "0", ",", "cmap", "=", "Spectral", ",", "figsize", "=", "(", "13", ",", "12", ")", ",", "wlim", "=", "(", "0", ",", "0.5", ")", ",", "tlim", "=", "(", "0.05", ",", "0.5", ")", ")", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "nrows", "=", "2", "+", "showFit", ",", "figsize", "=", "figsize", ",", "sharex", "=", "True", ")", "self", ".", "showWC", "(", "wlim", ",", "ax", "=", "ax", "[", "-", "2", "]", ",", "cmap", "=", "cmap", ")", "self", ".", "showT2", "(", "tlim", ",", "ax", "=", "ax", "[", "-", "1", "]", ",", "cmap", "=", "cmap", ")", "xl", "=", "ax", "[", "-", "1", "]", ".", "get_xlim", "(", ")", "ax", "[", "0", "]", ".", "set_xlabel", "(", "'x (m)'", ")", "ax", "[", "0", "]", ".", "xaxis", ".", "set_label_position", "(", "'top'", ")", "ax", "[", "0", "]", ".", "xaxis", ".", "tick_top", "(", ")", "ax", "[", "0", "]", ".", "set_ylabel", "(", "r'$\\chi^2$ (-)'", ")", "for", "axi", "in", "ax", "[", "-", "2", ":", "]", ":", "axi", ".", "set_ylabel", "(", "'z (m)'", ")", "if", "showFit", ">", "0", ":", "self", ".", "showFits", "(", "ax", "[", "0", "]", ")", "ax", "[", "0", "]", ".", "set_xlim", "(", "xl", ")", "return", "fig", ",", "ax" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/sNMR/mrsprofile.py#L416-L433
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py
python
CompileCommand.directory
(self)
return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
Get the working directory for this CompileCommand
Get the working directory for this CompileCommand
[ "Get", "the", "working", "directory", "for", "this", "CompileCommand" ]
def directory(self): """Get the working directory for this CompileCommand""" return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
[ "def", "directory", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CompileCommand_getDirectory", "(", "self", ".", "cmd", ")" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py#L3178-L3180
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/metrics/python/ops/histogram_ops.py
python
_strict_conv1d
(x, h)
Return x * h for rank 1 tensors x and h.
Return x * h for rank 1 tensors x and h.
[ "Return", "x", "*", "h", "for", "rank", "1", "tensors", "x", "and", "h", "." ]
def _strict_conv1d(x, h): """Return x * h for rank 1 tensors x and h.""" with ops.name_scope('strict_conv1d', values=[x, h]): x = array_ops.reshape(x, (1, -1, 1, 1)) h = array_ops.reshape(h, (-1, 1, 1, 1)) result = nn_ops.conv2d(x, h, [1, 1, 1, 1], 'SAME') return array_ops.reshape(result, [-1])
[ "def", "_strict_conv1d", "(", "x", ",", "h", ")", ":", "with", "ops", ".", "name_scope", "(", "'strict_conv1d'", ",", "values", "=", "[", "x", ",", "h", "]", ")", ":", "x", "=", "array_ops", ".", "reshape", "(", "x", ",", "(", "1", ",", "-", "1", ",", "1", ",", "1", ")", ")", "h", "=", "array_ops", ".", "reshape", "(", "h", ",", "(", "-", "1", ",", "1", ",", "1", ",", "1", ")", ")", "result", "=", "nn_ops", ".", "conv2d", "(", "x", ",", "h", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ",", "'SAME'", ")", "return", "array_ops", ".", "reshape", "(", "result", ",", "[", "-", "1", "]", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/metrics/python/ops/histogram_ops.py#L237-L243
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
scripts/cpp_lint.py
python
_NestingState.UpdatePreprocessor
(self, line)
Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check.
Update preprocessor stack.
[ "Update", "preprocessor", "stack", "." ]
def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass
[ "def", "UpdatePreprocessor", "(", "self", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef)\\b'", ",", "line", ")", ":", "# Beginning of #if block, save the nesting stack here. The saved", "# stack will allow us to restore the parsing state in the #else case.", "self", ".", "pp_stack", ".", "append", "(", "_PreprocessorInfo", "(", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", ")", ")", "elif", "Match", "(", "r'^\\s*#\\s*(else|elif)\\b'", ",", "line", ")", ":", "# Beginning of #else block", "if", "self", ".", "pp_stack", ":", "if", "not", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "# This is the first #else or #elif block. Remember the", "# whole nesting stack up to this point. This is what we", "# keep after the #endif.", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", "=", "True", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "=", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", "# Restore the stack to how it was before the #if", "self", ".", "stack", "=", "copy", ".", "deepcopy", "(", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_if", ")", "else", ":", "# TODO(unknown): unexpected #else, issue warning?", "pass", "elif", "Match", "(", "r'^\\s*#\\s*endif\\b'", ",", "line", ")", ":", "# End of #if or #else blocks.", "if", "self", ".", "pp_stack", ":", "# If we saw an #else, we will need to restore the nesting", "# stack to its former state before the #else, otherwise we", "# will just continue from where we left off.", "if", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "# Here we can just use a shallow copy since we are the last", "# reference to it.", "self", ".", "stack", "=", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "# Drop the corresponding #if", "self", ".", "pp_stack", ".", "pop", "(", ")", "else", ":", "# TODO(unknown): unexpected #endif, issue warning?", "pass" ]
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L1948-L2002
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/distutils/msvc9compiler.py
python
Reg.read_values
(cls, base, key)
return d
Return dict of registry keys and values. All names are converted to lowercase.
Return dict of registry keys and values.
[ "Return", "dict", "of", "registry", "keys", "and", "values", "." ]
def read_values(cls, base, key): """Return dict of registry keys and values. All names are converted to lowercase. """ try: handle = RegOpenKeyEx(base, key) except RegError: return None d = {} i = 0 while True: try: name, value, type = RegEnumValue(handle, i) except RegError: break name = name.lower() d[cls.convert_mbcs(name)] = cls.convert_mbcs(value) i += 1 return d
[ "def", "read_values", "(", "cls", ",", "base", ",", "key", ")", ":", "try", ":", "handle", "=", "RegOpenKeyEx", "(", "base", ",", "key", ")", "except", "RegError", ":", "return", "None", "d", "=", "{", "}", "i", "=", "0", "while", "True", ":", "try", ":", "name", ",", "value", ",", "type", "=", "RegEnumValue", "(", "handle", ",", "i", ")", "except", "RegError", ":", "break", "name", "=", "name", ".", "lower", "(", ")", "d", "[", "cls", ".", "convert_mbcs", "(", "name", ")", "]", "=", "cls", ".", "convert_mbcs", "(", "value", ")", "i", "+=", "1", "return", "d" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/msvc9compiler.py#L90-L109
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
utils/vim-lldb/python-vim-lldb/import_lldb.py
python
import_lldb
()
return False
Find and import the lldb modules. This function tries to find the lldb module by: 1. Simply by doing "import lldb" in case the system python installation is aware of lldb. If that fails, 2. Executes the lldb executable pointed to by the LLDB environment variable (or if unset, the first lldb on PATH") with the -P flag to determine the PYTHONPATH to set. If the lldb executable returns a valid path, it is added to sys.path and the import is attempted again. If that fails, 3. On Mac OS X the default Xcode 4.5 installation path.
Find and import the lldb modules. This function tries to find the lldb module by: 1. Simply by doing "import lldb" in case the system python installation is aware of lldb. If that fails, 2. Executes the lldb executable pointed to by the LLDB environment variable (or if unset, the first lldb on PATH") with the -P flag to determine the PYTHONPATH to set. If the lldb executable returns a valid path, it is added to sys.path and the import is attempted again. If that fails, 3. On Mac OS X the default Xcode 4.5 installation path.
[ "Find", "and", "import", "the", "lldb", "modules", ".", "This", "function", "tries", "to", "find", "the", "lldb", "module", "by", ":", "1", ".", "Simply", "by", "doing", "import", "lldb", "in", "case", "the", "system", "python", "installation", "is", "aware", "of", "lldb", ".", "If", "that", "fails", "2", ".", "Executes", "the", "lldb", "executable", "pointed", "to", "by", "the", "LLDB", "environment", "variable", "(", "or", "if", "unset", "the", "first", "lldb", "on", "PATH", ")", "with", "the", "-", "P", "flag", "to", "determine", "the", "PYTHONPATH", "to", "set", ".", "If", "the", "lldb", "executable", "returns", "a", "valid", "path", "it", "is", "added", "to", "sys", ".", "path", "and", "the", "import", "is", "attempted", "again", ".", "If", "that", "fails", "3", ".", "On", "Mac", "OS", "X", "the", "default", "Xcode", "4", ".", "5", "installation", "path", "." ]
def import_lldb(): """ Find and import the lldb modules. This function tries to find the lldb module by: 1. Simply by doing "import lldb" in case the system python installation is aware of lldb. If that fails, 2. Executes the lldb executable pointed to by the LLDB environment variable (or if unset, the first lldb on PATH") with the -P flag to determine the PYTHONPATH to set. If the lldb executable returns a valid path, it is added to sys.path and the import is attempted again. If that fails, 3. On Mac OS X the default Xcode 4.5 installation path. """ # Try simple 'import lldb', in case of a system-wide install or a # pre-configured PYTHONPATH try: import lldb return True except ImportError: pass # Allow overriding default path to lldb executable with the LLDB # environment variable lldb_executable = 'lldb' if 'LLDB' in os.environ and os.path.exists(os.environ['LLDB']): lldb_executable = os.environ['LLDB'] # Try using builtin module location support ('lldb -P') from subprocess import check_output, CalledProcessError try: with open(os.devnull, 'w') as fnull: lldb_minus_p_path = check_output( "%s -P" % lldb_executable, shell=True, stderr=fnull).strip() if not os.path.exists(lldb_minus_p_path): # lldb -P returned invalid path, probably too old pass else: sys.path.append(lldb_minus_p_path) import lldb return True except CalledProcessError: # Cannot run 'lldb -P' to determine location of lldb python module pass except ImportError: # Unable to import lldb module from path returned by `lldb -P` pass # On Mac OS X, use the try the default path to XCode lldb module if "darwin" in sys.platform: xcode_python_path = "/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Versions/Current/Resources/Python/" sys.path.append(xcode_python_path) try: import lldb return True except ImportError: # Unable to import lldb module from default Xcode python path pass return False
[ "def", "import_lldb", "(", ")", ":", "# Try simple 'import lldb', in case of a system-wide install or a", "# pre-configured PYTHONPATH", "try", ":", "import", "lldb", "return", "True", "except", "ImportError", ":", "pass", "# Allow overriding default path to lldb executable with the LLDB", "# environment variable", "lldb_executable", "=", "'lldb'", "if", "'LLDB'", "in", "os", ".", "environ", "and", "os", ".", "path", ".", "exists", "(", "os", ".", "environ", "[", "'LLDB'", "]", ")", ":", "lldb_executable", "=", "os", ".", "environ", "[", "'LLDB'", "]", "# Try using builtin module location support ('lldb -P')", "from", "subprocess", "import", "check_output", ",", "CalledProcessError", "try", ":", "with", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "as", "fnull", ":", "lldb_minus_p_path", "=", "check_output", "(", "\"%s -P\"", "%", "lldb_executable", ",", "shell", "=", "True", ",", "stderr", "=", "fnull", ")", ".", "strip", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "lldb_minus_p_path", ")", ":", "# lldb -P returned invalid path, probably too old", "pass", "else", ":", "sys", ".", "path", ".", "append", "(", "lldb_minus_p_path", ")", "import", "lldb", "return", "True", "except", "CalledProcessError", ":", "# Cannot run 'lldb -P' to determine location of lldb python module", "pass", "except", "ImportError", ":", "# Unable to import lldb module from path returned by `lldb -P`", "pass", "# On Mac OS X, use the try the default path to XCode lldb module", "if", "\"darwin\"", "in", "sys", ".", "platform", ":", "xcode_python_path", "=", "\"/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Versions/Current/Resources/Python/\"", "sys", ".", "path", ".", "append", "(", "xcode_python_path", ")", "try", ":", "import", "lldb", "return", "True", "except", "ImportError", ":", "# Unable to import lldb module from default Xcode python path", "pass", "return", "False" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/vim-lldb/python-vim-lldb/import_lldb.py#L8-L65
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/_converters_entry.py
python
convert
( model, source="auto", inputs=None, outputs=None, classifier_config=None, minimum_deployment_target=None, **kwargs )
return model
Convert TensorFlow or Pytorch models to Core ML model format. Whether a parameter is required may differ between frameworks (see below). Note that this function is aliased as `ct.convert` in the tutorials. Parameters ---------- model: TensorFlow 1, TensorFlow 2 or Pytorch model in one of the following format: For TensorFlow versions 1.x: - Frozen `tf.Graph <https://www.tensorflow.org/api_docs/python/tf/Graph>`_ - Frozen graph (`.pb`) file path - `tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras>`_ - `HDF5 <https://keras.io/api/models/model_saving_apis/>`_ file path (`.h5`) - `SavedModel <https://www.tensorflow.org/guide/saved_model>`_ directory path For TensorFlow versions 2.x: - `tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras>`_ - `HDF5 file path <https://keras.io/api/models/model_saving_apis/>`_ (`.h5`) - `SavedModel <https://www.tensorflow.org/guide/saved_model>`_ directory path - A `concrete function <https://www.tensorflow.org/guide/concrete_function>`_ For Pytorch: - A `TorchScript <https://pytorch.org/docs/stable/jit.html>`_ object - Path to a `.pt` file source: str (optional) One of `auto`, `tensorflow`, or `pytorch`. `auto` determines the framework automatically for most cases. Raise ValueError if it fails to determine the source framework. inputs: list of `TensorType` or `ImageType` - Inputs are required for PyTorch model, but optional for TensorFlow. - For PyTorch models, the inputs may be nested list or tuple, but for TensorFlow models it must be a flat list. - For TensorFlow, if inputs is `None`, the inputs are `Placeholder` nodes in the model (if model is frozen graph) or function inputs (if model is tf function). - For TensorFlow, if inputs is not `None`, inputs may contain only a subset of all Placeholder in the TF model. outputs: list[str] (optional) TensorFlow 1 and 2: - `outputs` are optional. - If specified, `outputs` is a list of string representing node names. - If `outputs` are not specified, converter infers outputs as all terminal identity nodes. PyTorch: - `outputs` must not be specified. classifier_config: ClassifierConfig class (optional) The configuration if the mlmodel is intended to be a classifier. minimum_deployment_target: coremltools.target enumeration (optional) - one of the members of enum "coremltools.target." - When not-specified or None, converter aims for as minimum of a deployment target as possible Returns ------- model: MLModel A Core ML MLModel object Examples -------- TensorFlow 1, 2 (`model` is a frozen graph): >>> with tf.Graph().as_default() as graph: >>> x = tf.placeholder(tf.float32, shape=(1, 2, 3), name="input") >>> y = tf.nn.relu(x, name="output") # Automatically infer inputs and outputs >>> mlmodel = ct.convert(graph) >>> test_input = np.random.rand(1, 2, 3) - 0.5 >>> results = mlmodel.predict({"input": test_input}) >>> print(results['output']) TensorFlow 2 (`model` is tf.Keras model path): >>> x = tf.keras.Input(shape=(32,), name='input') >>> y = tf.keras.layers.Dense(16, activation='softmax')(x) >>> keras_model = tf.keras.Model(x, y) >>> keras_model.save(h5_path) >>> mlmodel = ct.convert(h5_path) >>> test_input = np.random.rand(2, 32) >>> results = mlmodel.predict({'input': test_input}) >>> print(results['Identity']) Pytorch: >>> model = torchvision.models.mobilenet_v2() >>> model.eval() >>> example_input = torch.rand(1, 3, 256, 256) >>> traced_model = torch.jit.trace(model, example_input) >>> input = ct.TensorType(name='input_name', shape=(1, 3, 256, 256)) >>> mlmodel = ct.convert(traced_model, inputs=[input]) >>> results = mlmodel.predict({"input": example_input.numpy()}) >>> print(results['1651']) # 1651 is the node name given by PyTorch's JIT See `here <https://coremltools.readme.io/docs/neural-network-conversion>`_ for more advanced options
Convert TensorFlow or Pytorch models to Core ML model format. Whether a parameter is required may differ between frameworks (see below). Note that this function is aliased as `ct.convert` in the tutorials.
[ "Convert", "TensorFlow", "or", "Pytorch", "models", "to", "Core", "ML", "model", "format", ".", "Whether", "a", "parameter", "is", "required", "may", "differ", "between", "frameworks", "(", "see", "below", ")", ".", "Note", "that", "this", "function", "is", "aliased", "as", "ct", ".", "convert", "in", "the", "tutorials", "." ]
def convert( model, source="auto", inputs=None, outputs=None, classifier_config=None, minimum_deployment_target=None, **kwargs ): """ Convert TensorFlow or Pytorch models to Core ML model format. Whether a parameter is required may differ between frameworks (see below). Note that this function is aliased as `ct.convert` in the tutorials. Parameters ---------- model: TensorFlow 1, TensorFlow 2 or Pytorch model in one of the following format: For TensorFlow versions 1.x: - Frozen `tf.Graph <https://www.tensorflow.org/api_docs/python/tf/Graph>`_ - Frozen graph (`.pb`) file path - `tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras>`_ - `HDF5 <https://keras.io/api/models/model_saving_apis/>`_ file path (`.h5`) - `SavedModel <https://www.tensorflow.org/guide/saved_model>`_ directory path For TensorFlow versions 2.x: - `tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras>`_ - `HDF5 file path <https://keras.io/api/models/model_saving_apis/>`_ (`.h5`) - `SavedModel <https://www.tensorflow.org/guide/saved_model>`_ directory path - A `concrete function <https://www.tensorflow.org/guide/concrete_function>`_ For Pytorch: - A `TorchScript <https://pytorch.org/docs/stable/jit.html>`_ object - Path to a `.pt` file source: str (optional) One of `auto`, `tensorflow`, or `pytorch`. `auto` determines the framework automatically for most cases. Raise ValueError if it fails to determine the source framework. inputs: list of `TensorType` or `ImageType` - Inputs are required for PyTorch model, but optional for TensorFlow. - For PyTorch models, the inputs may be nested list or tuple, but for TensorFlow models it must be a flat list. - For TensorFlow, if inputs is `None`, the inputs are `Placeholder` nodes in the model (if model is frozen graph) or function inputs (if model is tf function). - For TensorFlow, if inputs is not `None`, inputs may contain only a subset of all Placeholder in the TF model. outputs: list[str] (optional) TensorFlow 1 and 2: - `outputs` are optional. - If specified, `outputs` is a list of string representing node names. - If `outputs` are not specified, converter infers outputs as all terminal identity nodes. PyTorch: - `outputs` must not be specified. classifier_config: ClassifierConfig class (optional) The configuration if the mlmodel is intended to be a classifier. minimum_deployment_target: coremltools.target enumeration (optional) - one of the members of enum "coremltools.target." - When not-specified or None, converter aims for as minimum of a deployment target as possible Returns ------- model: MLModel A Core ML MLModel object Examples -------- TensorFlow 1, 2 (`model` is a frozen graph): >>> with tf.Graph().as_default() as graph: >>> x = tf.placeholder(tf.float32, shape=(1, 2, 3), name="input") >>> y = tf.nn.relu(x, name="output") # Automatically infer inputs and outputs >>> mlmodel = ct.convert(graph) >>> test_input = np.random.rand(1, 2, 3) - 0.5 >>> results = mlmodel.predict({"input": test_input}) >>> print(results['output']) TensorFlow 2 (`model` is tf.Keras model path): >>> x = tf.keras.Input(shape=(32,), name='input') >>> y = tf.keras.layers.Dense(16, activation='softmax')(x) >>> keras_model = tf.keras.Model(x, y) >>> keras_model.save(h5_path) >>> mlmodel = ct.convert(h5_path) >>> test_input = np.random.rand(2, 32) >>> results = mlmodel.predict({'input': test_input}) >>> print(results['Identity']) Pytorch: >>> model = torchvision.models.mobilenet_v2() >>> model.eval() >>> example_input = torch.rand(1, 3, 256, 256) >>> traced_model = torch.jit.trace(model, example_input) >>> input = ct.TensorType(name='input_name', shape=(1, 3, 256, 256)) >>> mlmodel = ct.convert(traced_model, inputs=[input]) >>> results = mlmodel.predict({"input": example_input.numpy()}) >>> print(results['1651']) # 1651 is the node name given by PyTorch's JIT See `here <https://coremltools.readme.io/docs/neural-network-conversion>`_ for more advanced options """ if minimum_deployment_target is not None and not isinstance( minimum_deployment_target, AvailableTarget ): msg = ( "Unrecognized value of argument 'minimum_deployment_target': {}. " "It needs to be a member of 'coremltools.target' enumeration. " "For example, coremltools.target.iOS13" ) raise TypeError(msg.format(minimum_deployment_target)) source = source.lower() if source not in {"auto", "tensorflow", "pytorch"}: msg = ( 'Unrecognized value of argument "source": {}. ' 'It must be one of ["auto", "tensorflow", "pytorch"].' ) raise ValueError(msg.format(source)) def raise_if_duplicated(input_list): # Detect duplicated inputs input_names = [t.name for t in input_list if t.name is not None] dups = [ item for item, count in collections.Counter(input_names).items() if count > 1 ] if len(dups) > 0: raise ValueError("Duplicated inputs: {}".format(dups)) if inputs is not None: if not isinstance(inputs, list): msg = '"inputs" must be of type list' raise ValueError(msg) if classifier_config is not None: if not isinstance(classifier_config, ClassifierConfig): msg = '"classifier_config" must be of type ClassifierConfig' raise ValueError(msg) if source == "tensorflow" and _HAS_TF_2: source = "tensorflow2" if source == "auto" and _HAS_TF_1: try: loader = TF1Loader(model, outputs=outputs) loader._graph_def_from_model(outputs=outputs) source = "tensorflow" except: pass if source == "auto" and _HAS_TF_2: try: loader = TF2Loader(model, outputs=outputs) loader._graph_def_from_model(outputs=outputs) source = "tensorflow2" except: pass if source == "auto" and _HAS_TORCH: try: pytorch_load(model) source = "pytorch" except: pass if source == "auto" and isinstance(model, Program): source = "mil" convert_to = kwargs.get("convert_to", "nn_proto") kwargs.pop("convert_to", None) if source == "auto": msg = ( "Unable to determine the type of the model, i.e. the source framework. " 'Please provide the value of argument "source", from one of ' '["tensorflow", "pytorch"]. Note that model conversion requires the ' "source package that generates the model. Please make sure you have " "the appropriate version of source package installed. E.g., if you're " "converting model originally trained with TensorFlow 1.14, make sure " "you have `tensorflow==1.14` installed." ) raise ValueError(msg) elif source in {"tensorflow", "tensorflow2"}: if source == "tensorflow" and not _HAS_TF_1: raise ValueError( 'Converter was called with source="tensorflow", but missing tensorflow package' ) if inputs is not None: raise_if_duplicated(inputs) if inputs is not None and not all( [isinstance(_input, InputType) for _input in inputs] ): raise ValueError("Input should be a list of TensorType or ImageType") proto_spec = _convert( model, convert_from=source, convert_to=convert_to, inputs=inputs, outputs=outputs, classifier_config=classifier_config, **kwargs ) elif source == "pytorch": if "example_inputs" in kwargs: msg = 'Unexpected argument "example_inputs" found' raise ValueError(msg) def _flatten_list(_inputs): ret = [] for _input in _inputs: if isinstance(_input, (list, tuple)): ret.extend(_flatten_list(_input)) elif isinstance(_input, InputType): ret.append(_input) else: raise ValueError( "Unknown type {} for flattening into InputType.".format( type(_input) ) ) return ret flat_inputs = _flatten_list(inputs) raise_if_duplicated(flat_inputs) if inputs is not None and not all( [isinstance(_input, InputType) for _input in flat_inputs] ): raise ValueError( "Input should be a list/tuple (or nested lists/tuples) of TensorType or ImageType" ) if outputs is not None: raise ValueError("outputs must not be specified for PyTorch") proto_spec = _convert( model, convert_from="torch", convert_to=convert_to, inputs=inputs, outputs=outputs, classifier_config=classifier_config, **kwargs ) elif source == "mil": if not isinstance(model, Program): msg = "Converter was asked to convert MIL input, but input is not a MIL program!" raise ValueError(msg) proto_spec = _convert( model, convert_from="mil", convert_to=convert_to, example_inputs=inputs, classifier_config=classifier_config, **kwargs ) model = coremltools.models.MLModel(proto_spec, useCPUOnly=True) if minimum_deployment_target is not None: check_deployment_compatibility( spec=proto_spec, representation=convert_to, deployment_target=minimum_deployment_target, ) del proto_spec gc.collect() # recording metadata: coremltools version, source framework and version if source in {"tensorflow", "tensorflow2"} and (_HAS_TF_1 or _HAS_TF_2): src_pkg_version = "tensorflow=={0}".format(tf.__version__) elif source == "pytorch" and _HAS_TORCH: src_pkg_version = "torch=={0}".format(torch.__version__) else: src_pkg_version = "unknown" model.user_defined_metadata[_METADATA_VERSION] = ct_version model.user_defined_metadata[_METADATA_SOURCE] = src_pkg_version return model
[ "def", "convert", "(", "model", ",", "source", "=", "\"auto\"", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ",", "classifier_config", "=", "None", ",", "minimum_deployment_target", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "minimum_deployment_target", "is", "not", "None", "and", "not", "isinstance", "(", "minimum_deployment_target", ",", "AvailableTarget", ")", ":", "msg", "=", "(", "\"Unrecognized value of argument 'minimum_deployment_target': {}. \"", "\"It needs to be a member of 'coremltools.target' enumeration. \"", "\"For example, coremltools.target.iOS13\"", ")", "raise", "TypeError", "(", "msg", ".", "format", "(", "minimum_deployment_target", ")", ")", "source", "=", "source", ".", "lower", "(", ")", "if", "source", "not", "in", "{", "\"auto\"", ",", "\"tensorflow\"", ",", "\"pytorch\"", "}", ":", "msg", "=", "(", "'Unrecognized value of argument \"source\": {}. '", "'It must be one of [\"auto\", \"tensorflow\", \"pytorch\"].'", ")", "raise", "ValueError", "(", "msg", ".", "format", "(", "source", ")", ")", "def", "raise_if_duplicated", "(", "input_list", ")", ":", "# Detect duplicated inputs", "input_names", "=", "[", "t", ".", "name", "for", "t", "in", "input_list", "if", "t", ".", "name", "is", "not", "None", "]", "dups", "=", "[", "item", "for", "item", ",", "count", "in", "collections", ".", "Counter", "(", "input_names", ")", ".", "items", "(", ")", "if", "count", ">", "1", "]", "if", "len", "(", "dups", ")", ">", "0", ":", "raise", "ValueError", "(", "\"Duplicated inputs: {}\"", ".", "format", "(", "dups", ")", ")", "if", "inputs", "is", "not", "None", ":", "if", "not", "isinstance", "(", "inputs", ",", "list", ")", ":", "msg", "=", "'\"inputs\" must be of type list'", "raise", "ValueError", "(", "msg", ")", "if", "classifier_config", "is", "not", "None", ":", "if", "not", "isinstance", "(", "classifier_config", ",", "ClassifierConfig", ")", ":", "msg", "=", "'\"classifier_config\" must be of type ClassifierConfig'", "raise", "ValueError", "(", "msg", ")", "if", "source", "==", "\"tensorflow\"", "and", "_HAS_TF_2", ":", "source", "=", "\"tensorflow2\"", "if", "source", "==", "\"auto\"", "and", "_HAS_TF_1", ":", "try", ":", "loader", "=", "TF1Loader", "(", "model", ",", "outputs", "=", "outputs", ")", "loader", ".", "_graph_def_from_model", "(", "outputs", "=", "outputs", ")", "source", "=", "\"tensorflow\"", "except", ":", "pass", "if", "source", "==", "\"auto\"", "and", "_HAS_TF_2", ":", "try", ":", "loader", "=", "TF2Loader", "(", "model", ",", "outputs", "=", "outputs", ")", "loader", ".", "_graph_def_from_model", "(", "outputs", "=", "outputs", ")", "source", "=", "\"tensorflow2\"", "except", ":", "pass", "if", "source", "==", "\"auto\"", "and", "_HAS_TORCH", ":", "try", ":", "pytorch_load", "(", "model", ")", "source", "=", "\"pytorch\"", "except", ":", "pass", "if", "source", "==", "\"auto\"", "and", "isinstance", "(", "model", ",", "Program", ")", ":", "source", "=", "\"mil\"", "convert_to", "=", "kwargs", ".", "get", "(", "\"convert_to\"", ",", "\"nn_proto\"", ")", "kwargs", ".", "pop", "(", "\"convert_to\"", ",", "None", ")", "if", "source", "==", "\"auto\"", ":", "msg", "=", "(", "\"Unable to determine the type of the model, i.e. the source framework. \"", "'Please provide the value of argument \"source\", from one of '", "'[\"tensorflow\", \"pytorch\"]. Note that model conversion requires the '", "\"source package that generates the model. Please make sure you have \"", "\"the appropriate version of source package installed. E.g., if you're \"", "\"converting model originally trained with TensorFlow 1.14, make sure \"", "\"you have `tensorflow==1.14` installed.\"", ")", "raise", "ValueError", "(", "msg", ")", "elif", "source", "in", "{", "\"tensorflow\"", ",", "\"tensorflow2\"", "}", ":", "if", "source", "==", "\"tensorflow\"", "and", "not", "_HAS_TF_1", ":", "raise", "ValueError", "(", "'Converter was called with source=\"tensorflow\", but missing tensorflow package'", ")", "if", "inputs", "is", "not", "None", ":", "raise_if_duplicated", "(", "inputs", ")", "if", "inputs", "is", "not", "None", "and", "not", "all", "(", "[", "isinstance", "(", "_input", ",", "InputType", ")", "for", "_input", "in", "inputs", "]", ")", ":", "raise", "ValueError", "(", "\"Input should be a list of TensorType or ImageType\"", ")", "proto_spec", "=", "_convert", "(", "model", ",", "convert_from", "=", "source", ",", "convert_to", "=", "convert_to", ",", "inputs", "=", "inputs", ",", "outputs", "=", "outputs", ",", "classifier_config", "=", "classifier_config", ",", "*", "*", "kwargs", ")", "elif", "source", "==", "\"pytorch\"", ":", "if", "\"example_inputs\"", "in", "kwargs", ":", "msg", "=", "'Unexpected argument \"example_inputs\" found'", "raise", "ValueError", "(", "msg", ")", "def", "_flatten_list", "(", "_inputs", ")", ":", "ret", "=", "[", "]", "for", "_input", "in", "_inputs", ":", "if", "isinstance", "(", "_input", ",", "(", "list", ",", "tuple", ")", ")", ":", "ret", ".", "extend", "(", "_flatten_list", "(", "_input", ")", ")", "elif", "isinstance", "(", "_input", ",", "InputType", ")", ":", "ret", ".", "append", "(", "_input", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown type {} for flattening into InputType.\"", ".", "format", "(", "type", "(", "_input", ")", ")", ")", "return", "ret", "flat_inputs", "=", "_flatten_list", "(", "inputs", ")", "raise_if_duplicated", "(", "flat_inputs", ")", "if", "inputs", "is", "not", "None", "and", "not", "all", "(", "[", "isinstance", "(", "_input", ",", "InputType", ")", "for", "_input", "in", "flat_inputs", "]", ")", ":", "raise", "ValueError", "(", "\"Input should be a list/tuple (or nested lists/tuples) of TensorType or ImageType\"", ")", "if", "outputs", "is", "not", "None", ":", "raise", "ValueError", "(", "\"outputs must not be specified for PyTorch\"", ")", "proto_spec", "=", "_convert", "(", "model", ",", "convert_from", "=", "\"torch\"", ",", "convert_to", "=", "convert_to", ",", "inputs", "=", "inputs", ",", "outputs", "=", "outputs", ",", "classifier_config", "=", "classifier_config", ",", "*", "*", "kwargs", ")", "elif", "source", "==", "\"mil\"", ":", "if", "not", "isinstance", "(", "model", ",", "Program", ")", ":", "msg", "=", "\"Converter was asked to convert MIL input, but input is not a MIL program!\"", "raise", "ValueError", "(", "msg", ")", "proto_spec", "=", "_convert", "(", "model", ",", "convert_from", "=", "\"mil\"", ",", "convert_to", "=", "convert_to", ",", "example_inputs", "=", "inputs", ",", "classifier_config", "=", "classifier_config", ",", "*", "*", "kwargs", ")", "model", "=", "coremltools", ".", "models", ".", "MLModel", "(", "proto_spec", ",", "useCPUOnly", "=", "True", ")", "if", "minimum_deployment_target", "is", "not", "None", ":", "check_deployment_compatibility", "(", "spec", "=", "proto_spec", ",", "representation", "=", "convert_to", ",", "deployment_target", "=", "minimum_deployment_target", ",", ")", "del", "proto_spec", "gc", ".", "collect", "(", ")", "# recording metadata: coremltools version, source framework and version", "if", "source", "in", "{", "\"tensorflow\"", ",", "\"tensorflow2\"", "}", "and", "(", "_HAS_TF_1", "or", "_HAS_TF_2", ")", ":", "src_pkg_version", "=", "\"tensorflow=={0}\"", ".", "format", "(", "tf", ".", "__version__", ")", "elif", "source", "==", "\"pytorch\"", "and", "_HAS_TORCH", ":", "src_pkg_version", "=", "\"torch=={0}\"", ".", "format", "(", "torch", ".", "__version__", ")", "else", ":", "src_pkg_version", "=", "\"unknown\"", "model", ".", "user_defined_metadata", "[", "_METADATA_VERSION", "]", "=", "ct_version", "model", ".", "user_defined_metadata", "[", "_METADATA_SOURCE", "]", "=", "src_pkg_version", "return", "model" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/_converters_entry.py#L35-L339
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/hilbert/tensor_hilbert.py
python
TensorHilbert.__init__
(self, *hilb_spaces: DiscreteHilbert)
r"""Constructs a tensor Hilbert space Args: *hilb: An iterable object containing at least 1 hilbert space.
r"""Constructs a tensor Hilbert space
[ "r", "Constructs", "a", "tensor", "Hilbert", "space" ]
def __init__(self, *hilb_spaces: DiscreteHilbert): r"""Constructs a tensor Hilbert space Args: *hilb: An iterable object containing at least 1 hilbert space. """ self._hilbert_spaces = hilb_spaces self._n_hilbert_spaces = len(hilb_spaces) self._hilbert_i = np.concatenate( [[i for _ in range(hi.size)] for (i, hi) in enumerate(hilb_spaces)] ) self._sizes = tuple([hi.size for hi in hilb_spaces]) shape = np.concatenate([hi.shape for hi in hilb_spaces]) self._cum_sizes = np.cumsum(self._sizes) self._cum_indices = np.concatenate([[0], self._cum_sizes]) self._size = sum(self._sizes) self._delta_indices_i = np.array( [self._cum_indices[i] for i in self._hilbert_i] ) # pre-compute indexing data iff the tensor space is still indexable if all(hi.is_indexable for hi in hilb_spaces) and _is_indexable(shape): self._ns_states = [hi.n_states for hi in self._hilbert_spaces] self._ns_states_r = np.flip(self._ns_states) self._cum_ns_states = np.concatenate([[0], np.cumprod(self._ns_states)]) self._cum_ns_states_r = np.flip( np.cumprod(np.concatenate([[1], np.flip(self._ns_states)]))[:-1] ) self._n_states = np.prod(self._ns_states) super().__init__(shape=shape)
[ "def", "__init__", "(", "self", ",", "*", "hilb_spaces", ":", "DiscreteHilbert", ")", ":", "self", ".", "_hilbert_spaces", "=", "hilb_spaces", "self", ".", "_n_hilbert_spaces", "=", "len", "(", "hilb_spaces", ")", "self", ".", "_hilbert_i", "=", "np", ".", "concatenate", "(", "[", "[", "i", "for", "_", "in", "range", "(", "hi", ".", "size", ")", "]", "for", "(", "i", ",", "hi", ")", "in", "enumerate", "(", "hilb_spaces", ")", "]", ")", "self", ".", "_sizes", "=", "tuple", "(", "[", "hi", ".", "size", "for", "hi", "in", "hilb_spaces", "]", ")", "shape", "=", "np", ".", "concatenate", "(", "[", "hi", ".", "shape", "for", "hi", "in", "hilb_spaces", "]", ")", "self", ".", "_cum_sizes", "=", "np", ".", "cumsum", "(", "self", ".", "_sizes", ")", "self", ".", "_cum_indices", "=", "np", ".", "concatenate", "(", "[", "[", "0", "]", ",", "self", ".", "_cum_sizes", "]", ")", "self", ".", "_size", "=", "sum", "(", "self", ".", "_sizes", ")", "self", ".", "_delta_indices_i", "=", "np", ".", "array", "(", "[", "self", ".", "_cum_indices", "[", "i", "]", "for", "i", "in", "self", ".", "_hilbert_i", "]", ")", "# pre-compute indexing data iff the tensor space is still indexable", "if", "all", "(", "hi", ".", "is_indexable", "for", "hi", "in", "hilb_spaces", ")", "and", "_is_indexable", "(", "shape", ")", ":", "self", ".", "_ns_states", "=", "[", "hi", ".", "n_states", "for", "hi", "in", "self", ".", "_hilbert_spaces", "]", "self", ".", "_ns_states_r", "=", "np", ".", "flip", "(", "self", ".", "_ns_states", ")", "self", ".", "_cum_ns_states", "=", "np", ".", "concatenate", "(", "[", "[", "0", "]", ",", "np", ".", "cumprod", "(", "self", ".", "_ns_states", ")", "]", ")", "self", ".", "_cum_ns_states_r", "=", "np", ".", "flip", "(", "np", ".", "cumprod", "(", "np", ".", "concatenate", "(", "[", "[", "1", "]", ",", "np", ".", "flip", "(", "self", ".", "_ns_states", ")", "]", ")", ")", "[", ":", "-", "1", "]", ")", "self", ".", "_n_states", "=", "np", ".", "prod", "(", "self", ".", "_ns_states", ")", "super", "(", ")", ".", "__init__", "(", "shape", "=", "shape", ")" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/hilbert/tensor_hilbert.py#L44-L76
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/histograms.py
python
_get_outer_edges
(a, range)
return first_edge, last_edge
Determine the outer bin edges to use, from either the data or the range argument
Determine the outer bin edges to use, from either the data or the range argument
[ "Determine", "the", "outer", "bin", "edges", "to", "use", "from", "either", "the", "data", "or", "the", "range", "argument" ]
def _get_outer_edges(a, range): """ Determine the outer bin edges to use, from either the data or the range argument """ if range is not None: first_edge, last_edge = range if first_edge > last_edge: raise ValueError( 'max must be larger than min in range parameter.') if not (np.isfinite(first_edge) and np.isfinite(last_edge)): raise ValueError( "supplied range of [{}, {}] is not finite".format(first_edge, last_edge)) elif a.size == 0: # handle empty arrays. Can't determine range, so use 0-1. first_edge, last_edge = 0, 1 else: first_edge, last_edge = a.min(), a.max() if not (np.isfinite(first_edge) and np.isfinite(last_edge)): raise ValueError( "autodetected range of [{}, {}] is not finite".format(first_edge, last_edge)) # expand empty range to avoid divide by zero if first_edge == last_edge: first_edge = first_edge - 0.5 last_edge = last_edge + 0.5 return first_edge, last_edge
[ "def", "_get_outer_edges", "(", "a", ",", "range", ")", ":", "if", "range", "is", "not", "None", ":", "first_edge", ",", "last_edge", "=", "range", "if", "first_edge", ">", "last_edge", ":", "raise", "ValueError", "(", "'max must be larger than min in range parameter.'", ")", "if", "not", "(", "np", ".", "isfinite", "(", "first_edge", ")", "and", "np", ".", "isfinite", "(", "last_edge", ")", ")", ":", "raise", "ValueError", "(", "\"supplied range of [{}, {}] is not finite\"", ".", "format", "(", "first_edge", ",", "last_edge", ")", ")", "elif", "a", ".", "size", "==", "0", ":", "# handle empty arrays. Can't determine range, so use 0-1.", "first_edge", ",", "last_edge", "=", "0", ",", "1", "else", ":", "first_edge", ",", "last_edge", "=", "a", ".", "min", "(", ")", ",", "a", ".", "max", "(", ")", "if", "not", "(", "np", ".", "isfinite", "(", "first_edge", ")", "and", "np", ".", "isfinite", "(", "last_edge", ")", ")", ":", "raise", "ValueError", "(", "\"autodetected range of [{}, {}] is not finite\"", ".", "format", "(", "first_edge", ",", "last_edge", ")", ")", "# expand empty range to avoid divide by zero", "if", "first_edge", "==", "last_edge", ":", "first_edge", "=", "first_edge", "-", "0.5", "last_edge", "=", "last_edge", "+", "0.5", "return", "first_edge", ",", "last_edge" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/histograms.py#L307-L334