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
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextBuffer.EndRightIndent
(*args, **kwargs)
return _richtext.RichTextBuffer_EndRightIndent(*args, **kwargs)
EndRightIndent(self) -> bool
EndRightIndent(self) -> bool
[ "EndRightIndent", "(", "self", ")", "-", ">", "bool" ]
def EndRightIndent(*args, **kwargs): """EndRightIndent(self) -> bool""" return _richtext.RichTextBuffer_EndRightIndent(*args, **kwargs)
[ "def", "EndRightIndent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_EndRightIndent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2401-L2403
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ListCtrl.DeleteAllItems
(*args, **kwargs)
return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs)
DeleteAllItems(self) -> bool
DeleteAllItems(self) -> bool
[ "DeleteAllItems", "(", "self", ")", "-", ">", "bool" ]
def DeleteAllItems(*args, **kwargs): """DeleteAllItems(self) -> bool""" return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs)
[ "def", "DeleteAllItems", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_DeleteAllItems", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4645-L4647
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/layers/python/layers/feature_column_ops.py
python
sequence_input_from_feature_columns
(columns_to_tensors, feature_columns, weight_collections=None, trainable=True, scope=None)
return _input_from_feature_columns( columns_to_tensors, feature_columns, weight_collections, trainable, scope, output_rank=3, default_name='sequence_input_from_feature_columns')
Builds inputs for sequence models from `FeatureColumn`s. See documentation for `input_from_feature_columns`. The following types of `FeatureColumn` are permitted in `feature_columns`: `_OneHotColumn`, `_EmbeddingColumn`, `_HashedEmbeddingColumn`, `_RealValuedColumn`, `_DataFrameColumn`. In addition, columns in `feature_columns` may not be constructed using any of the following: `HashedEmbeddingColumn`, `BucketizedColumn`, `CrossedColumn`. Args: columns_to_tensors: A mapping from feature column to tensors. 'string' key means a base feature (not-transformed). It can have FeatureColumn as a key too. That means that FeatureColumn is already transformed by input pipeline. For example, `inflow` may have handled transformations. feature_columns: A set containing all the feature columns. All items in the set should be instances of classes derived by FeatureColumn. weight_collections: List of graph collections to which weights are added. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). scope: Optional scope for variable_scope. Returns: A Tensor which can be consumed by hidden layers in the neural network. Raises: ValueError: if FeatureColumn cannot be consumed by a neural network.
Builds inputs for sequence models from `FeatureColumn`s.
[ "Builds", "inputs", "for", "sequence", "models", "from", "FeatureColumn", "s", "." ]
def sequence_input_from_feature_columns(columns_to_tensors, feature_columns, weight_collections=None, trainable=True, scope=None): """Builds inputs for sequence models from `FeatureColumn`s. See documentation for `input_from_feature_columns`. The following types of `FeatureColumn` are permitted in `feature_columns`: `_OneHotColumn`, `_EmbeddingColumn`, `_HashedEmbeddingColumn`, `_RealValuedColumn`, `_DataFrameColumn`. In addition, columns in `feature_columns` may not be constructed using any of the following: `HashedEmbeddingColumn`, `BucketizedColumn`, `CrossedColumn`. Args: columns_to_tensors: A mapping from feature column to tensors. 'string' key means a base feature (not-transformed). It can have FeatureColumn as a key too. That means that FeatureColumn is already transformed by input pipeline. For example, `inflow` may have handled transformations. feature_columns: A set containing all the feature columns. All items in the set should be instances of classes derived by FeatureColumn. weight_collections: List of graph collections to which weights are added. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). scope: Optional scope for variable_scope. Returns: A Tensor which can be consumed by hidden layers in the neural network. Raises: ValueError: if FeatureColumn cannot be consumed by a neural network. """ _check_supported_sequence_columns(feature_columns) _check_forbidden_sequence_columns(feature_columns) return _input_from_feature_columns( columns_to_tensors, feature_columns, weight_collections, trainable, scope, output_rank=3, default_name='sequence_input_from_feature_columns')
[ "def", "sequence_input_from_feature_columns", "(", "columns_to_tensors", ",", "feature_columns", ",", "weight_collections", "=", "None", ",", "trainable", "=", "True", ",", "scope", "=", "None", ")", ":", "_check_supported_sequence_columns", "(", "feature_columns", ")", "_check_forbidden_sequence_columns", "(", "feature_columns", ")", "return", "_input_from_feature_columns", "(", "columns_to_tensors", ",", "feature_columns", ",", "weight_collections", ",", "trainable", ",", "scope", ",", "output_rank", "=", "3", ",", "default_name", "=", "'sequence_input_from_feature_columns'", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/layers/python/layers/feature_column_ops.py#L248-L290
google/mozc
7329757e1ad30e327c1ae823a8302c79482d6b9c
src/win32/installer/postbuilds_win.py
python
RunOrDie
(argv)
Run the command, or die if it failed.
Run the command, or die if it failed.
[ "Run", "the", "command", "or", "die", "if", "it", "failed", "." ]
def RunOrDie(argv): """Run the command, or die if it failed.""" # Rest are the target program name and the parameters, but we special # case if the target program name ends with '.py' if argv[0].endswith('.py'): argv.insert(0, sys.executable) # Inject the python interpreter path. # We don't capture stdout and stderr from Popen. The output will just # be emitted to a terminal or console. process = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() if process.wait() != 0: raise RunOrDieError('\n'.join(['', '==========', ' ERROR: %s' % ' '.join(argv), ' Stdout', out.decode('utf-8'), ' Stderr', err.decode('utf-8'), '==========']))
[ "def", "RunOrDie", "(", "argv", ")", ":", "# Rest are the target program name and the parameters, but we special", "# case if the target program name ends with '.py'", "if", "argv", "[", "0", "]", ".", "endswith", "(", "'.py'", ")", ":", "argv", ".", "insert", "(", "0", ",", "sys", ".", "executable", ")", "# Inject the python interpreter path.", "# We don't capture stdout and stderr from Popen. The output will just", "# be emitted to a terminal or console.", "process", "=", "subprocess", ".", "Popen", "(", "argv", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "process", ".", "communicate", "(", ")", "if", "process", ".", "wait", "(", ")", "!=", "0", ":", "raise", "RunOrDieError", "(", "'\\n'", ".", "join", "(", "[", "''", ",", "'=========='", ",", "' ERROR: %s'", "%", "' '", ".", "join", "(", "argv", ")", ",", "' Stdout'", ",", "out", ".", "decode", "(", "'utf-8'", ")", ",", "' Stderr'", ",", "err", ".", "decode", "(", "'utf-8'", ")", ",", "'=========='", "]", ")", ")" ]
https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/win32/installer/postbuilds_win.py#L107-L125
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/landmines.py
python
clobber_if_necessary
(new_landmines, src_dir, landmines_path)
Does the work of setting, planting, and triggering landmines.
Does the work of setting, planting, and triggering landmines.
[ "Does", "the", "work", "of", "setting", "planting", "and", "triggering", "landmines", "." ]
def clobber_if_necessary(new_landmines, src_dir, landmines_path): """Does the work of setting, planting, and triggering landmines.""" out_dir = get_build_dir(src_dir) try: os.makedirs(out_dir) except OSError as e: if e.errno == errno.EEXIST: pass if os.path.exists(landmines_path): with open(landmines_path, 'r') as f: old_landmines = f.readlines() if old_landmines != new_landmines: old_date = time.ctime(os.stat(landmines_path).st_ctime) diff = difflib.unified_diff(old_landmines, new_landmines, fromfile='old_landmines', tofile='new_landmines', fromfiledate=old_date, tofiledate=time.ctime(), n=0) sys.stdout.write('Clobbering due to:\n') sys.stdout.writelines(diff) sys.stdout.flush() clobber.clobber(out_dir) # Save current set of landmines for next time. with open(landmines_path, 'w') as f: f.writelines(new_landmines)
[ "def", "clobber_if_necessary", "(", "new_landmines", ",", "src_dir", ",", "landmines_path", ")", ":", "out_dir", "=", "get_build_dir", "(", "src_dir", ")", "try", ":", "os", ".", "makedirs", "(", "out_dir", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "EEXIST", ":", "pass", "if", "os", ".", "path", ".", "exists", "(", "landmines_path", ")", ":", "with", "open", "(", "landmines_path", ",", "'r'", ")", "as", "f", ":", "old_landmines", "=", "f", ".", "readlines", "(", ")", "if", "old_landmines", "!=", "new_landmines", ":", "old_date", "=", "time", ".", "ctime", "(", "os", ".", "stat", "(", "landmines_path", ")", ".", "st_ctime", ")", "diff", "=", "difflib", ".", "unified_diff", "(", "old_landmines", ",", "new_landmines", ",", "fromfile", "=", "'old_landmines'", ",", "tofile", "=", "'new_landmines'", ",", "fromfiledate", "=", "old_date", ",", "tofiledate", "=", "time", ".", "ctime", "(", ")", ",", "n", "=", "0", ")", "sys", ".", "stdout", ".", "write", "(", "'Clobbering due to:\\n'", ")", "sys", ".", "stdout", ".", "writelines", "(", "diff", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "clobber", ".", "clobber", "(", "out_dir", ")", "# Save current set of landmines for next time.", "with", "open", "(", "landmines_path", ",", "'w'", ")", "as", "f", ":", "f", ".", "writelines", "(", "new_landmines", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/landmines.py#L55-L80
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/build/src/build/generators.py
python
__construct_really
(project, name, target_type, prop_set, sources)
return result
Attempts to construct target by finding viable generators, running them and selecting the dependency graph.
Attempts to construct target by finding viable generators, running them and selecting the dependency graph.
[ "Attempts", "to", "construct", "target", "by", "finding", "viable", "generators", "running", "them", "and", "selecting", "the", "dependency", "graph", "." ]
def __construct_really (project, name, target_type, prop_set, sources): """ Attempts to construct target by finding viable generators, running them and selecting the dependency graph. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(target_type, basestring) assert isinstance(prop_set, property_set.PropertySet) assert is_iterable_typed(sources, virtual_target.VirtualTarget) viable_generators = find_viable_generators (target_type, prop_set) result = [] dout(" *** %d viable generators" % len (viable_generators)) generators_that_succeeded = [] for g in viable_generators: __active_generators.append(g) r = try_one_generator (project, name, g, target_type, prop_set, sources) del __active_generators[-1] if r: generators_that_succeeded.append(g) if result: output = cStringIO.StringIO() print >>output, "ambiguity found when searching for best transformation" print >>output, "Trying to produce type '%s' from: " % (target_type) for s in sources: print >>output, " - " + s.str() print >>output, "Generators that succeeded:" for g in generators_that_succeeded: print >>output, " - " + g.id() print >>output, "First generator produced: " for t in result[1:]: print >>output, " - " + str(t) print >>output, "Second generator produced:" for t in r[1:]: print >>output, " - " + str(t) get_manager().errors()(output.getvalue()) else: result = r; return result;
[ "def", "__construct_really", "(", "project", ",", "name", ",", "target_type", ",", "prop_set", ",", "sources", ")", ":", "if", "__debug__", ":", "from", ".", "targets", "import", "ProjectTarget", "assert", "isinstance", "(", "project", ",", "ProjectTarget", ")", "assert", "isinstance", "(", "name", ",", "basestring", ")", "or", "name", "is", "None", "assert", "isinstance", "(", "target_type", ",", "basestring", ")", "assert", "isinstance", "(", "prop_set", ",", "property_set", ".", "PropertySet", ")", "assert", "is_iterable_typed", "(", "sources", ",", "virtual_target", ".", "VirtualTarget", ")", "viable_generators", "=", "find_viable_generators", "(", "target_type", ",", "prop_set", ")", "result", "=", "[", "]", "dout", "(", "\" *** %d viable generators\"", "%", "len", "(", "viable_generators", ")", ")", "generators_that_succeeded", "=", "[", "]", "for", "g", "in", "viable_generators", ":", "__active_generators", ".", "append", "(", "g", ")", "r", "=", "try_one_generator", "(", "project", ",", "name", ",", "g", ",", "target_type", ",", "prop_set", ",", "sources", ")", "del", "__active_generators", "[", "-", "1", "]", "if", "r", ":", "generators_that_succeeded", ".", "append", "(", "g", ")", "if", "result", ":", "output", "=", "cStringIO", ".", "StringIO", "(", ")", "print", ">>", "output", ",", "\"ambiguity found when searching for best transformation\"", "print", ">>", "output", ",", "\"Trying to produce type '%s' from: \"", "%", "(", "target_type", ")", "for", "s", "in", "sources", ":", "print", ">>", "output", ",", "\" - \"", "+", "s", ".", "str", "(", ")", "print", ">>", "output", ",", "\"Generators that succeeded:\"", "for", "g", "in", "generators_that_succeeded", ":", "print", ">>", "output", ",", "\" - \"", "+", "g", ".", "id", "(", ")", "print", ">>", "output", ",", "\"First generator produced: \"", "for", "t", "in", "result", "[", "1", ":", "]", ":", "print", ">>", "output", ",", "\" - \"", "+", "str", "(", "t", ")", "print", ">>", "output", ",", "\"Second generator produced:\"", "for", "t", "in", "r", "[", "1", ":", "]", ":", "print", ">>", "output", ",", "\" - \"", "+", "str", "(", "t", ")", "get_manager", "(", ")", ".", "errors", "(", ")", "(", "output", ".", "getvalue", "(", ")", ")", "else", ":", "result", "=", "r", "return", "result" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/generators.py#L1091-L1136
dmlc/nnvm
dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38
python/nnvm/top/tensor.py
python
_compute_binary_scalar
(f)
return _compute
auxiliary function
auxiliary function
[ "auxiliary", "function" ]
def _compute_binary_scalar(f): """auxiliary function""" @tvm.tag_scope(topi.tag.ELEMWISE) def _compute(attrs, x, _): x = x[0] scalar = attrs.get_float("scalar") scalar = tvm.const(scalar, x.dtype) return tvm.compute(x.shape, lambda *i: f(x(*i), scalar)) return _compute
[ "def", "_compute_binary_scalar", "(", "f", ")", ":", "@", "tvm", ".", "tag_scope", "(", "topi", ".", "tag", ".", "ELEMWISE", ")", "def", "_compute", "(", "attrs", ",", "x", ",", "_", ")", ":", "x", "=", "x", "[", "0", "]", "scalar", "=", "attrs", ".", "get_float", "(", "\"scalar\"", ")", "scalar", "=", "tvm", ".", "const", "(", "scalar", ",", "x", ".", "dtype", ")", "return", "tvm", ".", "compute", "(", "x", ".", "shape", ",", "lambda", "*", "i", ":", "f", "(", "x", "(", "*", "i", ")", ",", "scalar", ")", ")", "return", "_compute" ]
https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/top/tensor.py#L16-L24
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/client/timeline.py
python
_ChromeTraceFormatter._create_event
(self, ph, category, name, pid, tid, timestamp)
return event
Creates a new Chrome Trace event. For details of the file format, see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md Args: ph: The type of event - usually a single character. category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. timestamp: The timestamp of this event as a long integer. Returns: A JSON compatible event object.
Creates a new Chrome Trace event.
[ "Creates", "a", "new", "Chrome", "Trace", "event", "." ]
def _create_event(self, ph, category, name, pid, tid, timestamp): """Creates a new Chrome Trace event. For details of the file format, see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md Args: ph: The type of event - usually a single character. category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. timestamp: The timestamp of this event as a long integer. Returns: A JSON compatible event object. """ event = {} event['ph'] = ph event['cat'] = category event['name'] = name event['pid'] = pid event['tid'] = tid event['ts'] = timestamp return event
[ "def", "_create_event", "(", "self", ",", "ph", ",", "category", ",", "name", ",", "pid", ",", "tid", ",", "timestamp", ")", ":", "event", "=", "{", "}", "event", "[", "'ph'", "]", "=", "ph", "event", "[", "'cat'", "]", "=", "category", "event", "[", "'name'", "]", "=", "name", "event", "[", "'pid'", "]", "=", "pid", "event", "[", "'tid'", "]", "=", "tid", "event", "[", "'ts'", "]", "=", "timestamp", "return", "event" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/client/timeline.py#L64-L88
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/tlslite/utils/keyfactory.py
python
generateRSAKey
(bits, implementations=["openssl", "python"])
Generate an RSA key with the specified bit length. @type bits: int @param bits: Desired bit length of the new key's modulus. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: A new RSA private key.
Generate an RSA key with the specified bit length.
[ "Generate", "an", "RSA", "key", "with", "the", "specified", "bit", "length", "." ]
def generateRSAKey(bits, implementations=["openssl", "python"]): """Generate an RSA key with the specified bit length. @type bits: int @param bits: Desired bit length of the new key's modulus. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: A new RSA private key. """ for implementation in implementations: if implementation == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_RSAKey.generate(bits) elif implementation == "python": return Python_RSAKey.generate(bits) raise ValueError("No acceptable implementations")
[ "def", "generateRSAKey", "(", "bits", ",", "implementations", "=", "[", "\"openssl\"", ",", "\"python\"", "]", ")", ":", "for", "implementation", "in", "implementations", ":", "if", "implementation", "==", "\"openssl\"", "and", "cryptomath", ".", "m2cryptoLoaded", ":", "return", "OpenSSL_RSAKey", ".", "generate", "(", "bits", ")", "elif", "implementation", "==", "\"python\"", ":", "return", "Python_RSAKey", ".", "generate", "(", "bits", ")", "raise", "ValueError", "(", "\"No acceptable implementations\"", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/tlslite/utils/keyfactory.py#L22-L36
twhui/LiteFlowNet
00925aebf2db9ac50f4b1666f718688b10dd10d1
python/caffe/detector.py
python
Detector.configure_crop
(self, context_pad)
Configure crop dimensions and amount of context for cropping. If context is included, make the special input mean for context padding. Parameters ---------- context_pad : amount of context for cropping.
Configure crop dimensions and amount of context for cropping. If context is included, make the special input mean for context padding.
[ "Configure", "crop", "dimensions", "and", "amount", "of", "context", "for", "cropping", ".", "If", "context", "is", "included", "make", "the", "special", "input", "mean", "for", "context", "padding", "." ]
def configure_crop(self, context_pad): """ Configure crop dimensions and amount of context for cropping. If context is included, make the special input mean for context padding. Parameters ---------- context_pad : amount of context for cropping. """ # crop dimensions in_ = self.inputs[0] tpose = self.transformer.transpose[in_] inv_tpose = [tpose[t] for t in tpose] self.crop_dims = np.array(self.blobs[in_].data.shape[1:])[inv_tpose] #.transpose(inv_tpose) # context padding self.context_pad = context_pad if self.context_pad: in_ = self.inputs[0] transpose = self.transformer.transpose.get(in_) channel_order = self.transformer.channel_swap.get(in_) raw_scale = self.transformer.raw_scale.get(in_) # Padding context crops needs the mean in unprocessed input space. mean = self.transformer.mean.get(in_) if mean is not None: inv_transpose = [transpose[t] for t in transpose] crop_mean = mean.copy().transpose(inv_transpose) if channel_order is not None: channel_order_inverse = [channel_order.index(i) for i in range(crop_mean.shape[2])] crop_mean = crop_mean[:, :, channel_order_inverse] if raw_scale is not None: crop_mean /= raw_scale self.crop_mean = crop_mean else: self.crop_mean = np.zeros(self.crop_dims, dtype=np.float32)
[ "def", "configure_crop", "(", "self", ",", "context_pad", ")", ":", "# crop dimensions", "in_", "=", "self", ".", "inputs", "[", "0", "]", "tpose", "=", "self", ".", "transformer", ".", "transpose", "[", "in_", "]", "inv_tpose", "=", "[", "tpose", "[", "t", "]", "for", "t", "in", "tpose", "]", "self", ".", "crop_dims", "=", "np", ".", "array", "(", "self", ".", "blobs", "[", "in_", "]", ".", "data", ".", "shape", "[", "1", ":", "]", ")", "[", "inv_tpose", "]", "#.transpose(inv_tpose)", "# context padding", "self", ".", "context_pad", "=", "context_pad", "if", "self", ".", "context_pad", ":", "in_", "=", "self", ".", "inputs", "[", "0", "]", "transpose", "=", "self", ".", "transformer", ".", "transpose", ".", "get", "(", "in_", ")", "channel_order", "=", "self", ".", "transformer", ".", "channel_swap", ".", "get", "(", "in_", ")", "raw_scale", "=", "self", ".", "transformer", ".", "raw_scale", ".", "get", "(", "in_", ")", "# Padding context crops needs the mean in unprocessed input space.", "mean", "=", "self", ".", "transformer", ".", "mean", ".", "get", "(", "in_", ")", "if", "mean", "is", "not", "None", ":", "inv_transpose", "=", "[", "transpose", "[", "t", "]", "for", "t", "in", "transpose", "]", "crop_mean", "=", "mean", ".", "copy", "(", ")", ".", "transpose", "(", "inv_transpose", ")", "if", "channel_order", "is", "not", "None", ":", "channel_order_inverse", "=", "[", "channel_order", ".", "index", "(", "i", ")", "for", "i", "in", "range", "(", "crop_mean", ".", "shape", "[", "2", "]", ")", "]", "crop_mean", "=", "crop_mean", "[", ":", ",", ":", ",", "channel_order_inverse", "]", "if", "raw_scale", "is", "not", "None", ":", "crop_mean", "/=", "raw_scale", "self", ".", "crop_mean", "=", "crop_mean", "else", ":", "self", ".", "crop_mean", "=", "np", ".", "zeros", "(", "self", ".", "crop_dims", ",", "dtype", "=", "np", ".", "float32", ")" ]
https://github.com/twhui/LiteFlowNet/blob/00925aebf2db9ac50f4b1666f718688b10dd10d1/python/caffe/detector.py#L181-L216
Harick1/caffe-yolo
eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3
python/caffe/io.py
python
Transformer.set_transpose
(self, in_, order)
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. Parameters ---------- in_ : which input to assign this channel order order : the order to transpose the dimensions
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model.
[ "Set", "the", "input", "channel", "order", "for", "e", ".", "g", ".", "RGB", "to", "BGR", "conversion", "as", "needed", "for", "the", "reference", "ImageNet", "model", "." ]
def set_transpose(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. Parameters ---------- in_ : which input to assign this channel order order : the order to transpose the dimensions """ self.__check_input(in_) if len(order) != len(self.inputs[in_]) - 1: raise Exception('Transpose order needs to have the same number of ' 'dimensions as the input.') self.transpose[in_] = order
[ "def", "set_transpose", "(", "self", ",", "in_", ",", "order", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "if", "len", "(", "order", ")", "!=", "len", "(", "self", ".", "inputs", "[", "in_", "]", ")", "-", "1", ":", "raise", "Exception", "(", "'Transpose order needs to have the same number of '", "'dimensions as the input.'", ")", "self", ".", "transpose", "[", "in_", "]", "=", "order" ]
https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/python/caffe/io.py#L187-L201
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/base.py
python
TensorFlowEstimator.predict_proba
(self, x, batch_size=None)
return self._predict(x, batch_size=batch_size)
Predict class probability of the input samples `x`. Args: x: array-like matrix, [n_samples, n_features...] or iterator. batch_size: If test set is too big, use batch size to split it into mini batches. By default the batch_size member variable is used. Returns: y: array of shape [n_samples, n_classes]. The predicted probabilities for each class.
Predict class probability of the input samples `x`.
[ "Predict", "class", "probability", "of", "the", "input", "samples", "x", "." ]
def predict_proba(self, x, batch_size=None): """Predict class probability of the input samples `x`. Args: x: array-like matrix, [n_samples, n_features...] or iterator. batch_size: If test set is too big, use batch size to split it into mini batches. By default the batch_size member variable is used. Returns: y: array of shape [n_samples, n_classes]. The predicted probabilities for each class. """ return self._predict(x, batch_size=batch_size)
[ "def", "predict_proba", "(", "self", ",", "x", ",", "batch_size", "=", "None", ")", ":", "return", "self", ".", "_predict", "(", "x", ",", "batch_size", "=", "batch_size", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/base.py#L245-L257
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/variables.py
python
Variable.initial_value
(self)
return self._initial_value
Returns the Tensor used as the initial value for the variable. Note that this is different from `initialized_value()` which runs the op that initializes the variable before returning its value. This method returns the tensor that is used by the op that initializes the variable. Returns: A `Tensor`.
Returns the Tensor used as the initial value for the variable.
[ "Returns", "the", "Tensor", "used", "as", "the", "initial", "value", "for", "the", "variable", "." ]
def initial_value(self): """Returns the Tensor used as the initial value for the variable. Note that this is different from `initialized_value()` which runs the op that initializes the variable before returning its value. This method returns the tensor that is used by the op that initializes the variable. Returns: A `Tensor`. """ return self._initial_value
[ "def", "initial_value", "(", "self", ")", ":", "return", "self", ".", "_initial_value" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/variables.py#L475-L486
lmb-freiburg/ogn
974f72ef4bf840d6f6693d22d1843a79223e77ce
examples/pycaffe/tools.py
python
CaffeSolver.add_from_file
(self, filepath)
Reads a caffe solver prototxt file and updates the Caffesolver instance parameters.
Reads a caffe solver prototxt file and updates the Caffesolver instance parameters.
[ "Reads", "a", "caffe", "solver", "prototxt", "file", "and", "updates", "the", "Caffesolver", "instance", "parameters", "." ]
def add_from_file(self, filepath): """ Reads a caffe solver prototxt file and updates the Caffesolver instance parameters. """ with open(filepath, 'r') as f: for line in f: if line[0] == '#': continue splitLine = line.split(':') self.sp[splitLine[0].strip()] = splitLine[1].strip()
[ "def", "add_from_file", "(", "self", ",", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "line", "[", "0", "]", "==", "'#'", ":", "continue", "splitLine", "=", "line", ".", "split", "(", "':'", ")", "self", ".", "sp", "[", "splitLine", "[", "0", "]", ".", "strip", "(", ")", "]", "=", "splitLine", "[", "1", "]", ".", "strip", "(", ")" ]
https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/examples/pycaffe/tools.py#L101-L111
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Point2D.__isub__
(*args, **kwargs)
return _core_.Point2D___isub__(*args, **kwargs)
__isub__(self, Point2D pt) -> Point2D
__isub__(self, Point2D pt) -> Point2D
[ "__isub__", "(", "self", "Point2D", "pt", ")", "-", ">", "Point2D" ]
def __isub__(*args, **kwargs): """__isub__(self, Point2D pt) -> Point2D""" return _core_.Point2D___isub__(*args, **kwargs)
[ "def", "__isub__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Point2D___isub__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L1722-L1724
MTG/gaia
0f7214dbdec6f9b651ca34211824841ffba0bc77
src/doc/doxy2swig.py
python
Doxy2SWIG.extract_text
(self, node)
return ret
Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list.
Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list.
[ "Return", "the", "string", "representation", "of", "the", "node", "or", "list", "of", "nodes", "by", "parsing", "the", "subnodes", "but", "returning", "the", "result", "as", "a", "string", "instead", "of", "adding", "it", "to", "self", ".", "pieces", ".", "Note", "that", "this", "allows", "extracting", "text", "even", "if", "the", "node", "is", "in", "the", "ignore", "list", "." ]
def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret
[ "def", "extract_text", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "(", "list", ",", "tuple", ")", ")", ":", "node", "=", "[", "node", "]", "pieces", ",", "self", ".", "pieces", "=", "self", ".", "pieces", ",", "[", "''", "]", "for", "n", "in", "node", ":", "for", "sn", "in", "n", ".", "childNodes", ":", "self", ".", "parse", "(", "sn", ")", "ret", "=", "''", ".", "join", "(", "self", ".", "pieces", ")", "self", ".", "pieces", "=", "pieces", "return", "ret" ]
https://github.com/MTG/gaia/blob/0f7214dbdec6f9b651ca34211824841ffba0bc77/src/doc/doxy2swig.py#L320-L333
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/InstanceDictHeader.py
python
InstanceDictHeader.addVisitor
(self, visitor)
Add a visitor to the list of visitors. @param visitor: the visitor to add, must be derived from AbstractVisitor.
Add a visitor to the list of visitors.
[ "Add", "a", "visitor", "to", "the", "list", "of", "visitors", "." ]
def addVisitor(self, visitor): """ Add a visitor to the list of visitors. @param visitor: the visitor to add, must be derived from AbstractVisitor. """ if issubclass(visitor.__class__, AbstractVisitor.AbstractVisitor): self.__visitor_list.append(visitor) else: DEBUG.error( "InstanceDictHeaderVisit.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!" ) raise Exception( "InstanceDictHeaderVisit.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!" )
[ "def", "addVisitor", "(", "self", ",", "visitor", ")", ":", "if", "issubclass", "(", "visitor", ".", "__class__", ",", "AbstractVisitor", ".", "AbstractVisitor", ")", ":", "self", ".", "__visitor_list", ".", "append", "(", "visitor", ")", "else", ":", "DEBUG", ".", "error", "(", "\"InstanceDictHeaderVisit.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!\"", ")", "raise", "Exception", "(", "\"InstanceDictHeaderVisit.addVisitor(v) - the given visitor is not a subclass of AbstractVisitor!\"", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/InstanceDictHeader.py#L86-L99
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
vis/python/athena_read.py
python
error_dat
(filename, **kwargs)
return data
Wrapper to np.loadtxt() for applying optional checks used in regression tests
Wrapper to np.loadtxt() for applying optional checks used in regression tests
[ "Wrapper", "to", "np", ".", "loadtxt", "()", "for", "applying", "optional", "checks", "used", "in", "regression", "tests" ]
def error_dat(filename, **kwargs): """Wrapper to np.loadtxt() for applying optional checks used in regression tests""" data = np.loadtxt(filename, dtype=np.float64, ndmin=2, # prevent NumPy from squeezing singleton dimensions **kwargs) if check_nan_flag: check_nan(data) return data
[ "def", "error_dat", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "data", "=", "np", ".", "loadtxt", "(", "filename", ",", "dtype", "=", "np", ".", "float64", ",", "ndmin", "=", "2", ",", "# prevent NumPy from squeezing singleton dimensions", "*", "*", "kwargs", ")", "if", "check_nan_flag", ":", "check_nan", "(", "data", ")", "return", "data" ]
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/vis/python/athena_read.py#L29-L37
facebookincubator/mvfst
034a40c797485113d00127852d4df3c5bb44b3ed
build/fbcode_builder/fbcode_builder.py
python
FBCodeBuilder.diagnostics
(self)
return self.step( "Diagnostics", [ self.comment("Builder {0}".format(repr(self))), self.run(ShellQuoted("hostname")), self.run(ShellQuoted("cat /etc/issue || echo no /etc/issue")), self.run(ShellQuoted("g++ --version || echo g++ not installed")), self.run(ShellQuoted("cmake --version || echo cmake not installed")), ], )
Log some system diagnostics before/after setup for ease of debugging
Log some system diagnostics before/after setup for ease of debugging
[ "Log", "some", "system", "diagnostics", "before", "/", "after", "setup", "for", "ease", "of", "debugging" ]
def diagnostics(self): "Log some system diagnostics before/after setup for ease of debugging" # The builder's repr is not used in a command to avoid pointlessly # invalidating Docker's build cache. return self.step( "Diagnostics", [ self.comment("Builder {0}".format(repr(self))), self.run(ShellQuoted("hostname")), self.run(ShellQuoted("cat /etc/issue || echo no /etc/issue")), self.run(ShellQuoted("g++ --version || echo g++ not installed")), self.run(ShellQuoted("cmake --version || echo cmake not installed")), ], )
[ "def", "diagnostics", "(", "self", ")", ":", "# The builder's repr is not used in a command to avoid pointlessly", "# invalidating Docker's build cache.", "return", "self", ".", "step", "(", "\"Diagnostics\"", ",", "[", "self", ".", "comment", "(", "\"Builder {0}\"", ".", "format", "(", "repr", "(", "self", ")", ")", ")", ",", "self", ".", "run", "(", "ShellQuoted", "(", "\"hostname\"", ")", ")", ",", "self", ".", "run", "(", "ShellQuoted", "(", "\"cat /etc/issue || echo no /etc/issue\"", ")", ")", ",", "self", ".", "run", "(", "ShellQuoted", "(", "\"g++ --version || echo g++ not installed\"", ")", ")", ",", "self", ".", "run", "(", "ShellQuoted", "(", "\"cmake --version || echo cmake not installed\"", ")", ")", ",", "]", ",", ")" ]
https://github.com/facebookincubator/mvfst/blob/034a40c797485113d00127852d4df3c5bb44b3ed/build/fbcode_builder/fbcode_builder.py#L153-L166
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/training/input.py
python
string_input_producer
(string_tensor, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None, cancel_op=None)
Output strings (e.g. filenames) to a queue for an input pipeline. Note: if `num_epochs` is not `None`, this function creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables. Args: string_tensor: A 1-D string tensor with the strings to produce. num_epochs: An integer (optional). If specified, `string_input_producer` produces each string from `string_tensor` `num_epochs` times before generating an `OutOfRange` error. If not specified, `string_input_producer` can cycle through the strings in `string_tensor` an unlimited number of times. shuffle: Boolean. If true, the strings are randomly shuffled within each epoch. seed: An integer (optional). Seed used if shuffle == True. capacity: An integer. Sets the queue capacity. shared_name: (optional). If set, this queue will be shared under the given name across multiple sessions. All sessions open to the device which has this queue will be able to access it via the shared_name. Using this in a distributed setting means each name will only be seen by one of the sessions which has access to this operation. name: A name for the operations (optional). cancel_op: Cancel op for the queue (optional). Returns: A queue with the output strings. A `QueueRunner` for the Queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. Raises: ValueError: If the string_tensor is a null Python list. At runtime, will fail with an assertion if string_tensor becomes a null tensor.
Output strings (e.g. filenames) to a queue for an input pipeline.
[ "Output", "strings", "(", "e", ".", "g", ".", "filenames", ")", "to", "a", "queue", "for", "an", "input", "pipeline", "." ]
def string_input_producer(string_tensor, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None, cancel_op=None): """Output strings (e.g. filenames) to a queue for an input pipeline. Note: if `num_epochs` is not `None`, this function creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables. Args: string_tensor: A 1-D string tensor with the strings to produce. num_epochs: An integer (optional). If specified, `string_input_producer` produces each string from `string_tensor` `num_epochs` times before generating an `OutOfRange` error. If not specified, `string_input_producer` can cycle through the strings in `string_tensor` an unlimited number of times. shuffle: Boolean. If true, the strings are randomly shuffled within each epoch. seed: An integer (optional). Seed used if shuffle == True. capacity: An integer. Sets the queue capacity. shared_name: (optional). If set, this queue will be shared under the given name across multiple sessions. All sessions open to the device which has this queue will be able to access it via the shared_name. Using this in a distributed setting means each name will only be seen by one of the sessions which has access to this operation. name: A name for the operations (optional). cancel_op: Cancel op for the queue (optional). Returns: A queue with the output strings. A `QueueRunner` for the Queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. Raises: ValueError: If the string_tensor is a null Python list. At runtime, will fail with an assertion if string_tensor becomes a null tensor. """ not_null_err = "string_input_producer requires a non-null input tensor" if not isinstance(string_tensor, ops.Tensor) and not string_tensor: raise ValueError(not_null_err) with ops.name_scope(name, "input_producer", [string_tensor]) as name: string_tensor = ops.convert_to_tensor(string_tensor, dtype=dtypes.string) with ops.control_dependencies([ control_flow_ops.Assert( math_ops.greater(array_ops.size(string_tensor), 0), [not_null_err])]): string_tensor = array_ops.identity(string_tensor) return input_producer( input_tensor=string_tensor, element_shape=[], num_epochs=num_epochs, shuffle=shuffle, seed=seed, capacity=capacity, shared_name=shared_name, name=name, summary_name="fraction_of_%d_full" % capacity, cancel_op=cancel_op)
[ "def", "string_input_producer", "(", "string_tensor", ",", "num_epochs", "=", "None", ",", "shuffle", "=", "True", ",", "seed", "=", "None", ",", "capacity", "=", "32", ",", "shared_name", "=", "None", ",", "name", "=", "None", ",", "cancel_op", "=", "None", ")", ":", "not_null_err", "=", "\"string_input_producer requires a non-null input tensor\"", "if", "not", "isinstance", "(", "string_tensor", ",", "ops", ".", "Tensor", ")", "and", "not", "string_tensor", ":", "raise", "ValueError", "(", "not_null_err", ")", "with", "ops", ".", "name_scope", "(", "name", ",", "\"input_producer\"", ",", "[", "string_tensor", "]", ")", "as", "name", ":", "string_tensor", "=", "ops", ".", "convert_to_tensor", "(", "string_tensor", ",", "dtype", "=", "dtypes", ".", "string", ")", "with", "ops", ".", "control_dependencies", "(", "[", "control_flow_ops", ".", "Assert", "(", "math_ops", ".", "greater", "(", "array_ops", ".", "size", "(", "string_tensor", ")", ",", "0", ")", ",", "[", "not_null_err", "]", ")", "]", ")", ":", "string_tensor", "=", "array_ops", ".", "identity", "(", "string_tensor", ")", "return", "input_producer", "(", "input_tensor", "=", "string_tensor", ",", "element_shape", "=", "[", "]", ",", "num_epochs", "=", "num_epochs", ",", "shuffle", "=", "shuffle", ",", "seed", "=", "seed", ",", "capacity", "=", "capacity", ",", "shared_name", "=", "shared_name", ",", "name", "=", "name", ",", "summary_name", "=", "\"fraction_of_%d_full\"", "%", "capacity", ",", "cancel_op", "=", "cancel_op", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/input.py#L180-L241
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/plotting/_misc.py
python
deregister
()
Remove pandas formatters and converters. Removes the custom converters added by :func:`register`. This attempts to set the state of the registry back to the state before pandas registered its own units. Converters for pandas' own types like Timestamp and Period are removed completely. Converters for types pandas overwrites, like ``datetime.datetime``, are restored to their original value. See Also -------- register_matplotlib_converters : Register pandas formatters and converters with matplotlib.
Remove pandas formatters and converters.
[ "Remove", "pandas", "formatters", "and", "converters", "." ]
def deregister(): """ Remove pandas formatters and converters. Removes the custom converters added by :func:`register`. This attempts to set the state of the registry back to the state before pandas registered its own units. Converters for pandas' own types like Timestamp and Period are removed completely. Converters for types pandas overwrites, like ``datetime.datetime``, are restored to their original value. See Also -------- register_matplotlib_converters : Register pandas formatters and converters with matplotlib. """ plot_backend = _get_plot_backend("matplotlib") plot_backend.deregister()
[ "def", "deregister", "(", ")", ":", "plot_backend", "=", "_get_plot_backend", "(", "\"matplotlib\"", ")", "plot_backend", ".", "deregister", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/plotting/_misc.py#L52-L69
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/internal/enum_type_wrapper.py
python
EnumTypeWrapper.Value
(self, name)
Returns the value coresponding to the given enum name.
Returns the value coresponding to the given enum name.
[ "Returns", "the", "value", "coresponding", "to", "the", "given", "enum", "name", "." ]
def Value(self, name): """Returns the value coresponding to the given enum name.""" if name in self._enum_type.values_by_name: return self._enum_type.values_by_name[name].number raise ValueError('Enum %s has no value defined for name %s' % ( self._enum_type.name, name))
[ "def", "Value", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_enum_type", ".", "values_by_name", ":", "return", "self", ".", "_enum_type", ".", "values_by_name", "[", "name", "]", ".", "number", "raise", "ValueError", "(", "'Enum %s has no value defined for name %s'", "%", "(", "self", ".", "_enum_type", ".", "name", ",", "name", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/enum_type_wrapper.py#L58-L63
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/SimpleXMLRPCServer.py
python
SimpleXMLRPCDispatcher.system_listMethods
(self)
return methods
system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.
system.listMethods() => ['add', 'subtract', 'multiple']
[ "system", ".", "listMethods", "()", "=", ">", "[", "add", "subtract", "multiple", "]" ]
def system_listMethods(self): """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.""" methods = self.funcs.keys() if self.instance is not None: # Instance can implement _listMethod to return a list of # methods if hasattr(self.instance, '_listMethods'): methods = remove_duplicates( methods + self.instance._listMethods() ) # if the instance has a _dispatch method then we # don't have enough information to provide a list # of methods elif not hasattr(self.instance, '_dispatch'): methods = remove_duplicates( methods + list_public_methods(self.instance) ) methods.sort() return methods
[ "def", "system_listMethods", "(", "self", ")", ":", "methods", "=", "self", ".", "funcs", ".", "keys", "(", ")", "if", "self", ".", "instance", "is", "not", "None", ":", "# Instance can implement _listMethod to return a list of", "# methods", "if", "hasattr", "(", "self", ".", "instance", ",", "'_listMethods'", ")", ":", "methods", "=", "remove_duplicates", "(", "methods", "+", "self", ".", "instance", ".", "_listMethods", "(", ")", ")", "# if the instance has a _dispatch method then we", "# don't have enough information to provide a list", "# of methods", "elif", "not", "hasattr", "(", "self", ".", "instance", ",", "'_dispatch'", ")", ":", "methods", "=", "remove_duplicates", "(", "methods", "+", "list_public_methods", "(", "self", ".", "instance", ")", ")", "methods", ".", "sort", "(", ")", "return", "methods" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/SimpleXMLRPCServer.py#L278-L299
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/MSVSVersion.py
python
VisualStudioVersion.ProjectVersion
(self)
return self.project_version
Get the version number of the vcproj or vcxproj files.
Get the version number of the vcproj or vcxproj files.
[ "Get", "the", "version", "number", "of", "the", "vcproj", "or", "vcxproj", "files", "." ]
def ProjectVersion(self): """Get the version number of the vcproj or vcxproj files.""" return self.project_version
[ "def", "ProjectVersion", "(", "self", ")", ":", "return", "self", ".", "project_version" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/MSVSVersion.py#L52-L54
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py
python
Doc.getdocloc
(self, object)
return docloc
Return the location of module docs or None
Return the location of module docs or None
[ "Return", "the", "location", "of", "module", "docs", "or", "None" ]
def getdocloc(self, object): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", "http://docs.python.org/library") basedir = os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3]) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith("http://"): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__) else: docloc = os.path.join(docloc, object.__name__ + ".html") else: docloc = None return docloc
[ "def", "getdocloc", "(", "self", ",", "object", ")", ":", "try", ":", "file", "=", "inspect", ".", "getabsfile", "(", "object", ")", "except", "TypeError", ":", "file", "=", "'(built-in)'", "docloc", "=", "os", ".", "environ", ".", "get", "(", "\"PYTHONDOCS\"", ",", "\"http://docs.python.org/library\"", ")", "basedir", "=", "os", ".", "path", ".", "join", "(", "sys", ".", "exec_prefix", ",", "\"lib\"", ",", "\"python\"", "+", "sys", ".", "version", "[", "0", ":", "3", "]", ")", "if", "(", "isinstance", "(", "object", ",", "type", "(", "os", ")", ")", "and", "(", "object", ".", "__name__", "in", "(", "'errno'", ",", "'exceptions'", ",", "'gc'", ",", "'imp'", ",", "'marshal'", ",", "'posix'", ",", "'signal'", ",", "'sys'", ",", "'thread'", ",", "'zipimport'", ")", "or", "(", "file", ".", "startswith", "(", "basedir", ")", "and", "not", "file", ".", "startswith", "(", "os", ".", "path", ".", "join", "(", "basedir", ",", "'site-packages'", ")", ")", ")", ")", "and", "object", ".", "__name__", "not", "in", "(", "'xml.etree'", ",", "'test.pydoc_mod'", ")", ")", ":", "if", "docloc", ".", "startswith", "(", "\"http://\"", ")", ":", "docloc", "=", "\"%s/%s\"", "%", "(", "docloc", ".", "rstrip", "(", "\"/\"", ")", ",", "object", ".", "__name__", ")", "else", ":", "docloc", "=", "os", ".", "path", ".", "join", "(", "docloc", ",", "object", ".", "__name__", "+", "\".html\"", ")", "else", ":", "docloc", "=", "None", "return", "docloc" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py#L345-L370
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/rgw.py
python
task
(ctx, config)
For example, to run rgw on all clients:: tasks: - ceph: - rgw: To only run on certain clients:: tasks: - ceph: - rgw: [client.0, client.3] or tasks: - ceph: - rgw: client.0: client.3: To run radosgw through valgrind: tasks: - ceph: - rgw: client.0: valgrind: [--tool=memcheck] client.3: valgrind: [--tool=memcheck] To configure data or index pool pg_size: overrides: rgw: data_pool_pg_size: 256 index_pool_pg_size: 128
For example, to run rgw on all clients::
[ "For", "example", "to", "run", "rgw", "on", "all", "clients", "::" ]
def task(ctx, config): """ For example, to run rgw on all clients:: tasks: - ceph: - rgw: To only run on certain clients:: tasks: - ceph: - rgw: [client.0, client.3] or tasks: - ceph: - rgw: client.0: client.3: To run radosgw through valgrind: tasks: - ceph: - rgw: client.0: valgrind: [--tool=memcheck] client.3: valgrind: [--tool=memcheck] To configure data or index pool pg_size: overrides: rgw: data_pool_pg_size: 256 index_pool_pg_size: 128 """ if config is None: config = dict(('client.{id}'.format(id=id_), None) for id_ in teuthology.all_roles_of_type( ctx.cluster, 'client')) elif isinstance(config, list): config = dict((name, None) for name in config) clients = config.keys() # http://tracker.ceph.com/issues/20417 overrides = ctx.config.get('overrides', {}) teuthology.deep_merge(config, overrides.get('rgw', {})) ctx.rgw = argparse.Namespace() ctx.rgw.ec_data_pool = bool(config.pop('ec-data-pool', False)) ctx.rgw.erasure_code_profile = config.pop('erasure_code_profile', {}) ctx.rgw.cache_pools = bool(config.pop('cache-pools', False)) ctx.rgw.frontend = config.pop('frontend', 'beast') ctx.rgw.compression_type = config.pop('compression type', None) ctx.rgw.storage_classes = config.pop('storage classes', None) default_cert = config.pop('ssl certificate', None) ctx.rgw.data_pool_pg_size = config.pop('data_pool_pg_size', 64) ctx.rgw.index_pool_pg_size = config.pop('index_pool_pg_size', 64) ctx.rgw.datacache = bool(config.pop('datacache', False)) ctx.rgw.datacache_path = config.pop('datacache_path', None) ctx.rgw.config = config log.debug("config is {}".format(config)) log.debug("client list is {}".format(clients)) ctx.rgw.role_endpoints = assign_endpoints(ctx, config, default_cert) subtasks = [ lambda: create_pools(ctx=ctx, clients=clients), ] if ctx.rgw.compression_type: subtasks.extend([ lambda: configure_compression(ctx=ctx, clients=clients, compression=ctx.rgw.compression_type), ]) if ctx.rgw.datacache: subtasks.extend([ lambda: configure_datacache(ctx=ctx, clients=clients, datacache_path=ctx.rgw.datacache_path), ]) if ctx.rgw.storage_classes: subtasks.extend([ lambda: configure_storage_classes(ctx=ctx, clients=clients, storage_classes=ctx.rgw.storage_classes), ]) subtasks.extend([ lambda: start_rgw(ctx=ctx, config=config, clients=clients), ]) with contextutil.nested(*subtasks): yield
[ "def", "task", "(", "ctx", ",", "config", ")", ":", "if", "config", "is", "None", ":", "config", "=", "dict", "(", "(", "'client.{id}'", ".", "format", "(", "id", "=", "id_", ")", ",", "None", ")", "for", "id_", "in", "teuthology", ".", "all_roles_of_type", "(", "ctx", ".", "cluster", ",", "'client'", ")", ")", "elif", "isinstance", "(", "config", ",", "list", ")", ":", "config", "=", "dict", "(", "(", "name", ",", "None", ")", "for", "name", "in", "config", ")", "clients", "=", "config", ".", "keys", "(", ")", "# http://tracker.ceph.com/issues/20417", "overrides", "=", "ctx", ".", "config", ".", "get", "(", "'overrides'", ",", "{", "}", ")", "teuthology", ".", "deep_merge", "(", "config", ",", "overrides", ".", "get", "(", "'rgw'", ",", "{", "}", ")", ")", "ctx", ".", "rgw", "=", "argparse", ".", "Namespace", "(", ")", "ctx", ".", "rgw", ".", "ec_data_pool", "=", "bool", "(", "config", ".", "pop", "(", "'ec-data-pool'", ",", "False", ")", ")", "ctx", ".", "rgw", ".", "erasure_code_profile", "=", "config", ".", "pop", "(", "'erasure_code_profile'", ",", "{", "}", ")", "ctx", ".", "rgw", ".", "cache_pools", "=", "bool", "(", "config", ".", "pop", "(", "'cache-pools'", ",", "False", ")", ")", "ctx", ".", "rgw", ".", "frontend", "=", "config", ".", "pop", "(", "'frontend'", ",", "'beast'", ")", "ctx", ".", "rgw", ".", "compression_type", "=", "config", ".", "pop", "(", "'compression type'", ",", "None", ")", "ctx", ".", "rgw", ".", "storage_classes", "=", "config", ".", "pop", "(", "'storage classes'", ",", "None", ")", "default_cert", "=", "config", ".", "pop", "(", "'ssl certificate'", ",", "None", ")", "ctx", ".", "rgw", ".", "data_pool_pg_size", "=", "config", ".", "pop", "(", "'data_pool_pg_size'", ",", "64", ")", "ctx", ".", "rgw", ".", "index_pool_pg_size", "=", "config", ".", "pop", "(", "'index_pool_pg_size'", ",", "64", ")", "ctx", ".", "rgw", ".", "datacache", "=", "bool", "(", "config", ".", "pop", "(", "'datacache'", ",", "False", ")", ")", "ctx", ".", "rgw", ".", "datacache_path", "=", "config", ".", "pop", "(", "'datacache_path'", ",", "None", ")", "ctx", ".", "rgw", ".", "config", "=", "config", "log", ".", "debug", "(", "\"config is {}\"", ".", "format", "(", "config", ")", ")", "log", ".", "debug", "(", "\"client list is {}\"", ".", "format", "(", "clients", ")", ")", "ctx", ".", "rgw", ".", "role_endpoints", "=", "assign_endpoints", "(", "ctx", ",", "config", ",", "default_cert", ")", "subtasks", "=", "[", "lambda", ":", "create_pools", "(", "ctx", "=", "ctx", ",", "clients", "=", "clients", ")", ",", "]", "if", "ctx", ".", "rgw", ".", "compression_type", ":", "subtasks", ".", "extend", "(", "[", "lambda", ":", "configure_compression", "(", "ctx", "=", "ctx", ",", "clients", "=", "clients", ",", "compression", "=", "ctx", ".", "rgw", ".", "compression_type", ")", ",", "]", ")", "if", "ctx", ".", "rgw", ".", "datacache", ":", "subtasks", ".", "extend", "(", "[", "lambda", ":", "configure_datacache", "(", "ctx", "=", "ctx", ",", "clients", "=", "clients", ",", "datacache_path", "=", "ctx", ".", "rgw", ".", "datacache_path", ")", ",", "]", ")", "if", "ctx", ".", "rgw", ".", "storage_classes", ":", "subtasks", ".", "extend", "(", "[", "lambda", ":", "configure_storage_classes", "(", "ctx", "=", "ctx", ",", "clients", "=", "clients", ",", "storage_classes", "=", "ctx", ".", "rgw", ".", "storage_classes", ")", ",", "]", ")", "subtasks", ".", "extend", "(", "[", "lambda", ":", "start_rgw", "(", "ctx", "=", "ctx", ",", "config", "=", "config", ",", "clients", "=", "clients", ")", ",", "]", ")", "with", "contextutil", ".", "nested", "(", "*", "subtasks", ")", ":", "yield" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/rgw.py#L355-L449
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/msvc.py
python
EnvironmentInfo.FxTools
(self)
return tools
Microsoft .NET Framework Tools. Return ------ list of str paths
Microsoft .NET Framework Tools.
[ "Microsoft", ".", "NET", "Framework", "Tools", "." ]
def FxTools(self): """ Microsoft .NET Framework Tools. Return ------ list of str paths """ pi = self.pi si = self.si if self.vs_ver <= 10.0: include32 = True include64 = not pi.target_is_x86() and not pi.current_is_x86() else: include32 = pi.target_is_x86() or pi.current_is_x86() include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64' tools = [] if include32: tools += [join(si.FrameworkDir32, ver) for ver in si.FrameworkVersion32] if include64: tools += [join(si.FrameworkDir64, ver) for ver in si.FrameworkVersion64] return tools
[ "def", "FxTools", "(", "self", ")", ":", "pi", "=", "self", ".", "pi", "si", "=", "self", ".", "si", "if", "self", ".", "vs_ver", "<=", "10.0", ":", "include32", "=", "True", "include64", "=", "not", "pi", ".", "target_is_x86", "(", ")", "and", "not", "pi", ".", "current_is_x86", "(", ")", "else", ":", "include32", "=", "pi", ".", "target_is_x86", "(", ")", "or", "pi", ".", "current_is_x86", "(", ")", "include64", "=", "pi", ".", "current_cpu", "==", "'amd64'", "or", "pi", ".", "target_cpu", "==", "'amd64'", "tools", "=", "[", "]", "if", "include32", ":", "tools", "+=", "[", "join", "(", "si", ".", "FrameworkDir32", ",", "ver", ")", "for", "ver", "in", "si", ".", "FrameworkVersion32", "]", "if", "include64", ":", "tools", "+=", "[", "join", "(", "si", ".", "FrameworkDir64", ",", "ver", ")", "for", "ver", "in", "si", ".", "FrameworkVersion64", "]", "return", "tools" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/msvc.py#L1509-L1535
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
bindings/python/llvm/object.py
python
Relocation.cache
(self)
Cache all cacheable properties on this instance.
Cache all cacheable properties on this instance.
[ "Cache", "all", "cacheable", "properties", "on", "this", "instance", "." ]
def cache(self): """Cache all cacheable properties on this instance.""" getattr(self, 'address') getattr(self, 'offset') getattr(self, 'symbol') getattr(self, 'type') getattr(self, 'type_name') getattr(self, 'value_string')
[ "def", "cache", "(", "self", ")", ":", "getattr", "(", "self", ",", "'address'", ")", "getattr", "(", "self", ",", "'offset'", ")", "getattr", "(", "self", ",", "'symbol'", ")", "getattr", "(", "self", ",", "'type'", ")", "getattr", "(", "self", ",", "'type_name'", ")", "getattr", "(", "self", ",", "'value_string'", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/bindings/python/llvm/object.py#L418-L425
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
MimeTypesManager_IsOfType
(*args, **kwargs)
return _misc_.MimeTypesManager_IsOfType(*args, **kwargs)
MimeTypesManager_IsOfType(String mimeType, String wildcard) -> bool
MimeTypesManager_IsOfType(String mimeType, String wildcard) -> bool
[ "MimeTypesManager_IsOfType", "(", "String", "mimeType", "String", "wildcard", ")", "-", ">", "bool" ]
def MimeTypesManager_IsOfType(*args, **kwargs): """MimeTypesManager_IsOfType(String mimeType, String wildcard) -> bool""" return _misc_.MimeTypesManager_IsOfType(*args, **kwargs)
[ "def", "MimeTypesManager_IsOfType", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "MimeTypesManager_IsOfType", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L2698-L2700
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/util.py
python
flatten_tree
(tree, leaves=None)
return leaves
Flatten a tree into a list. Args: tree: iterable or not. If iterable, its elements (child) can also be iterable or not. leaves: list to which the tree leaves are appended (None by default). Returns: A list of all the leaves in the tree.
Flatten a tree into a list.
[ "Flatten", "a", "tree", "into", "a", "list", "." ]
def flatten_tree(tree, leaves=None): """Flatten a tree into a list. Args: tree: iterable or not. If iterable, its elements (child) can also be iterable or not. leaves: list to which the tree leaves are appended (None by default). Returns: A list of all the leaves in the tree. """ if leaves is None: leaves = [] if isinstance(tree, dict): for _, child in iteritems(tree): flatten_tree(child, leaves) elif is_iterable(tree): for child in tree: flatten_tree(child, leaves) else: leaves.append(tree) return leaves
[ "def", "flatten_tree", "(", "tree", ",", "leaves", "=", "None", ")", ":", "if", "leaves", "is", "None", ":", "leaves", "=", "[", "]", "if", "isinstance", "(", "tree", ",", "dict", ")", ":", "for", "_", ",", "child", "in", "iteritems", "(", "tree", ")", ":", "flatten_tree", "(", "child", ",", "leaves", ")", "elif", "is_iterable", "(", "tree", ")", ":", "for", "child", "in", "tree", ":", "flatten_tree", "(", "child", ",", "leaves", ")", "else", ":", "leaves", ".", "append", "(", "tree", ")", "return", "leaves" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/util.py#L110-L130
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/environment.py
python
Environment._parse
(self, source, name, filename)
return Parser(self, source, name, encode_filename(filename)).parse()
Internal parsing function used by `parse` and `compile`.
Internal parsing function used by `parse` and `compile`.
[ "Internal", "parsing", "function", "used", "by", "parse", "and", "compile", "." ]
def _parse(self, source, name, filename): """Internal parsing function used by `parse` and `compile`.""" return Parser(self, source, name, encode_filename(filename)).parse()
[ "def", "_parse", "(", "self", ",", "source", ",", "name", ",", "filename", ")", ":", "return", "Parser", "(", "self", ",", "source", ",", "name", ",", "encode_filename", "(", "filename", ")", ")", ".", "parse", "(", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/environment.py#L495-L497
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/json/decoder.py
python
JSONDecoder.__init__
(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True)
``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered.
``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects.
[ "encoding", "determines", "the", "encoding", "used", "to", "interpret", "any", "str", "objects", "decoded", "by", "this", "instance", "(", "utf", "-", "8", "by", "default", ")", ".", "It", "has", "no", "effect", "when", "decoding", "unicode", "objects", "." ]
def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True): """``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. """ self.encoding = encoding self.object_hook = object_hook self.parse_float = parse_float self.parse_int = parse_int self.parse_constant = parse_constant self.strict = strict
[ "def", "__init__", "(", "self", ",", "encoding", "=", "None", ",", "object_hook", "=", "None", ",", "parse_float", "=", "None", ",", "parse_int", "=", "None", ",", "parse_constant", "=", "None", ",", "strict", "=", "True", ")", ":", "self", ".", "encoding", "=", "encoding", "self", ".", "object_hook", "=", "object_hook", "self", ".", "parse_float", "=", "parse_float", "self", ".", "parse_int", "=", "parse_int", "self", ".", "parse_constant", "=", "parse_constant", "self", ".", "strict", "=", "strict" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/json/decoder.py#L276-L311
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/enum.py
python
EnumMeta._create_
(cls, class_name, names, *, module=None, qualname=None, type=None, start=1)
return enum_class
Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are incremented by 1 from `start`. * An iterable of member names. Values are incremented by 1 from `start`. * An iterable of (member name, value) pairs. * A mapping of member name -> value pairs.
Convenience method to create a new Enum class.
[ "Convenience", "method", "to", "create", "a", "new", "Enum", "class", "." ]
def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1): """ Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are incremented by 1 from `start`. * An iterable of member names. Values are incremented by 1 from `start`. * An iterable of (member name, value) pairs. * A mapping of member name -> value pairs. """ metacls = cls.__class__ bases = (cls, ) if type is None else (type, cls) _, first_enum = cls._get_mixins_(cls, bases) classdict = metacls.__prepare__(class_name, bases) # special processing needed for names? if isinstance(names, str): names = names.replace(',', ' ').split() if isinstance(names, (tuple, list)) and names and isinstance(names[0], str): original_names, names = names, [] last_values = [] for count, name in enumerate(original_names): value = first_enum._generate_next_value_(name, start, count, last_values[:]) last_values.append(value) names.append((name, value)) # Here, names is either an iterable of (name, value) or a mapping. for item in names: if isinstance(item, str): member_name, member_value = item, names[item] else: member_name, member_value = item classdict[member_name] = member_value enum_class = metacls.__new__(metacls, class_name, bases, classdict) # TODO: replace the frame hack if a blessed way to know the calling # module is ever developed if module is None: try: module = sys._getframe(2).f_globals['__name__'] except (AttributeError, ValueError, KeyError): pass if module is None: _make_class_unpicklable(enum_class) else: enum_class.__module__ = module if qualname is not None: enum_class.__qualname__ = qualname return enum_class
[ "def", "_create_", "(", "cls", ",", "class_name", ",", "names", ",", "*", ",", "module", "=", "None", ",", "qualname", "=", "None", ",", "type", "=", "None", ",", "start", "=", "1", ")", ":", "metacls", "=", "cls", ".", "__class__", "bases", "=", "(", "cls", ",", ")", "if", "type", "is", "None", "else", "(", "type", ",", "cls", ")", "_", ",", "first_enum", "=", "cls", ".", "_get_mixins_", "(", "cls", ",", "bases", ")", "classdict", "=", "metacls", ".", "__prepare__", "(", "class_name", ",", "bases", ")", "# special processing needed for names?", "if", "isinstance", "(", "names", ",", "str", ")", ":", "names", "=", "names", ".", "replace", "(", "','", ",", "' '", ")", ".", "split", "(", ")", "if", "isinstance", "(", "names", ",", "(", "tuple", ",", "list", ")", ")", "and", "names", "and", "isinstance", "(", "names", "[", "0", "]", ",", "str", ")", ":", "original_names", ",", "names", "=", "names", ",", "[", "]", "last_values", "=", "[", "]", "for", "count", ",", "name", "in", "enumerate", "(", "original_names", ")", ":", "value", "=", "first_enum", ".", "_generate_next_value_", "(", "name", ",", "start", ",", "count", ",", "last_values", "[", ":", "]", ")", "last_values", ".", "append", "(", "value", ")", "names", ".", "append", "(", "(", "name", ",", "value", ")", ")", "# Here, names is either an iterable of (name, value) or a mapping.", "for", "item", "in", "names", ":", "if", "isinstance", "(", "item", ",", "str", ")", ":", "member_name", ",", "member_value", "=", "item", ",", "names", "[", "item", "]", "else", ":", "member_name", ",", "member_value", "=", "item", "classdict", "[", "member_name", "]", "=", "member_value", "enum_class", "=", "metacls", ".", "__new__", "(", "metacls", ",", "class_name", ",", "bases", ",", "classdict", ")", "# TODO: replace the frame hack if a blessed way to know the calling", "# module is ever developed", "if", "module", "is", "None", ":", "try", ":", "module", "=", "sys", ".", "_getframe", "(", "2", ")", ".", "f_globals", "[", "'__name__'", "]", "except", "(", "AttributeError", ",", "ValueError", ",", "KeyError", ")", ":", "pass", "if", "module", "is", "None", ":", "_make_class_unpicklable", "(", "enum_class", ")", "else", ":", "enum_class", ".", "__module__", "=", "module", "if", "qualname", "is", "not", "None", ":", "enum_class", ".", "__qualname__", "=", "qualname", "return", "enum_class" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/enum.py#L475-L526
nRF24/RF24
f9e507544686af23bcfe9578a1558bbb08d382c9
examples_linux/acknowledgement_payloads.py
python
master
()
Transmits a message and an incrementing integer every second.
Transmits a message and an incrementing integer every second.
[ "Transmits", "a", "message", "and", "an", "incrementing", "integer", "every", "second", "." ]
def master(): """Transmits a message and an incrementing integer every second.""" radio.stopListening() # put radio in TX mode failures = 0 while failures < 6: # construct a payload to send buffer = b"Hello \x00" + bytes(counter) # send the payload and prompt start_timer = time.monotonic_ns() # start timer result = radio.write(buffer) # save the report end_timer = time.monotonic_ns() # stop timer if result: # print timer results upon transmission success print( "Transmission successful! Time to transmit: " "{} us. Sent: {}{}".format( int((end_timer - start_timer) / 1000), buffer[:6].decode("utf-8"), counter[0] ), end=" " ) has_payload, pipe_number = radio.available_pipe() if has_payload: # print the received ACK that was automatically sent length = radio.getDynamicPayloadSize() response = radio.read(length) print( "Received {} on pipe {}: {}{}".format( length, pipe_number, bytes(response[:6]).decode("utf-8"), response[7:8][0] ) ) # increment counter from received payload if response[7:8][0] < 255: counter[0] = response[7:8][0] + 1 else: counter[0] = 0 else: print("Received an empty ACK packet") else: failures += 1 print("Transmission failed or timed out") time.sleep(1) # let the RX node prepare a new ACK payload print(failures, "failures detected. Leaving TX role.")
[ "def", "master", "(", ")", ":", "radio", ".", "stopListening", "(", ")", "# put radio in TX mode", "failures", "=", "0", "while", "failures", "<", "6", ":", "# construct a payload to send", "buffer", "=", "b\"Hello \\x00\"", "+", "bytes", "(", "counter", ")", "# send the payload and prompt", "start_timer", "=", "time", ".", "monotonic_ns", "(", ")", "# start timer", "result", "=", "radio", ".", "write", "(", "buffer", ")", "# save the report", "end_timer", "=", "time", ".", "monotonic_ns", "(", ")", "# stop timer", "if", "result", ":", "# print timer results upon transmission success", "print", "(", "\"Transmission successful! Time to transmit: \"", "\"{} us. Sent: {}{}\"", ".", "format", "(", "int", "(", "(", "end_timer", "-", "start_timer", ")", "/", "1000", ")", ",", "buffer", "[", ":", "6", "]", ".", "decode", "(", "\"utf-8\"", ")", ",", "counter", "[", "0", "]", ")", ",", "end", "=", "\" \"", ")", "has_payload", ",", "pipe_number", "=", "radio", ".", "available_pipe", "(", ")", "if", "has_payload", ":", "# print the received ACK that was automatically sent", "length", "=", "radio", ".", "getDynamicPayloadSize", "(", ")", "response", "=", "radio", ".", "read", "(", "length", ")", "print", "(", "\"Received {} on pipe {}: {}{}\"", ".", "format", "(", "length", ",", "pipe_number", ",", "bytes", "(", "response", "[", ":", "6", "]", ")", ".", "decode", "(", "\"utf-8\"", ")", ",", "response", "[", "7", ":", "8", "]", "[", "0", "]", ")", ")", "# increment counter from received payload", "if", "response", "[", "7", ":", "8", "]", "[", "0", "]", "<", "255", ":", "counter", "[", "0", "]", "=", "response", "[", "7", ":", "8", "]", "[", "0", "]", "+", "1", "else", ":", "counter", "[", "0", "]", "=", "0", "else", ":", "print", "(", "\"Received an empty ACK packet\"", ")", "else", ":", "failures", "+=", "1", "print", "(", "\"Transmission failed or timed out\"", ")", "time", ".", "sleep", "(", "1", ")", "# let the RX node prepare a new ACK payload", "print", "(", "failures", ",", "\"failures detected. Leaving TX role.\"", ")" ]
https://github.com/nRF24/RF24/blob/f9e507544686af23bcfe9578a1558bbb08d382c9/examples_linux/acknowledgement_payloads.py#L52-L99
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/sparse/scipy_sparse.py
python
_coo_to_sparse_series
(A, dense_index=False)
return s
Convert a scipy.sparse.coo_matrix to a SparseSeries. Use the defaults given in the SparseSeries constructor.
Convert a scipy.sparse.coo_matrix to a SparseSeries. Use the defaults given in the SparseSeries constructor.
[ "Convert", "a", "scipy", ".", "sparse", ".", "coo_matrix", "to", "a", "SparseSeries", ".", "Use", "the", "defaults", "given", "in", "the", "SparseSeries", "constructor", "." ]
def _coo_to_sparse_series(A, dense_index=False): """ Convert a scipy.sparse.coo_matrix to a SparseSeries. Use the defaults given in the SparseSeries constructor. """ s = Series(A.data, MultiIndex.from_arrays((A.row, A.col))) s = s.sort_index() s = s.to_sparse() # TODO: specify kind? if dense_index: # is there a better constructor method to use here? i = range(A.shape[0]) j = range(A.shape[1]) ind = MultiIndex.from_product([i, j]) s = s.reindex(ind) return s
[ "def", "_coo_to_sparse_series", "(", "A", ",", "dense_index", "=", "False", ")", ":", "s", "=", "Series", "(", "A", ".", "data", ",", "MultiIndex", ".", "from_arrays", "(", "(", "A", ".", "row", ",", "A", ".", "col", ")", ")", ")", "s", "=", "s", ".", "sort_index", "(", ")", "s", "=", "s", ".", "to_sparse", "(", ")", "# TODO: specify kind?", "if", "dense_index", ":", "# is there a better constructor method to use here?", "i", "=", "range", "(", "A", ".", "shape", "[", "0", "]", ")", "j", "=", "range", "(", "A", ".", "shape", "[", "1", "]", ")", "ind", "=", "MultiIndex", ".", "from_product", "(", "[", "i", ",", "j", "]", ")", "s", "=", "s", ".", "reindex", "(", "ind", ")", "return", "s" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/sparse/scipy_sparse.py#L118-L131
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/mox.py
python
UnorderedGroup.IsSatisfied
(self)
return len(self._methods) == 0
Return True if there are not any methods in this group.
Return True if there are not any methods in this group.
[ "Return", "True", "if", "there", "are", "not", "any", "methods", "in", "this", "group", "." ]
def IsSatisfied(self): """Return True if there are not any methods in this group.""" return len(self._methods) == 0
[ "def", "IsSatisfied", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_methods", ")", "==", "0" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/mox.py#L1257-L1260
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/distribute/distributed_training_utils_v1.py
python
unwrap_outputs
(distribution_strategy, grouped_outputs, with_loss_tensor=False)
return [loss] + all_outputs
Unwrap the list of outputs contained in the PerReplica parameters. This function calls `flatten_per_replica_values` to parse each of the input parameters into a list of outputs on the different devices. If we set `with_loss_tensor` to be True, we also call `reduce` on the list of losses on the different devices to give us one loss tensor. Args: distribution_strategy: DistributionStrategy used to distribute training and validation. grouped_outputs: PerReplica outputs returned from the train or test function that we ran on each device. with_loss_tensor: Boolean that indicates if we need to add the reduced loss tensor as one of the outputs. Returns: Values of each of the PerReplica outputs.
Unwrap the list of outputs contained in the PerReplica parameters.
[ "Unwrap", "the", "list", "of", "outputs", "contained", "in", "the", "PerReplica", "parameters", "." ]
def unwrap_outputs(distribution_strategy, grouped_outputs, with_loss_tensor=False): """Unwrap the list of outputs contained in the PerReplica parameters. This function calls `flatten_per_replica_values` to parse each of the input parameters into a list of outputs on the different devices. If we set `with_loss_tensor` to be True, we also call `reduce` on the list of losses on the different devices to give us one loss tensor. Args: distribution_strategy: DistributionStrategy used to distribute training and validation. grouped_outputs: PerReplica outputs returned from the train or test function that we ran on each device. with_loss_tensor: Boolean that indicates if we need to add the reduced loss tensor as one of the outputs. Returns: Values of each of the PerReplica outputs. """ if not with_loss_tensor: return flatten_per_replica_values(distribution_strategy, grouped_outputs) if not isinstance(grouped_outputs, list): grouped_outputs = [grouped_outputs] # reduce loss tensor before adding it to the list of fetches loss = distribution_strategy.reduce(reduce_util.ReduceOp.SUM, grouped_outputs[0], axis=None) all_outputs = flatten_per_replica_values(distribution_strategy, grouped_outputs[1:]) if (backend.is_tpu_strategy(distribution_strategy) and ops.executing_eagerly_outside_functions()): # Choose 1 value per replica in the TPU case since all replicas produce the # same output. # We only do this in eager mode for now since this function is used in # both graph and eager mode and in the graph case we currently don't use # experimental_run so would need to be removed when we converge the graph # code path as well. all_outputs = all_outputs[::distribution_strategy.num_replicas_in_sync] return [loss] + all_outputs
[ "def", "unwrap_outputs", "(", "distribution_strategy", ",", "grouped_outputs", ",", "with_loss_tensor", "=", "False", ")", ":", "if", "not", "with_loss_tensor", ":", "return", "flatten_per_replica_values", "(", "distribution_strategy", ",", "grouped_outputs", ")", "if", "not", "isinstance", "(", "grouped_outputs", ",", "list", ")", ":", "grouped_outputs", "=", "[", "grouped_outputs", "]", "# reduce loss tensor before adding it to the list of fetches", "loss", "=", "distribution_strategy", ".", "reduce", "(", "reduce_util", ".", "ReduceOp", ".", "SUM", ",", "grouped_outputs", "[", "0", "]", ",", "axis", "=", "None", ")", "all_outputs", "=", "flatten_per_replica_values", "(", "distribution_strategy", ",", "grouped_outputs", "[", "1", ":", "]", ")", "if", "(", "backend", ".", "is_tpu_strategy", "(", "distribution_strategy", ")", "and", "ops", ".", "executing_eagerly_outside_functions", "(", ")", ")", ":", "# Choose 1 value per replica in the TPU case since all replicas produce the", "# same output.", "# We only do this in eager mode for now since this function is used in", "# both graph and eager mode and in the graph case we currently don't use", "# experimental_run so would need to be removed when we converge the graph", "# code path as well.", "all_outputs", "=", "all_outputs", "[", ":", ":", "distribution_strategy", ".", "num_replicas_in_sync", "]", "return", "[", "loss", "]", "+", "all_outputs" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/distribute/distributed_training_utils_v1.py#L168-L209
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/stats/stats.py
python
sem
(a, axis=0, ddof=1, nan_policy='propagate')
return s
Calculates the standard error of the mean (or standard error of measurement) of the values in the input array. Parameters ---------- a : array_like An array containing the values for which the standard error is returned. 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. How many degrees of freedom to adjust for bias in limited samples relative to the population estimate of variance. Defaults to 1. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Returns ------- s : ndarray or float The standard error of the mean in the sample(s), along the input axis. Notes ----- The default value for `ddof` is different to the default (0) used by other ddof containing routines, such as np.std and np.nanstd. Examples -------- Find standard error along the first axis: >>> from scipy import stats >>> a = np.arange(20).reshape(5,4) >>> stats.sem(a) array([ 2.8284, 2.8284, 2.8284, 2.8284]) Find standard error across the whole array, using n degrees of freedom: >>> stats.sem(a, axis=None, ddof=0) 1.2893796958227628
Calculates the standard error of the mean (or standard error of measurement) of the values in the input array.
[ "Calculates", "the", "standard", "error", "of", "the", "mean", "(", "or", "standard", "error", "of", "measurement", ")", "of", "the", "values", "in", "the", "input", "array", "." ]
def sem(a, axis=0, ddof=1, nan_policy='propagate'): """ Calculates the standard error of the mean (or standard error of measurement) of the values in the input array. Parameters ---------- a : array_like An array containing the values for which the standard error is returned. 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. How many degrees of freedom to adjust for bias in limited samples relative to the population estimate of variance. Defaults to 1. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Returns ------- s : ndarray or float The standard error of the mean in the sample(s), along the input axis. Notes ----- The default value for `ddof` is different to the default (0) used by other ddof containing routines, such as np.std and np.nanstd. Examples -------- Find standard error along the first axis: >>> from scipy import stats >>> a = np.arange(20).reshape(5,4) >>> stats.sem(a) array([ 2.8284, 2.8284, 2.8284, 2.8284]) Find standard error across the whole array, using n degrees of freedom: >>> stats.sem(a, axis=None, ddof=0) 1.2893796958227628 """ a, axis = _chk_asarray(a, axis) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return mstats_basic.sem(a, axis, ddof) n = a.shape[axis] s = np.std(a, axis=axis, ddof=ddof) / np.sqrt(n) return s
[ "def", "sem", "(", "a", ",", "axis", "=", "0", ",", "ddof", "=", "1", ",", "nan_policy", "=", "'propagate'", ")", ":", "a", ",", "axis", "=", "_chk_asarray", "(", "a", ",", "axis", ")", "contains_nan", ",", "nan_policy", "=", "_contains_nan", "(", "a", ",", "nan_policy", ")", "if", "contains_nan", "and", "nan_policy", "==", "'omit'", ":", "a", "=", "ma", ".", "masked_invalid", "(", "a", ")", "return", "mstats_basic", ".", "sem", "(", "a", ",", "axis", ",", "ddof", ")", "n", "=", "a", ".", "shape", "[", "axis", "]", "s", "=", "np", ".", "std", "(", "a", ",", "axis", "=", "axis", ",", "ddof", "=", "ddof", ")", "/", "np", ".", "sqrt", "(", "n", ")", "return", "s" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/stats.py#L2121-L2178
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/timeseries/python/timeseries/model.py
python
TimeSeriesModel.initialize_graph
(self, input_statistics=None)
Define ops for the model, not depending on any previously defined ops. Args: input_statistics: A math_utils.InputStatistics object containing input statistics. If None, data-independent defaults are used, which may result in longer or unstable training.
Define ops for the model, not depending on any previously defined ops.
[ "Define", "ops", "for", "the", "model", "not", "depending", "on", "any", "previously", "defined", "ops", "." ]
def initialize_graph(self, input_statistics=None): """Define ops for the model, not depending on any previously defined ops. Args: input_statistics: A math_utils.InputStatistics object containing input statistics. If None, data-independent defaults are used, which may result in longer or unstable training. """ self._graph_initialized = True self._input_statistics = input_statistics
[ "def", "initialize_graph", "(", "self", ",", "input_statistics", "=", "None", ")", ":", "self", ".", "_graph_initialized", "=", "True", "self", ".", "_input_statistics", "=", "input_statistics" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/model.py#L114-L123
PaddlePaddle/PaddleOCR
b756bf5f8c90142e0d89d3db0163965c686b6ffe
ppocr/losses/det_basic_loss.py
python
BalanceLoss.forward
(self, pred, gt, mask=None)
return balance_loss
The BalanceLoss for Differentiable Binarization text detection args: pred (variable): predicted feature maps. gt (variable): ground truth feature maps. mask (variable): masked maps. return: (variable) balanced loss
The BalanceLoss for Differentiable Binarization text detection args: pred (variable): predicted feature maps. gt (variable): ground truth feature maps. mask (variable): masked maps. return: (variable) balanced loss
[ "The", "BalanceLoss", "for", "Differentiable", "Binarization", "text", "detection", "args", ":", "pred", "(", "variable", ")", ":", "predicted", "feature", "maps", ".", "gt", "(", "variable", ")", ":", "ground", "truth", "feature", "maps", ".", "mask", "(", "variable", ")", ":", "masked", "maps", ".", "return", ":", "(", "variable", ")", "balanced", "loss" ]
def forward(self, pred, gt, mask=None): """ The BalanceLoss for Differentiable Binarization text detection args: pred (variable): predicted feature maps. gt (variable): ground truth feature maps. mask (variable): masked maps. return: (variable) balanced loss """ positive = gt * mask negative = (1 - gt) * mask positive_count = int(positive.sum()) negative_count = int( min(negative.sum(), positive_count * self.negative_ratio)) loss = self.loss(pred, gt, mask=mask) if not self.balance_loss: return loss positive_loss = positive * loss negative_loss = negative * loss negative_loss = paddle.reshape(negative_loss, shape=[-1]) if negative_count > 0: sort_loss = negative_loss.sort(descending=True) negative_loss = sort_loss[:negative_count] # negative_loss, _ = paddle.topk(negative_loss, k=negative_count_int) balance_loss = (positive_loss.sum() + negative_loss.sum()) / ( positive_count + negative_count + self.eps) else: balance_loss = positive_loss.sum() / (positive_count + self.eps) if self.return_origin: return balance_loss, loss return balance_loss
[ "def", "forward", "(", "self", ",", "pred", ",", "gt", ",", "mask", "=", "None", ")", ":", "positive", "=", "gt", "*", "mask", "negative", "=", "(", "1", "-", "gt", ")", "*", "mask", "positive_count", "=", "int", "(", "positive", ".", "sum", "(", ")", ")", "negative_count", "=", "int", "(", "min", "(", "negative", ".", "sum", "(", ")", ",", "positive_count", "*", "self", ".", "negative_ratio", ")", ")", "loss", "=", "self", ".", "loss", "(", "pred", ",", "gt", ",", "mask", "=", "mask", ")", "if", "not", "self", ".", "balance_loss", ":", "return", "loss", "positive_loss", "=", "positive", "*", "loss", "negative_loss", "=", "negative", "*", "loss", "negative_loss", "=", "paddle", ".", "reshape", "(", "negative_loss", ",", "shape", "=", "[", "-", "1", "]", ")", "if", "negative_count", ">", "0", ":", "sort_loss", "=", "negative_loss", ".", "sort", "(", "descending", "=", "True", ")", "negative_loss", "=", "sort_loss", "[", ":", "negative_count", "]", "# negative_loss, _ = paddle.topk(negative_loss, k=negative_count_int)", "balance_loss", "=", "(", "positive_loss", ".", "sum", "(", ")", "+", "negative_loss", ".", "sum", "(", ")", ")", "/", "(", "positive_count", "+", "negative_count", "+", "self", ".", "eps", ")", "else", ":", "balance_loss", "=", "positive_loss", ".", "sum", "(", ")", "/", "(", "positive_count", "+", "self", ".", "eps", ")", "if", "self", ".", "return_origin", ":", "return", "balance_loss", ",", "loss", "return", "balance_loss" ]
https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/losses/det_basic_loss.py#L72-L106
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/dex.py
python
_IntermediateDexFilePathsFromInputJars
(class_inputs, incremental_dir)
return dex_files
Returns a list of all intermediate dex file paths.
Returns a list of all intermediate dex file paths.
[ "Returns", "a", "list", "of", "all", "intermediate", "dex", "file", "paths", "." ]
def _IntermediateDexFilePathsFromInputJars(class_inputs, incremental_dir): """Returns a list of all intermediate dex file paths.""" dex_files = [] for jar in class_inputs: with zipfile.ZipFile(jar, 'r') as z: for subpath in z.namelist(): if _IsClassFile(subpath): subpath = subpath[:-5] + 'dex' dex_files.append(os.path.join(incremental_dir, subpath)) return dex_files
[ "def", "_IntermediateDexFilePathsFromInputJars", "(", "class_inputs", ",", "incremental_dir", ")", ":", "dex_files", "=", "[", "]", "for", "jar", "in", "class_inputs", ":", "with", "zipfile", ".", "ZipFile", "(", "jar", ",", "'r'", ")", "as", "z", ":", "for", "subpath", "in", "z", ".", "namelist", "(", ")", ":", "if", "_IsClassFile", "(", "subpath", ")", ":", "subpath", "=", "subpath", "[", ":", "-", "5", "]", "+", "'dex'", "dex_files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "incremental_dir", ",", "subpath", ")", ")", "return", "dex_files" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/dex.py#L426-L435
tpfister/caffe-heatmap
4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e
scripts/cpp_lint.py
python
_SetVerboseLevel
(level)
return _cpplint_state.SetVerboseLevel(level)
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level)
[ "def", "_SetVerboseLevel", "(", "level", ")", ":", "return", "_cpplint_state", ".", "SetVerboseLevel", "(", "level", ")" ]
https://github.com/tpfister/caffe-heatmap/blob/4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e/scripts/cpp_lint.py#L782-L784
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/remote.py
python
_ServiceClass.__init__
(cls, name, bases, dct)
Create uninitialized state on new class.
Create uninitialized state on new class.
[ "Create", "uninitialized", "state", "on", "new", "class", "." ]
def __init__(cls, name, bases, dct): """Create uninitialized state on new class.""" type.__init__(cls, name, bases, dct) # Only service implementation classes should have remote methods and stub # sub classes created. Stub implementations have their own methods passed # in to the type constructor. if StubBase not in bases: # Create list of remote methods. cls.__remote_methods = dict(cls.__base_methods) for attribute, value in dct.items(): value = getattr(cls, attribute) remote_method_info = get_remote_method_info(value) if remote_method_info: cls.__remote_methods[attribute] = value # Build asynchronous stub class. stub_attributes = {'Service': cls} async_methods = cls.__create_async_methods(cls.__remote_methods) stub_attributes.update(async_methods) async_class = type('AsyncStub', (StubBase, cls), stub_attributes) cls.AsyncStub = async_class # Constructor for synchronous stub class. def __init__(self, transport): """Constructor. Args: transport: Underlying transport to communicate with remote service. """ super(cls.Stub, self).__init__(transport) self.async = cls.AsyncStub(transport) # Build synchronous stub class. stub_attributes = {'Service': cls, '__init__': __init__} stub_attributes.update(cls.__create_sync_methods(async_methods)) cls.Stub = type('Stub', (StubBase, cls), stub_attributes)
[ "def", "__init__", "(", "cls", ",", "name", ",", "bases", ",", "dct", ")", ":", "type", ".", "__init__", "(", "cls", ",", "name", ",", "bases", ",", "dct", ")", "# Only service implementation classes should have remote methods and stub", "# sub classes created. Stub implementations have their own methods passed", "# in to the type constructor.", "if", "StubBase", "not", "in", "bases", ":", "# Create list of remote methods.", "cls", ".", "__remote_methods", "=", "dict", "(", "cls", ".", "__base_methods", ")", "for", "attribute", ",", "value", "in", "dct", ".", "items", "(", ")", ":", "value", "=", "getattr", "(", "cls", ",", "attribute", ")", "remote_method_info", "=", "get_remote_method_info", "(", "value", ")", "if", "remote_method_info", ":", "cls", ".", "__remote_methods", "[", "attribute", "]", "=", "value", "# Build asynchronous stub class.", "stub_attributes", "=", "{", "'Service'", ":", "cls", "}", "async_methods", "=", "cls", ".", "__create_async_methods", "(", "cls", ".", "__remote_methods", ")", "stub_attributes", ".", "update", "(", "async_methods", ")", "async_class", "=", "type", "(", "'AsyncStub'", ",", "(", "StubBase", ",", "cls", ")", ",", "stub_attributes", ")", "cls", ".", "AsyncStub", "=", "async_class", "# Constructor for synchronous stub class.", "def", "__init__", "(", "self", ",", "transport", ")", ":", "\"\"\"Constructor.\n\n Args:\n transport: Underlying transport to communicate with remote service.\n \"\"\"", "super", "(", "cls", ".", "Stub", ",", "self", ")", ".", "__init__", "(", "transport", ")", "self", ".", "async", "=", "cls", ".", "AsyncStub", "(", "transport", ")", "# Build synchronous stub class.", "stub_attributes", "=", "{", "'Service'", ":", "cls", ",", "'__init__'", ":", "__init__", "}", "stub_attributes", ".", "update", "(", "cls", ".", "__create_sync_methods", "(", "async_methods", ")", ")", "cls", ".", "Stub", "=", "type", "(", "'Stub'", ",", "(", "StubBase", ",", "cls", ")", ",", "stub_attributes", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/remote.py#L655-L694
nyuwireless-unipd/ns3-mmwave
4ff9e87e8079764e04cbeccd8e85bff15ae16fb3
utils/grid.py
python
ScaleRenderer.get_position
(self, x)
return real_x
! Get Position @param self this object @param x x @return real x
! Get Position
[ "!", "Get", "Position" ]
def get_position(self, x): """! Get Position @param self this object @param x x @return real x """ real_x = (x - self.__lo ) * self.__width / (self.__hi - self.__lo) return real_x
[ "def", "get_position", "(", "self", ",", "x", ")", ":", "real_x", "=", "(", "x", "-", "self", ".", "__lo", ")", "*", "self", ".", "__width", "/", "(", "self", ".", "__hi", "-", "self", ".", "__lo", ")", "return", "real_x" ]
https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/grid.py#L879-L886
google/iree
1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76
integrations/tensorflow/iree-dialects/python/iree/compiler/dialects/iree_pydm/importer/util.py
python
ImportContext.abort
(self, message: str)
Emits an error diagnostic and raises an exception to abort.
Emits an error diagnostic and raises an exception to abort.
[ "Emits", "an", "error", "diagnostic", "and", "raises", "an", "exception", "to", "abort", "." ]
def abort(self, message: str): """Emits an error diagnostic and raises an exception to abort.""" loc = self.loc _emit_error(loc, message) raise EmittedError(loc, message)
[ "def", "abort", "(", "self", ",", "message", ":", "str", ")", ":", "loc", "=", "self", ".", "loc", "_emit_error", "(", "loc", ",", "message", ")", "raise", "EmittedError", "(", "loc", ",", "message", ")" ]
https://github.com/google/iree/blob/1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76/integrations/tensorflow/iree-dialects/python/iree/compiler/dialects/iree_pydm/importer/util.py#L108-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/boto3/resources/model.py
python
DefinitionWithParams.params
(self)
return params
Get a list of auto-filled parameters for this request. :type: list(:py:class:`Parameter`)
Get a list of auto-filled parameters for this request.
[ "Get", "a", "list", "of", "auto", "-", "filled", "parameters", "for", "this", "request", "." ]
def params(self): """ Get a list of auto-filled parameters for this request. :type: list(:py:class:`Parameter`) """ params = [] for item in self._definition.get('params', []): params.append(Parameter(**item)) return params
[ "def", "params", "(", "self", ")", ":", "params", "=", "[", "]", "for", "item", "in", "self", ".", "_definition", ".", "get", "(", "'params'", ",", "[", "]", ")", ":", "params", ".", "append", "(", "Parameter", "(", "*", "*", "item", ")", ")", "return", "params" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/boto3/resources/model.py#L89-L100
OPAE/opae-sdk
221124343c8275243a249eb72d69e0ea2d568d1b
binaries/utilities/vc_image_convert/merge_device_table.py
python
main
(input_file, dtb_file)
function reads and checks max10_device_table.bin to ensure the file is under the alloted size the section is written into the table section of the input file
function reads and checks max10_device_table.bin to ensure the file is under the alloted size the section is written into the table section of the input file
[ "function", "reads", "and", "checks", "max10_device_table", ".", "bin", "to", "ensure", "the", "file", "is", "under", "the", "alloted", "size", "the", "section", "is", "written", "into", "the", "table", "section", "of", "the", "input", "file" ]
def main(input_file, dtb_file): """ function reads and checks max10_device_table.bin to ensure the file is under the alloted size the section is written into the table section of the input file """ LOGGER.info("Reading: %s" % dtb_file) with open(dtb_file, "rb") as max_table_file: LOGGER.info("max10_device_table.bin size: %x" % os.path.getsize(max_table_file.name)) LOGGER.info("Max max10 table size: %x" % MAX10_TABLE_SIZE) if (os.path.getsize(max_table_file.name) > MAX10_TABLE_SIZE): raise Exception(LOGGER.error("max10_device_table.bin is too big")) max10_table = max_table_file.read() LOGGER.info("Writing file: %s" % input_file) with open(input_file, "rb+") as rpd_file: rpd_file.seek(MAX10_TABLE_START) rpd_file.write(bytearray(max10_table)) LOGGER.info("Done merging Max10 device table")
[ "def", "main", "(", "input_file", ",", "dtb_file", ")", ":", "LOGGER", ".", "info", "(", "\"Reading: %s\"", "%", "dtb_file", ")", "with", "open", "(", "dtb_file", ",", "\"rb\"", ")", "as", "max_table_file", ":", "LOGGER", ".", "info", "(", "\"max10_device_table.bin size: %x\"", "%", "os", ".", "path", ".", "getsize", "(", "max_table_file", ".", "name", ")", ")", "LOGGER", ".", "info", "(", "\"Max max10 table size: %x\"", "%", "MAX10_TABLE_SIZE", ")", "if", "(", "os", ".", "path", ".", "getsize", "(", "max_table_file", ".", "name", ")", ">", "MAX10_TABLE_SIZE", ")", ":", "raise", "Exception", "(", "LOGGER", ".", "error", "(", "\"max10_device_table.bin is too big\"", ")", ")", "max10_table", "=", "max_table_file", ".", "read", "(", ")", "LOGGER", ".", "info", "(", "\"Writing file: %s\"", "%", "input_file", ")", "with", "open", "(", "input_file", ",", "\"rb+\"", ")", "as", "rpd_file", ":", "rpd_file", ".", "seek", "(", "MAX10_TABLE_START", ")", "rpd_file", ".", "write", "(", "bytearray", "(", "max10_table", ")", ")", "LOGGER", ".", "info", "(", "\"Done merging Max10 device table\"", ")" ]
https://github.com/OPAE/opae-sdk/blob/221124343c8275243a249eb72d69e0ea2d568d1b/binaries/utilities/vc_image_convert/merge_device_table.py#L21-L39
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/encodings/base64_codec.py
python
base64_encode
(input,errors='strict')
return (output, len(input))
Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
Encodes the object input and returns a tuple (output object, length consumed).
[ "Encodes", "the", "object", "input", "and", "returns", "a", "tuple", "(", "output", "object", "length", "consumed", ")", "." ]
def base64_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = base64.encodestring(input) return (output, len(input))
[ "def", "base64_encode", "(", "input", ",", "errors", "=", "'strict'", ")", ":", "assert", "errors", "==", "'strict'", "output", "=", "base64", ".", "encodestring", "(", "input", ")", "return", "(", "output", ",", "len", "(", "input", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/encodings/base64_codec.py#L13-L25
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/labeled_tensor/python/ops/_typecheck.py
python
accepts
(*types)
return check_accepts
A decorator which checks the input types of a function. Based on: http://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments The above draws from: https://www.python.org/dev/peps/pep-0318/ Args: *types: A list of Python types. Returns: A function to use as a decorator.
A decorator which checks the input types of a function.
[ "A", "decorator", "which", "checks", "the", "input", "types", "of", "a", "function", "." ]
def accepts(*types): """A decorator which checks the input types of a function. Based on: http://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments The above draws from: https://www.python.org/dev/peps/pep-0318/ Args: *types: A list of Python types. Returns: A function to use as a decorator. """ def check_accepts(f): """Check the types.""" spec = tf_inspect.getargspec(f) num_function_arguments = len(spec.args) if len(types) != num_function_arguments: raise Error( "Function %r has %d arguments but only %d types were provided in the " "annotation." % (f, num_function_arguments, len(types))) if spec.defaults: num_defaults = len(spec.defaults) for (name, a, t) in zip(spec.args[-num_defaults:], spec.defaults, types[-num_defaults:]): allowed_type = _replace_forward_references(t, f.__globals__) if not isinstance(a, allowed_type): raise Error("default argument value %r of type %r is not an instance " "of the allowed type %s for the %s argument to %r" % (a, type(a), _type_repr(allowed_type), name, f)) @functools.wraps(f) def new_f(*args, **kwds): """A helper function.""" for (a, t) in zip(args, types): allowed_type = _replace_forward_references(t, f.__globals__) if not isinstance(a, allowed_type): raise Error("%r of type %r is not an instance of the allowed type %s " "for %r" % (a, type(a), _type_repr(allowed_type), f)) return f(*args, **kwds) return new_f return check_accepts
[ "def", "accepts", "(", "*", "types", ")", ":", "def", "check_accepts", "(", "f", ")", ":", "\"\"\"Check the types.\"\"\"", "spec", "=", "tf_inspect", ".", "getargspec", "(", "f", ")", "num_function_arguments", "=", "len", "(", "spec", ".", "args", ")", "if", "len", "(", "types", ")", "!=", "num_function_arguments", ":", "raise", "Error", "(", "\"Function %r has %d arguments but only %d types were provided in the \"", "\"annotation.\"", "%", "(", "f", ",", "num_function_arguments", ",", "len", "(", "types", ")", ")", ")", "if", "spec", ".", "defaults", ":", "num_defaults", "=", "len", "(", "spec", ".", "defaults", ")", "for", "(", "name", ",", "a", ",", "t", ")", "in", "zip", "(", "spec", ".", "args", "[", "-", "num_defaults", ":", "]", ",", "spec", ".", "defaults", ",", "types", "[", "-", "num_defaults", ":", "]", ")", ":", "allowed_type", "=", "_replace_forward_references", "(", "t", ",", "f", ".", "__globals__", ")", "if", "not", "isinstance", "(", "a", ",", "allowed_type", ")", ":", "raise", "Error", "(", "\"default argument value %r of type %r is not an instance \"", "\"of the allowed type %s for the %s argument to %r\"", "%", "(", "a", ",", "type", "(", "a", ")", ",", "_type_repr", "(", "allowed_type", ")", ",", "name", ",", "f", ")", ")", "@", "functools", ".", "wraps", "(", "f", ")", "def", "new_f", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "\"\"\"A helper function.\"\"\"", "for", "(", "a", ",", "t", ")", "in", "zip", "(", "args", ",", "types", ")", ":", "allowed_type", "=", "_replace_forward_references", "(", "t", ",", "f", ".", "__globals__", ")", "if", "not", "isinstance", "(", "a", ",", "allowed_type", ")", ":", "raise", "Error", "(", "\"%r of type %r is not an instance of the allowed type %s \"", "\"for %r\"", "%", "(", "a", ",", "type", "(", "a", ")", ",", "_type_repr", "(", "allowed_type", ")", ",", "f", ")", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwds", ")", "return", "new_f", "return", "check_accepts" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/labeled_tensor/python/ops/_typecheck.py#L216-L264
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextBuffer.SetFontTable
(*args, **kwargs)
return _richtext.RichTextBuffer_SetFontTable(*args, **kwargs)
SetFontTable(self, RichTextFontTable table)
SetFontTable(self, RichTextFontTable table)
[ "SetFontTable", "(", "self", "RichTextFontTable", "table", ")" ]
def SetFontTable(*args, **kwargs): """SetFontTable(self, RichTextFontTable table)""" return _richtext.RichTextBuffer_SetFontTable(*args, **kwargs)
[ "def", "SetFontTable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_SetFontTable", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L2233-L2235
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/utils/mpi/primitives.py
python
mpi_max
(x, *, comm=MPI_py_comm)
return ar
Computes the elementwise logical OR of an array or a scalar across all MPI processes, effectively equivalent to an elementwise any Args: a: The input array, which will usually be overwritten in place. Returns: out: The reduced array.
Computes the elementwise logical OR of an array or a scalar across all MPI processes, effectively equivalent to an elementwise any
[ "Computes", "the", "elementwise", "logical", "OR", "of", "an", "array", "or", "a", "scalar", "across", "all", "MPI", "processes", "effectively", "equivalent", "to", "an", "elementwise", "any" ]
def mpi_max(x, *, comm=MPI_py_comm): """ Computes the elementwise logical OR of an array or a scalar across all MPI processes, effectively equivalent to an elementwise any Args: a: The input array, which will usually be overwritten in place. Returns: out: The reduced array. """ ar = np.asarray(x) if n_nodes > 1: comm.Allreduce(MPI.IN_PLACE, ar.reshape(-1), op=MPI.MAX) return ar
[ "def", "mpi_max", "(", "x", ",", "*", ",", "comm", "=", "MPI_py_comm", ")", ":", "ar", "=", "np", ".", "asarray", "(", "x", ")", "if", "n_nodes", ">", "1", ":", "comm", ".", "Allreduce", "(", "MPI", ".", "IN_PLACE", ",", "ar", ".", "reshape", "(", "-", "1", ")", ",", "op", "=", "MPI", ".", "MAX", ")", "return", "ar" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/utils/mpi/primitives.py#L211-L226
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py
python
EnvironmentInfo.HTMLHelpWorkshop
(self)
return [os.path.join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
Microsoft HTML Help Workshop
Microsoft HTML Help Workshop
[ "Microsoft", "HTML", "Help", "Workshop" ]
def HTMLHelpWorkshop(self): """ Microsoft HTML Help Workshop """ if self.vc_ver < 11.0: return [] return [os.path.join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
[ "def", "HTMLHelpWorkshop", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "11.0", ":", "return", "[", "]", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "ProgramFilesx86", ",", "'HTML Help Workshop'", ")", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py#L1147-L1154
redpony/cdec
f7c4899b174d86bc70b40b1cae68dcad364615cb
realtime/rt/rt.py
python
RealtimeTranslator.learn
(self, source, target, ctx_name=None)
Learn from training instance (inc extracting grammar if needed) Threadsafe, FIFO
Learn from training instance (inc extracting grammar if needed) Threadsafe, FIFO
[ "Learn", "from", "training", "instance", "(", "inc", "extracting", "grammar", "if", "needed", ")", "Threadsafe", "FIFO" ]
def learn(self, source, target, ctx_name=None): '''Learn from training instance (inc extracting grammar if needed) Threadsafe, FIFO''' lock = self.ctx_locks[ctx_name] lock.acquire() self.lazy_ctx(ctx_name) if '' in (source.strip(), target.strip()): logger.info('({}) ERROR: empty source or target: {} ||| {}'.format(ctx_name, source, target)) lock.release() return if self.norm: source = self.tokenize(source) target = self.tokenize(target) # Align instance alignment = self.aligner.align(source, target) grammar_file = self.grammar(source, ctx_name) # MIRA update before adding data to grammar extractor decoder = self.decoders[ctx_name] mira_log = decoder.decoder.update(source, grammar_file, target) logger.info('({}) MIRA HBF: {}'.format(ctx_name, mira_log)) # Add to HPYPLM by writing to fifo (read on next translation) if self.hpyplm: logger.info('({}) Adding to HPYPLM: {}'.format(ctx_name, target)) decoder.ref_fifo.write('{}\n'.format(target)) decoder.ref_fifo.flush() # Store incremental data for save/load self.ctx_data[ctx_name].append((source, target, alignment)) # Add aligned sentence pair to grammar extractor logger.info('({}) Adding to bitext: {} ||| {} ||| {}'.format(ctx_name, source, target, alignment)) self.extractor.add_instance(source, target, alignment, ctx_name) # Clear (old) cached grammar rm_grammar = self.grammar_dict[ctx_name].pop(source) os.remove(rm_grammar) lock.release()
[ "def", "learn", "(", "self", ",", "source", ",", "target", ",", "ctx_name", "=", "None", ")", ":", "lock", "=", "self", ".", "ctx_locks", "[", "ctx_name", "]", "lock", ".", "acquire", "(", ")", "self", ".", "lazy_ctx", "(", "ctx_name", ")", "if", "''", "in", "(", "source", ".", "strip", "(", ")", ",", "target", ".", "strip", "(", ")", ")", ":", "logger", ".", "info", "(", "'({}) ERROR: empty source or target: {} ||| {}'", ".", "format", "(", "ctx_name", ",", "source", ",", "target", ")", ")", "lock", ".", "release", "(", ")", "return", "if", "self", ".", "norm", ":", "source", "=", "self", ".", "tokenize", "(", "source", ")", "target", "=", "self", ".", "tokenize", "(", "target", ")", "# Align instance", "alignment", "=", "self", ".", "aligner", ".", "align", "(", "source", ",", "target", ")", "grammar_file", "=", "self", ".", "grammar", "(", "source", ",", "ctx_name", ")", "# MIRA update before adding data to grammar extractor", "decoder", "=", "self", ".", "decoders", "[", "ctx_name", "]", "mira_log", "=", "decoder", ".", "decoder", ".", "update", "(", "source", ",", "grammar_file", ",", "target", ")", "logger", ".", "info", "(", "'({}) MIRA HBF: {}'", ".", "format", "(", "ctx_name", ",", "mira_log", ")", ")", "# Add to HPYPLM by writing to fifo (read on next translation)", "if", "self", ".", "hpyplm", ":", "logger", ".", "info", "(", "'({}) Adding to HPYPLM: {}'", ".", "format", "(", "ctx_name", ",", "target", ")", ")", "decoder", ".", "ref_fifo", ".", "write", "(", "'{}\\n'", ".", "format", "(", "target", ")", ")", "decoder", ".", "ref_fifo", ".", "flush", "(", ")", "# Store incremental data for save/load", "self", ".", "ctx_data", "[", "ctx_name", "]", ".", "append", "(", "(", "source", ",", "target", ",", "alignment", ")", ")", "# Add aligned sentence pair to grammar extractor", "logger", ".", "info", "(", "'({}) Adding to bitext: {} ||| {} ||| {}'", ".", "format", "(", "ctx_name", ",", "source", ",", "target", ",", "alignment", ")", ")", "self", ".", "extractor", ".", "add_instance", "(", "source", ",", "target", ",", "alignment", ",", "ctx_name", ")", "# Clear (old) cached grammar", "rm_grammar", "=", "self", ".", "grammar_dict", "[", "ctx_name", "]", ".", "pop", "(", "source", ")", "os", ".", "remove", "(", "rm_grammar", ")", "lock", ".", "release", "(", ")" ]
https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/realtime/rt/rt.py#L345-L378
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/sandbox.py
python
SandboxedEnvironment.is_safe_callable
(self, obj)
return not (getattr(obj, 'unsafe_callable', False) or getattr(obj, 'alters_data', False))
Check if an object is safely callable. Per default a function is considered safe unless the `unsafe_callable` attribute exists and is True. Override this method to alter the behavior, but this won't affect the `unsafe` decorator from this module.
Check if an object is safely callable. Per default a function is considered safe unless the `unsafe_callable` attribute exists and is True. Override this method to alter the behavior, but this won't affect the `unsafe` decorator from this module.
[ "Check", "if", "an", "object", "is", "safely", "callable", ".", "Per", "default", "a", "function", "is", "considered", "safe", "unless", "the", "unsafe_callable", "attribute", "exists", "and", "is", "True", ".", "Override", "this", "method", "to", "alter", "the", "behavior", "but", "this", "won", "t", "affect", "the", "unsafe", "decorator", "from", "this", "module", "." ]
def is_safe_callable(self, obj): """Check if an object is safely callable. Per default a function is considered safe unless the `unsafe_callable` attribute exists and is True. Override this method to alter the behavior, but this won't affect the `unsafe` decorator from this module. """ return not (getattr(obj, 'unsafe_callable', False) or getattr(obj, 'alters_data', False))
[ "def", "is_safe_callable", "(", "self", ",", "obj", ")", ":", "return", "not", "(", "getattr", "(", "obj", ",", "'unsafe_callable'", ",", "False", ")", "or", "getattr", "(", "obj", ",", "'alters_data'", ",", "False", ")", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/sandbox.py#L332-L339
RegrowthStudios/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
utils/git-hooks/pep8.py
python
BaseReport.increment_logical_line
(self)
Signal a new logical line.
Signal a new logical line.
[ "Signal", "a", "new", "logical", "line", "." ]
def increment_logical_line(self): """Signal a new logical line.""" self.counters['logical lines'] += 1
[ "def", "increment_logical_line", "(", "self", ")", ":", "self", ".", "counters", "[", "'logical lines'", "]", "+=", "1" ]
https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/pep8.py#L1442-L1444
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py
python
_MSVSOnly
(tool, name, setting_type)
Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting.
Defines a setting that is only found in MSVS.
[ "Defines", "a", "setting", "that", "is", "only", "found", "in", "MSVS", "." ]
def _MSVSOnly(tool, name, setting_type): """Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ def _Translate(unused_value, unused_msbuild_settings): # Since this is for MSVS only settings, no translation will happen. pass _msvs_validators[tool.msvs_name][name] = setting_type.ValidateMSVS _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate
[ "def", "_MSVSOnly", "(", "tool", ",", "name", ",", "setting_type", ")", ":", "def", "_Translate", "(", "unused_value", ",", "unused_msbuild_settings", ")", ":", "# Since this is for MSVS only settings, no translation will happen.", "pass", "_msvs_validators", "[", "tool", ".", "msvs_name", "]", "[", "name", "]", "=", "setting_type", ".", "ValidateMSVS", "_msvs_to_msbuild_converters", "[", "tool", ".", "msvs_name", "]", "[", "name", "]", "=", "_Translate" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L296-L310
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/period.py
python
PeriodArray._add_timedeltalike_scalar
(self, other)
return ordinals
Parameters ---------- other : timedelta, Tick, np.timedelta64 Returns ------- result : ndarray[int64]
Parameters ---------- other : timedelta, Tick, np.timedelta64
[ "Parameters", "----------", "other", ":", "timedelta", "Tick", "np", ".", "timedelta64" ]
def _add_timedeltalike_scalar(self, other): """ Parameters ---------- other : timedelta, Tick, np.timedelta64 Returns ------- result : ndarray[int64] """ assert isinstance(self.freq, Tick) # checked by calling function assert isinstance(other, (timedelta, np.timedelta64, Tick)) if notna(other): # special handling for np.timedelta64("NaT"), avoid calling # _check_timedeltalike_freq_compat as that would raise TypeError other = self._check_timedeltalike_freq_compat(other) # Note: when calling parent class's _add_timedeltalike_scalar, # it will call delta_to_nanoseconds(delta). Because delta here # is an integer, delta_to_nanoseconds will return it unchanged. ordinals = super(PeriodArray, self)._add_timedeltalike_scalar(other) return ordinals
[ "def", "_add_timedeltalike_scalar", "(", "self", ",", "other", ")", ":", "assert", "isinstance", "(", "self", ".", "freq", ",", "Tick", ")", "# checked by calling function", "assert", "isinstance", "(", "other", ",", "(", "timedelta", ",", "np", ".", "timedelta64", ",", "Tick", ")", ")", "if", "notna", "(", "other", ")", ":", "# special handling for np.timedelta64(\"NaT\"), avoid calling", "# _check_timedeltalike_freq_compat as that would raise TypeError", "other", "=", "self", ".", "_check_timedeltalike_freq_compat", "(", "other", ")", "# Note: when calling parent class's _add_timedeltalike_scalar,", "# it will call delta_to_nanoseconds(delta). Because delta here", "# is an integer, delta_to_nanoseconds will return it unchanged.", "ordinals", "=", "super", "(", "PeriodArray", ",", "self", ")", ".", "_add_timedeltalike_scalar", "(", "other", ")", "return", "ordinals" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/period.py#L565-L587
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/squeeze.py
python
_squeeze_tbe
()
return
Squeeze TBE register
Squeeze TBE register
[ "Squeeze", "TBE", "register" ]
def _squeeze_tbe(): """Squeeze TBE register""" return
[ "def", "_squeeze_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/squeeze.py#L35-L37
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBSection.GetTargetByteSize
(self)
return _lldb.SBSection_GetTargetByteSize(self)
GetTargetByteSize(self) -> uint32_t Return the size of a target's byte represented by this section in numbers of host bytes. Note that certain architectures have varying minimum addressable unit (i.e. byte) size for their CODE or DATA buses. @return The number of host (8-bit) bytes needed to hold a target byte
GetTargetByteSize(self) -> uint32_t
[ "GetTargetByteSize", "(", "self", ")", "-", ">", "uint32_t" ]
def GetTargetByteSize(self): """ GetTargetByteSize(self) -> uint32_t Return the size of a target's byte represented by this section in numbers of host bytes. Note that certain architectures have varying minimum addressable unit (i.e. byte) size for their CODE or DATA buses. @return The number of host (8-bit) bytes needed to hold a target byte """ return _lldb.SBSection_GetTargetByteSize(self)
[ "def", "GetTargetByteSize", "(", "self", ")", ":", "return", "_lldb", ".", "SBSection_GetTargetByteSize", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7739-L7751
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
CheckComment
(line, filename, linenum, next_line_start, error)
Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found.
Checks for common mistakes in comments.
[ "Checks", "for", "common", "mistakes", "in", "comments", "." ]
def CheckComment(line, filename, linenum, next_line_start, error): """Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found. """ commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0: # Allow one space for new scopes, two spaces otherwise: if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # Checks for common mistakes in TODO comments. comment = line[commentpos:] match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') # If the comment contains an alphanumeric character, there # should be a space somewhere between it and the // unless # it's a /// or //! Doxygen comment. if (Match(r'//[^ ]*\w', comment) and not Match(r'(///|//\!)(\s+|$)', comment)): error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment')
[ "def", "CheckComment", "(", "line", ",", "filename", ",", "linenum", ",", "next_line_start", ",", "error", ")", ":", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", ":", "# Check if the // may be in quotes. If so, ignore it", "if", "re", ".", "sub", "(", "r'\\\\.'", ",", "''", ",", "line", "[", "0", ":", "commentpos", "]", ")", ".", "count", "(", "'\"'", ")", "%", "2", "==", "0", ":", "# Allow one space for new scopes, two spaces otherwise:", "if", "(", "not", "(", "Match", "(", "r'^.*{ *//'", ",", "line", ")", "and", "next_line_start", "==", "commentpos", ")", "and", "(", "(", "commentpos", ">=", "1", "and", "line", "[", "commentpos", "-", "1", "]", "not", "in", "string", ".", "whitespace", ")", "or", "(", "commentpos", ">=", "2", "and", "line", "[", "commentpos", "-", "2", "]", "not", "in", "string", ".", "whitespace", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "2", ",", "'At least two spaces is best between code and comments'", ")", "# Checks for common mistakes in TODO comments.", "comment", "=", "line", "[", "commentpos", ":", "]", "match", "=", "_RE_PATTERN_TODO", ".", "match", "(", "comment", ")", "if", "match", ":", "# One whitespace is correct; zero whitespace is handled elsewhere.", "leading_whitespace", "=", "match", ".", "group", "(", "1", ")", "if", "len", "(", "leading_whitespace", ")", ">", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/todo'", ",", "2", ",", "'Too many spaces before TODO'", ")", "username", "=", "match", ".", "group", "(", "2", ")", "if", "not", "username", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/todo'", ",", "2", ",", "'Missing username in TODO; it should look like '", "'\"// TODO(my_username): Stuff.\"'", ")", "middle_whitespace", "=", "match", ".", "group", "(", "3", ")", "# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison", "if", "middle_whitespace", "!=", "' '", "and", "middle_whitespace", "!=", "''", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/todo'", ",", "2", ",", "'TODO(my_username) should be followed by a space'", ")", "# If the comment contains an alphanumeric character, there", "# should be a space somewhere between it and the // unless", "# it's a /// or //! Doxygen comment.", "if", "(", "Match", "(", "r'//[^ ]*\\w'", ",", "comment", ")", "and", "not", "Match", "(", "r'(///|//\\!)(\\s+|$)'", ",", "comment", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "4", ",", "'Should have a space between // and comment'", ")" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L3117-L3168
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/ISISCommandInterface.py
python
LOQ
(idf_path='LOQ_Definition_20020226-.xml')
return True
Initialises the instrument settings for LOQ @return True on success
Initialises the instrument settings for LOQ
[ "Initialises", "the", "instrument", "settings", "for", "LOQ" ]
def LOQ(idf_path='LOQ_Definition_20020226-.xml'): """ Initialises the instrument settings for LOQ @return True on success """ _printMessage('LOQ()') try: instrument = isis_instrument.LOQ(idf_path) if instrument is None: raise RuntimeError("The provided idf path seems to have been incorrect") ReductionSingleton().set_instrument(instrument) config['default.instrument'] = 'LOQ' except(Exception, Warning): return False return True
[ "def", "LOQ", "(", "idf_path", "=", "'LOQ_Definition_20020226-.xml'", ")", ":", "_printMessage", "(", "'LOQ()'", ")", "try", ":", "instrument", "=", "isis_instrument", ".", "LOQ", "(", "idf_path", ")", "if", "instrument", "is", "None", ":", "raise", "RuntimeError", "(", "\"The provided idf path seems to have been incorrect\"", ")", "ReductionSingleton", "(", ")", ".", "set_instrument", "(", "instrument", ")", "config", "[", "'default.instrument'", "]", "=", "'LOQ'", "except", "(", "Exception", ",", "Warning", ")", ":", "return", "False", "return", "True" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/ISISCommandInterface.py#L111-L125
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/scrollable_pane.py
python
ScrollablePane._copy_over_write_positions
( self, screen: Screen, temp_screen: Screen, write_position: WritePosition )
Copy over window write positions.
Copy over window write positions.
[ "Copy", "over", "window", "write", "positions", "." ]
def _copy_over_write_positions( self, screen: Screen, temp_screen: Screen, write_position: WritePosition ) -> None: """ Copy over window write positions. """ ypos = write_position.ypos xpos = write_position.xpos for win, write_pos in temp_screen.visible_windows_to_write_positions.items(): screen.visible_windows_to_write_positions[win] = WritePosition( xpos=write_pos.xpos + xpos, ypos=write_pos.ypos + ypos - self.vertical_scroll, # TODO: if the window is only partly visible, then truncate width/height. # This could be important if we have nested ScrollablePanes. height=write_pos.height, width=write_pos.width, )
[ "def", "_copy_over_write_positions", "(", "self", ",", "screen", ":", "Screen", ",", "temp_screen", ":", "Screen", ",", "write_position", ":", "WritePosition", ")", "->", "None", ":", "ypos", "=", "write_position", ".", "ypos", "xpos", "=", "write_position", ".", "xpos", "for", "win", ",", "write_pos", "in", "temp_screen", ".", "visible_windows_to_write_positions", ".", "items", "(", ")", ":", "screen", ".", "visible_windows_to_write_positions", "[", "win", "]", "=", "WritePosition", "(", "xpos", "=", "write_pos", ".", "xpos", "+", "xpos", ",", "ypos", "=", "write_pos", ".", "ypos", "+", "ypos", "-", "self", ".", "vertical_scroll", ",", "# TODO: if the window is only partly visible, then truncate width/height.", "# This could be important if we have nested ScrollablePanes.", "height", "=", "write_pos", ".", "height", ",", "width", "=", "write_pos", ".", "width", ",", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/scrollable_pane.py#L328-L345
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/queues.py
python
Queue.put_nowait
(self, item)
Put an item into the queue without blocking. If no free slot is immediately available, raise QueueFull.
Put an item into the queue without blocking.
[ "Put", "an", "item", "into", "the", "queue", "without", "blocking", "." ]
def put_nowait(self, item): """Put an item into the queue without blocking. If no free slot is immediately available, raise QueueFull. """ if self.full(): raise QueueFull self._put(item) self._unfinished_tasks += 1 self._finished.clear() self._wakeup_next(self._getters)
[ "def", "put_nowait", "(", "self", ",", "item", ")", ":", "if", "self", ".", "full", "(", ")", ":", "raise", "QueueFull", "self", ".", "_put", "(", "item", ")", "self", ".", "_unfinished_tasks", "+=", "1", "self", ".", "_finished", ".", "clear", "(", ")", "self", ".", "_wakeup_next", "(", "self", ".", "_getters", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/queues.py#L138-L148
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/eager/graph_callable.py
python
_VariableCapturingScope.initializing_scope
(self)
Context manager to capture variable creations. Forcibly initializes all created variables. Yields: nothing
Context manager to capture variable creations.
[ "Context", "manager", "to", "capture", "variable", "creations", "." ]
def initializing_scope(self): """Context manager to capture variable creations. Forcibly initializes all created variables. Yields: nothing """ # TODO(apassos) ignoring the regularizer and partitioner here; figure out # how to deal with these. def _custom_getter(getter=None, name=None, shape=None, dtype=dtypes.float32, # pylint: disable=missing-docstring initializer=None, regularizer=None, reuse=None, trainable=True, collections=None, caching_device=None, # pylint: disable=redefined-outer-name partitioner=None, validate_shape=True, use_resource=None): del getter, regularizer, collections, caching_device, partitioner del use_resource, validate_shape if name in self.tf_variables: if reuse: return self.tf_variables[name].initialized_value() else: raise ValueError("Specified reuse=%s but tried to reuse variables." % reuse) # TODO(apassos): ensure this is on the same device as above v = _CapturedVariable(name, initializer, shape, dtype, trainable) self.variables[name] = v graph_mode_resource = v.variable.handle if initializer is None: initializer = _default_initializer(name, shape, dtype) resource_variable_ops.assign_variable_op( graph_mode_resource, initializer(shape, dtype)) return v.variable scope = variable_scope.get_variable_scope() with variable_scope.variable_scope(scope, custom_getter=_custom_getter): yield
[ "def", "initializing_scope", "(", "self", ")", ":", "# TODO(apassos) ignoring the regularizer and partitioner here; figure out", "# how to deal with these.", "def", "_custom_getter", "(", "getter", "=", "None", ",", "name", "=", "None", ",", "shape", "=", "None", ",", "dtype", "=", "dtypes", ".", "float32", ",", "# pylint: disable=missing-docstring", "initializer", "=", "None", ",", "regularizer", "=", "None", ",", "reuse", "=", "None", ",", "trainable", "=", "True", ",", "collections", "=", "None", ",", "caching_device", "=", "None", ",", "# pylint: disable=redefined-outer-name", "partitioner", "=", "None", ",", "validate_shape", "=", "True", ",", "use_resource", "=", "None", ")", ":", "del", "getter", ",", "regularizer", ",", "collections", ",", "caching_device", ",", "partitioner", "del", "use_resource", ",", "validate_shape", "if", "name", "in", "self", ".", "tf_variables", ":", "if", "reuse", ":", "return", "self", ".", "tf_variables", "[", "name", "]", ".", "initialized_value", "(", ")", "else", ":", "raise", "ValueError", "(", "\"Specified reuse=%s but tried to reuse variables.\"", "%", "reuse", ")", "# TODO(apassos): ensure this is on the same device as above", "v", "=", "_CapturedVariable", "(", "name", ",", "initializer", ",", "shape", ",", "dtype", ",", "trainable", ")", "self", ".", "variables", "[", "name", "]", "=", "v", "graph_mode_resource", "=", "v", ".", "variable", ".", "handle", "if", "initializer", "is", "None", ":", "initializer", "=", "_default_initializer", "(", "name", ",", "shape", ",", "dtype", ")", "resource_variable_ops", ".", "assign_variable_op", "(", "graph_mode_resource", ",", "initializer", "(", "shape", ",", "dtype", ")", ")", "return", "v", ".", "variable", "scope", "=", "variable_scope", ".", "get_variable_scope", "(", ")", "with", "variable_scope", ".", "variable_scope", "(", "scope", ",", "custom_getter", "=", "_custom_getter", ")", ":", "yield" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/eager/graph_callable.py#L129-L165
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/wallet.py
python
Wallet.to_dict
(self)
return result
Returns the model properties as a dict
Returns the model properties as a dict
[ "Returns", "the", "model", "properties", "as", "a", "dict" ]
def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Wallet, dict): for key, value in self.items(): result[key] = value return result
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "attr", ",", "_", "in", "six", ".", "iteritems", "(", "self", ".", "swagger_types", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "result", "[", "attr", "]", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", ".", "to_dict", "(", ")", "if", "hasattr", "(", "x", ",", "\"to_dict\"", ")", "else", "x", ",", "value", ")", ")", "elif", "hasattr", "(", "value", ",", "\"to_dict\"", ")", ":", "result", "[", "attr", "]", "=", "value", ".", "to_dict", "(", ")", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "result", "[", "attr", "]", "=", "dict", "(", "map", "(", "lambda", "item", ":", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ".", "to_dict", "(", ")", ")", "if", "hasattr", "(", "item", "[", "1", "]", ",", "\"to_dict\"", ")", "else", "item", ",", "value", ".", "items", "(", ")", ")", ")", "else", ":", "result", "[", "attr", "]", "=", "value", "if", "issubclass", "(", "Wallet", ",", "dict", ")", ":", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", ":", "result", "[", "key", "]", "=", "value", "return", "result" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/wallet.py#L697-L722
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/elastic/rendezvous/c10d_rendezvous_backend.py
python
C10dRendezvousBackend.get_state
(self)
return self._decode_state(base64_state)
See base class.
See base class.
[ "See", "base", "class", "." ]
def get_state(self) -> Optional[Tuple[bytes, Token]]: """See base class.""" base64_state: bytes = self._call_store("get", self._key) return self._decode_state(base64_state)
[ "def", "get_state", "(", "self", ")", "->", "Optional", "[", "Tuple", "[", "bytes", ",", "Token", "]", "]", ":", "base64_state", ":", "bytes", "=", "self", ".", "_call_store", "(", "\"get\"", ",", "self", ".", "_key", ")", "return", "self", ".", "_decode_state", "(", "base64_state", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/rendezvous/c10d_rendezvous_backend.py#L71-L75
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ListCtrl.GetItemCount
(*args, **kwargs)
return _controls_.ListCtrl_GetItemCount(*args, **kwargs)
GetItemCount(self) -> int
GetItemCount(self) -> int
[ "GetItemCount", "(", "self", ")", "-", ">", "int" ]
def GetItemCount(*args, **kwargs): """GetItemCount(self) -> int""" return _controls_.ListCtrl_GetItemCount(*args, **kwargs)
[ "def", "GetItemCount", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_GetItemCount", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4567-L4569
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pyedbglib/protocols/jtagice3protocol.py
python
Jtagice3Protocol.set_le16
(self, context, offset, value)
Sets a little-endian 16-bit parameter :param context: context (address) to set :param offset: offset address to set :param value: value to set
Sets a little-endian 16-bit parameter
[ "Sets", "a", "little", "-", "endian", "16", "-", "bit", "parameter" ]
def set_le16(self, context, offset, value): """ Sets a little-endian 16-bit parameter :param context: context (address) to set :param offset: offset address to set :param value: value to set """ self._set_protocol(context, offset, binary.pack_le16(value))
[ "def", "set_le16", "(", "self", ",", "context", ",", "offset", ",", "value", ")", ":", "self", ".", "_set_protocol", "(", "context", ",", "offset", ",", "binary", ".", "pack_le16", "(", "value", ")", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/jtagice3protocol.py#L251-L259
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/pyprogress.py
python
PyProgress.GetFirstGradientColour
(self)
return self._gauge.GetFirstGradientColour()
Returns the gauge first gradient colour.
Returns the gauge first gradient colour.
[ "Returns", "the", "gauge", "first", "gradient", "colour", "." ]
def GetFirstGradientColour(self): """ Returns the gauge first gradient colour. """ return self._gauge.GetFirstGradientColour()
[ "def", "GetFirstGradientColour", "(", "self", ")", ":", "return", "self", ".", "_gauge", ".", "GetFirstGradientColour", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/pyprogress.py#L636-L639
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/distutils/dist.py
python
Distribution.parse_command_line
(self)
return True
Parse the setup script's command line, taken from the 'script_args' instance attribute (which defaults to 'sys.argv[1:]' -- see 'setup()' in core.py). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternately scanned for Distutils commands and options for that command. Each new command terminates the options for the previous command. The allowed options for a command are determined by the 'user_options' attribute of the command class -- thus, we have to be able to load command classes in order to parse the command line. Any error in that 'options' attribute raises DistutilsGetoptError; any error on the command-line raises DistutilsArgError. If no Distutils commands were found on the command line, raises DistutilsArgError. Return true if command-line was successfully parsed and we should carry on with executing commands; false if no errors but we shouldn't execute commands (currently, this only happens if user asks for help).
Parse the setup script's command line, taken from the 'script_args' instance attribute (which defaults to 'sys.argv[1:]' -- see 'setup()' in core.py). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternately scanned for Distutils commands and options for that command. Each new command terminates the options for the previous command. The allowed options for a command are determined by the 'user_options' attribute of the command class -- thus, we have to be able to load command classes in order to parse the command line. Any error in that 'options' attribute raises DistutilsGetoptError; any error on the command-line raises DistutilsArgError. If no Distutils commands were found on the command line, raises DistutilsArgError. Return true if command-line was successfully parsed and we should carry on with executing commands; false if no errors but we shouldn't execute commands (currently, this only happens if user asks for help).
[ "Parse", "the", "setup", "script", "s", "command", "line", "taken", "from", "the", "script_args", "instance", "attribute", "(", "which", "defaults", "to", "sys", ".", "argv", "[", "1", ":", "]", "--", "see", "setup", "()", "in", "core", ".", "py", ")", ".", "This", "list", "is", "first", "processed", "for", "global", "options", "--", "options", "that", "set", "attributes", "of", "the", "Distribution", "instance", ".", "Then", "it", "is", "alternately", "scanned", "for", "Distutils", "commands", "and", "options", "for", "that", "command", ".", "Each", "new", "command", "terminates", "the", "options", "for", "the", "previous", "command", ".", "The", "allowed", "options", "for", "a", "command", "are", "determined", "by", "the", "user_options", "attribute", "of", "the", "command", "class", "--", "thus", "we", "have", "to", "be", "able", "to", "load", "command", "classes", "in", "order", "to", "parse", "the", "command", "line", ".", "Any", "error", "in", "that", "options", "attribute", "raises", "DistutilsGetoptError", ";", "any", "error", "on", "the", "command", "-", "line", "raises", "DistutilsArgError", ".", "If", "no", "Distutils", "commands", "were", "found", "on", "the", "command", "line", "raises", "DistutilsArgError", ".", "Return", "true", "if", "command", "-", "line", "was", "successfully", "parsed", "and", "we", "should", "carry", "on", "with", "executing", "commands", ";", "false", "if", "no", "errors", "but", "we", "shouldn", "t", "execute", "commands", "(", "currently", "this", "only", "happens", "if", "user", "asks", "for", "help", ")", "." ]
def parse_command_line(self): """Parse the setup script's command line, taken from the 'script_args' instance attribute (which defaults to 'sys.argv[1:]' -- see 'setup()' in core.py). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternately scanned for Distutils commands and options for that command. Each new command terminates the options for the previous command. The allowed options for a command are determined by the 'user_options' attribute of the command class -- thus, we have to be able to load command classes in order to parse the command line. Any error in that 'options' attribute raises DistutilsGetoptError; any error on the command-line raises DistutilsArgError. If no Distutils commands were found on the command line, raises DistutilsArgError. Return true if command-line was successfully parsed and we should carry on with executing commands; false if no errors but we shouldn't execute commands (currently, this only happens if user asks for help). """ # # We now have enough information to show the Macintosh dialog # that allows the user to interactively specify the "command line". # toplevel_options = self._get_toplevel_options() # We have to parse the command line a bit at a time -- global # options, then the first command, then its options, and so on -- # because each command will be handled by a different class, and # the options that are valid for a particular class aren't known # until we have loaded the command class, which doesn't happen # until we know what the command is. self.commands = [] parser = FancyGetopt(toplevel_options + self.display_options) parser.set_negative_aliases(self.negative_opt) parser.set_aliases({'licence': 'license'}) args = parser.getopt(args=self.script_args, object=self) option_order = parser.get_option_order() log.set_verbosity(self.verbose) # for display options we return immediately if self.handle_display_options(option_order): return while args: args = self._parse_command_opts(parser, args) if args is None: # user asked for help (and got it) return # Handle the cases of --help as a "global" option, ie. # "setup.py --help" and "setup.py --help command ...". For the # former, we show global options (--verbose, --dry-run, etc.) # and display-only options (--name, --version, etc.); for the # latter, we omit the display-only options and show help for # each command listed on the command line. if self.help: self._show_help(parser, display_options=len(self.commands) == 0, commands=self.commands) return # Oops, no commands found -- an end-user error if not self.commands: raise DistutilsArgError("no commands supplied") # All is well: return true return True
[ "def", "parse_command_line", "(", "self", ")", ":", "#", "# We now have enough information to show the Macintosh dialog", "# that allows the user to interactively specify the \"command line\".", "#", "toplevel_options", "=", "self", ".", "_get_toplevel_options", "(", ")", "# We have to parse the command line a bit at a time -- global", "# options, then the first command, then its options, and so on --", "# because each command will be handled by a different class, and", "# the options that are valid for a particular class aren't known", "# until we have loaded the command class, which doesn't happen", "# until we know what the command is.", "self", ".", "commands", "=", "[", "]", "parser", "=", "FancyGetopt", "(", "toplevel_options", "+", "self", ".", "display_options", ")", "parser", ".", "set_negative_aliases", "(", "self", ".", "negative_opt", ")", "parser", ".", "set_aliases", "(", "{", "'licence'", ":", "'license'", "}", ")", "args", "=", "parser", ".", "getopt", "(", "args", "=", "self", ".", "script_args", ",", "object", "=", "self", ")", "option_order", "=", "parser", ".", "get_option_order", "(", ")", "log", ".", "set_verbosity", "(", "self", ".", "verbose", ")", "# for display options we return immediately", "if", "self", ".", "handle_display_options", "(", "option_order", ")", ":", "return", "while", "args", ":", "args", "=", "self", ".", "_parse_command_opts", "(", "parser", ",", "args", ")", "if", "args", "is", "None", ":", "# user asked for help (and got it)", "return", "# Handle the cases of --help as a \"global\" option, ie.", "# \"setup.py --help\" and \"setup.py --help command ...\". For the", "# former, we show global options (--verbose, --dry-run, etc.)", "# and display-only options (--name, --version, etc.); for the", "# latter, we omit the display-only options and show help for", "# each command listed on the command line.", "if", "self", ".", "help", ":", "self", ".", "_show_help", "(", "parser", ",", "display_options", "=", "len", "(", "self", ".", "commands", ")", "==", "0", ",", "commands", "=", "self", ".", "commands", ")", "return", "# Oops, no commands found -- an end-user error", "if", "not", "self", ".", "commands", ":", "raise", "DistutilsArgError", "(", "\"no commands supplied\"", ")", "# All is well: return true", "return", "True" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/dist.py#L439-L504
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
tools/pytorch-quantization/pytorch_quantization/nn/modules/_utils.py
python
pop_quant_desc_in_kwargs
(quant_cls, input_only=False, **kwargs)
return quant_desc_input, quant_desc_weight
Pop quant descriptors in kwargs If there is no descriptor in kwargs, the default one in quant_cls will be used Arguments: quant_cls: A class that has default quantization descriptors input_only: A boolean. If True, pop quant_desc_input only, not quant_desc_weight. Default false. Keyword Arguments: quant_desc_input: An instance of :class:`QuantDescriptor <pytorch_quantization.tensor_quant.QuantDescriptor>`. Quantization descriptor of input. quant_desc_weight: An instance of :class:`QuantDescriptor <pytorch_quantization.tensor_quant.QuantDescriptor>`. Quantization descriptor of weight.
Pop quant descriptors in kwargs
[ "Pop", "quant", "descriptors", "in", "kwargs" ]
def pop_quant_desc_in_kwargs(quant_cls, input_only=False, **kwargs): """Pop quant descriptors in kwargs If there is no descriptor in kwargs, the default one in quant_cls will be used Arguments: quant_cls: A class that has default quantization descriptors input_only: A boolean. If True, pop quant_desc_input only, not quant_desc_weight. Default false. Keyword Arguments: quant_desc_input: An instance of :class:`QuantDescriptor <pytorch_quantization.tensor_quant.QuantDescriptor>`. Quantization descriptor of input. quant_desc_weight: An instance of :class:`QuantDescriptor <pytorch_quantization.tensor_quant.QuantDescriptor>`. Quantization descriptor of weight. """ quant_desc_input = kwargs.pop('quant_desc_input', quant_cls.default_quant_desc_input) if not input_only: quant_desc_weight = kwargs.pop('quant_desc_weight', quant_cls.default_quant_desc_weight) # Check if anything is left in **kwargs if kwargs: raise TypeError("Unused keys: {}".format(kwargs.keys())) if input_only: return quant_desc_input return quant_desc_input, quant_desc_weight
[ "def", "pop_quant_desc_in_kwargs", "(", "quant_cls", ",", "input_only", "=", "False", ",", "*", "*", "kwargs", ")", ":", "quant_desc_input", "=", "kwargs", ".", "pop", "(", "'quant_desc_input'", ",", "quant_cls", ".", "default_quant_desc_input", ")", "if", "not", "input_only", ":", "quant_desc_weight", "=", "kwargs", ".", "pop", "(", "'quant_desc_weight'", ",", "quant_cls", ".", "default_quant_desc_weight", ")", "# Check if anything is left in **kwargs", "if", "kwargs", ":", "raise", "TypeError", "(", "\"Unused keys: {}\"", ".", "format", "(", "kwargs", ".", "keys", "(", ")", ")", ")", "if", "input_only", ":", "return", "quant_desc_input", "return", "quant_desc_input", ",", "quant_desc_weight" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/pytorch-quantization/pytorch_quantization/nn/modules/_utils.py#L139-L164
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/classcalc/calc.py
python
Calc.t_NUMBER
(self, t)
return t
r'\d+
r'\d+
[ "r", "\\", "d", "+" ]
def t_NUMBER(self, t): r'\d+' try: t.value = int(t.value) except ValueError: print("Integer value too large %s" % t.value) t.value = 0 #print "parsed number %s" % repr(t.value) return t
[ "def", "t_NUMBER", "(", "self", ",", "t", ")", ":", "try", ":", "t", ".", "value", "=", "int", "(", "t", ".", "value", ")", "except", "ValueError", ":", "print", "(", "\"Integer value too large %s\"", "%", "t", ".", "value", ")", "t", ".", "value", "=", "0", "#print \"parsed number %s\" % repr(t.value)", "return", "t" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/classcalc/calc.py#L77-L85
PlatformLab/RAMCloud
b1866af19124325a6dfd8cbc267e2e3ef1f965d1
cpplint.py
python
ProcessFile
(filename, vlevel)
Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default.
Does google-lint on a single file.
[ "Does", "google", "-", "lint", "on", "a", "single", "file", "." ]
def ProcessFile(filename, vlevel): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. """ _SetVerboseLevel(vlevel) try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. If it is not expected to be present (i.e. os.linesep != # '\r\n' as in Windows), a warning is issued below if this file # is processed. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') carriage_return_found = False # Remove trailing '\r'. for linenum in range(len(lines)): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') carriage_return_found = True except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if (filename != '-' and file_extension != 'cc' and file_extension != 'h' and file_extension != 'cpp' and file_extension != 'c'): sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename) else: ProcessFileData(filename, file_extension, lines, Error) if carriage_return_found and os.linesep != '\r\n': # Use 0 for linenum since outputing only one error for potentially # several lines. Error(filename, 0, 'whitespace/newline', 1, 'One or more unexpected \\r (^M) found;' 'better to use only a \\n')
[ "def", "ProcessFile", "(", "filename", ",", "vlevel", ")", ":", "_SetVerboseLevel", "(", "vlevel", ")", "try", ":", "# Support the UNIX convention of using \"-\" for stdin. Note that", "# we are not opening the file with universal newline support", "# (which codecs doesn't support anyway), so the resulting lines do", "# contain trailing '\\r' characters if we are reading a file that", "# has CRLF endings.", "# If after the split a trailing '\\r' is present, it is removed", "# below. If it is not expected to be present (i.e. os.linesep !=", "# '\\r\\n' as in Windows), a warning is issued below if this file", "# is processed.", "if", "filename", "==", "'-'", ":", "lines", "=", "codecs", ".", "StreamReaderWriter", "(", "sys", ".", "stdin", ",", "codecs", ".", "getreader", "(", "'utf8'", ")", ",", "codecs", ".", "getwriter", "(", "'utf8'", ")", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "else", ":", "lines", "=", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "carriage_return_found", "=", "False", "# Remove trailing '\\r'.", "for", "linenum", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "if", "lines", "[", "linenum", "]", ".", "endswith", "(", "'\\r'", ")", ":", "lines", "[", "linenum", "]", "=", "lines", "[", "linenum", "]", ".", "rstrip", "(", "'\\r'", ")", "carriage_return_found", "=", "True", "except", "IOError", ":", "sys", ".", "stderr", ".", "write", "(", "\"Skipping input '%s': Can't open for reading\\n\"", "%", "filename", ")", "return", "# Note, if no dot is found, this will give the entire filename as the ext.", "file_extension", "=", "filename", "[", "filename", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "# When reading from stdin, the extension is unknown, so no cpplint tests", "# should rely on the extension.", "if", "(", "filename", "!=", "'-'", "and", "file_extension", "!=", "'cc'", "and", "file_extension", "!=", "'h'", "and", "file_extension", "!=", "'cpp'", "and", "file_extension", "!=", "'c'", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Ignoring %s; not a .cc or .h file\\n'", "%", "filename", ")", "else", ":", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "Error", ")", "if", "carriage_return_found", "and", "os", ".", "linesep", "!=", "'\\r\\n'", ":", "# Use 0 for linenum since outputing only one error for potentially", "# several lines.", "Error", "(", "filename", ",", "0", ",", "'whitespace/newline'", ",", "1", ",", "'One or more unexpected \\\\r (^M) found;'", "'better to use only a \\\\n'", ")" ]
https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/cpplint.py#L2944-L3002
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/factory.py
python
ResourceFactory._create_identifier
(factory_self, identifier, resource_name)
return property(get_identifier)
Creates a read-only property for identifier attributes.
Creates a read-only property for identifier attributes.
[ "Creates", "a", "read", "-", "only", "property", "for", "identifier", "attributes", "." ]
def _create_identifier(factory_self, identifier, resource_name): """ Creates a read-only property for identifier attributes. """ def get_identifier(self): # The default value is set to ``None`` instead of # raising an AttributeError because when resources are # instantiated a check is made such that none of the # identifiers have a value ``None``. If any are ``None``, # a more informative user error than a generic AttributeError # is raised. return getattr(self, '_' + identifier.name, None) get_identifier.__name__ = str(identifier.name) get_identifier.__doc__ = docstring.IdentifierDocstring( resource_name=resource_name, identifier_model=identifier, include_signature=False ) return property(get_identifier)
[ "def", "_create_identifier", "(", "factory_self", ",", "identifier", ",", "resource_name", ")", ":", "def", "get_identifier", "(", "self", ")", ":", "# The default value is set to ``None`` instead of", "# raising an AttributeError because when resources are", "# instantiated a check is made such that none of the", "# identifiers have a value ``None``. If any are ``None``,", "# a more informative user error than a generic AttributeError", "# is raised.", "return", "getattr", "(", "self", ",", "'_'", "+", "identifier", ".", "name", ",", "None", ")", "get_identifier", ".", "__name__", "=", "str", "(", "identifier", ".", "name", ")", "get_identifier", ".", "__doc__", "=", "docstring", ".", "IdentifierDocstring", "(", "resource_name", "=", "resource_name", ",", "identifier_model", "=", "identifier", ",", "include_signature", "=", "False", ")", "return", "property", "(", "get_identifier", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/factory.py#L284-L304
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
PyControl.DoSetClientSize
(*args, **kwargs)
return _controls_.PyControl_DoSetClientSize(*args, **kwargs)
DoSetClientSize(self, int width, int height)
DoSetClientSize(self, int width, int height)
[ "DoSetClientSize", "(", "self", "int", "width", "int", "height", ")" ]
def DoSetClientSize(*args, **kwargs): """DoSetClientSize(self, int width, int height)""" return _controls_.PyControl_DoSetClientSize(*args, **kwargs)
[ "def", "DoSetClientSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "PyControl_DoSetClientSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5850-L5852
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/syntax.py
python
SymbolTable.get_generic_reply_field_list
(self, name)
return None
Get a generic reply field list from the SymbolTable based on the list name.
Get a generic reply field list from the SymbolTable based on the list name.
[ "Get", "a", "generic", "reply", "field", "list", "from", "the", "SymbolTable", "based", "on", "the", "list", "name", "." ]
def get_generic_reply_field_list(self, name): # type: (str) -> GenericReplyFieldList """Get a generic reply field list from the SymbolTable based on the list name.""" for gen_reply_field_list in self.generic_reply_field_lists: if gen_reply_field_list.name == name: return gen_reply_field_list return None
[ "def", "get_generic_reply_field_list", "(", "self", ",", "name", ")", ":", "# type: (str) -> GenericReplyFieldList", "for", "gen_reply_field_list", "in", "self", ".", "generic_reply_field_lists", ":", "if", "gen_reply_field_list", ".", "name", "==", "name", ":", "return", "gen_reply_field_list", "return", "None" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/syntax.py#L219-L225
Netflix/NfWebCrypto
499faf4eb9f9ccf0b21dc728e974970f54bd6c52
plugin/ppapi/ppapi/generators/idl_parser.py
python
IDLParser.p_value
(self, p)
value : FLOAT | HEX | INT | OCT | STRING
value : FLOAT | HEX | INT | OCT | STRING
[ "value", ":", "FLOAT", "|", "HEX", "|", "INT", "|", "OCT", "|", "STRING" ]
def p_value(self, p): """value : FLOAT | HEX | INT | OCT | STRING""" p[0] = p[1] if self.parse_debug: DumpReduction('value', p)
[ "def", "p_value", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "if", "self", ".", "parse_debug", ":", "DumpReduction", "(", "'value'", ",", "p", ")" ]
https://github.com/Netflix/NfWebCrypto/blob/499faf4eb9f9ccf0b21dc728e974970f54bd6c52/plugin/ppapi/ppapi/generators/idl_parser.py#L475-L482
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributions/transformed_distribution.py
python
TransformedDistribution.rsample
(self, sample_shape=torch.Size())
return x
Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples if the distribution parameters are batched. Samples first from base distribution and applies `transform()` for every transform in the list.
Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples if the distribution parameters are batched. Samples first from base distribution and applies `transform()` for every transform in the list.
[ "Generates", "a", "sample_shape", "shaped", "reparameterized", "sample", "or", "sample_shape", "shaped", "batch", "of", "reparameterized", "samples", "if", "the", "distribution", "parameters", "are", "batched", ".", "Samples", "first", "from", "base", "distribution", "and", "applies", "transform", "()", "for", "every", "transform", "in", "the", "list", "." ]
def rsample(self, sample_shape=torch.Size()): """ Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples if the distribution parameters are batched. Samples first from base distribution and applies `transform()` for every transform in the list. """ x = self.base_dist.rsample(sample_shape) for transform in self.transforms: x = transform(x) return x
[ "def", "rsample", "(", "self", ",", "sample_shape", "=", "torch", ".", "Size", "(", ")", ")", ":", "x", "=", "self", ".", "base_dist", ".", "rsample", "(", "sample_shape", ")", "for", "transform", "in", "self", ".", "transforms", ":", "x", "=", "transform", "(", "x", ")", "return", "x" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributions/transformed_distribution.py#L120-L130
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py
python
PhactoriImagesetBlock.ClearPvViewAndPvRepAfterWriteImage
(self)
Since it turns out to be much more memory efficient to reuse a single render view rather than having one per image, this routine is called immediately after WriteImage in order to make stuff invisible again before the next item gets a chance to do WriteImage
Since it turns out to be much more memory efficient to reuse a single render view rather than having one per image, this routine is called immediately after WriteImage in order to make stuff invisible again before the next item gets a chance to do WriteImage
[ "Since", "it", "turns", "out", "to", "be", "much", "more", "memory", "efficient", "to", "reuse", "a", "single", "render", "view", "rather", "than", "having", "one", "per", "image", "this", "routine", "is", "called", "immediately", "after", "WriteImage", "in", "order", "to", "make", "stuff", "invisible", "again", "before", "the", "next", "item", "gets", "a", "chance", "to", "do", "WriteImage" ]
def ClearPvViewAndPvRepAfterWriteImage(self): """Since it turns out to be much more memory efficient to reuse a single render view rather than having one per image, this routine is called immediately after WriteImage in order to make stuff invisible again before the next item gets a chance to do WriteImage""" #if PhactoriDbg(150): # myDebugPrint3("ClearPvViewAndPvRepAfterWriteImage entered\n", 150) #cube axes invisible ShowCubeAxesXX(self.mSharedPvRenderView2, 'off') #3d/pointset dataset invisible (plot or 3d viewing) self.mPvDataRepresentation2.Visibility = 0 #color legend invisible, if 3d viewing for oneColorLegendRepRef in self.mColorLegendRepRefs: if oneColorLegendRepRef != None: if PhactoriDbg(100): myDebugPrint3("C inColorLegendRepRef was " + \ str(oneColorLegendRepRef.Visibility) + \ " now 0: " + str(oneColorLegendRepRef) + "\n") oneColorLegendRepRef.Visibility = 0 #time annotation invisible (for 3d plot) timeAnnStngs = self.mRepresentation.mTimeAnnotationSettings if timeAnnStngs.mVisible: global gPipeAndViewsState if gPipeAndViewsState.mTimeAnnotationPv != None: gPipeAndViewsState.mTimeAnnotationPv.\ mParaViewRepresentation.Visibility = 0 #markers for this imageset made invisible for oneMarker in self.mVisibleMarkers: oneMarker.MakeInvisible() for oneTextAnnotation in self.mTextAnnotations: oneTextAnnotation.MakeInvisible() #do extra visible operations/representations ii = 1 while ii < len(self.mVisibleReps): oneVisPvDataRep = self.mVisiblePvDataReps[ii] if(oneVisPvDataRep != None): oneVisPvDataRep.Visibility = 0 #this is already done above #oneColorLegendRepRef = self.mColorLegendRepRefs[ii] #if(oneColorLegendRepRef != None): # oneColorLegendRepRef.Visbility = 0 ii += 1
[ "def", "ClearPvViewAndPvRepAfterWriteImage", "(", "self", ")", ":", "#if PhactoriDbg(150):", "# myDebugPrint3(\"ClearPvViewAndPvRepAfterWriteImage entered\\n\", 150)", "#cube axes invisible", "ShowCubeAxesXX", "(", "self", ".", "mSharedPvRenderView2", ",", "'off'", ")", "#3d/pointset dataset invisible (plot or 3d viewing)", "self", ".", "mPvDataRepresentation2", ".", "Visibility", "=", "0", "#color legend invisible, if 3d viewing", "for", "oneColorLegendRepRef", "in", "self", ".", "mColorLegendRepRefs", ":", "if", "oneColorLegendRepRef", "!=", "None", ":", "if", "PhactoriDbg", "(", "100", ")", ":", "myDebugPrint3", "(", "\"C inColorLegendRepRef was \"", "+", "str", "(", "oneColorLegendRepRef", ".", "Visibility", ")", "+", "\" now 0: \"", "+", "str", "(", "oneColorLegendRepRef", ")", "+", "\"\\n\"", ")", "oneColorLegendRepRef", ".", "Visibility", "=", "0", "#time annotation invisible (for 3d plot)", "timeAnnStngs", "=", "self", ".", "mRepresentation", ".", "mTimeAnnotationSettings", "if", "timeAnnStngs", ".", "mVisible", ":", "global", "gPipeAndViewsState", "if", "gPipeAndViewsState", ".", "mTimeAnnotationPv", "!=", "None", ":", "gPipeAndViewsState", ".", "mTimeAnnotationPv", ".", "mParaViewRepresentation", ".", "Visibility", "=", "0", "#markers for this imageset made invisible", "for", "oneMarker", "in", "self", ".", "mVisibleMarkers", ":", "oneMarker", ".", "MakeInvisible", "(", ")", "for", "oneTextAnnotation", "in", "self", ".", "mTextAnnotations", ":", "oneTextAnnotation", ".", "MakeInvisible", "(", ")", "#do extra visible operations/representations", "ii", "=", "1", "while", "ii", "<", "len", "(", "self", ".", "mVisibleReps", ")", ":", "oneVisPvDataRep", "=", "self", ".", "mVisiblePvDataReps", "[", "ii", "]", "if", "(", "oneVisPvDataRep", "!=", "None", ")", ":", "oneVisPvDataRep", ".", "Visibility", "=", "0", "#this is already done above", "#oneColorLegendRepRef = self.mColorLegendRepRefs[ii]", "#if(oneColorLegendRepRef != None):", "# oneColorLegendRepRef.Visbility = 0", "ii", "+=", "1" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py#L9841-L9889
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py
python
Context.get_verify_mode
(self)
return _lib.SSL_CTX_get_verify_mode(self._context)
Retrieve the Context object's verify mode, as set by :meth:`set_verify`. :return: The verify mode
Retrieve the Context object's verify mode, as set by :meth:`set_verify`.
[ "Retrieve", "the", "Context", "object", "s", "verify", "mode", "as", "set", "by", ":", "meth", ":", "set_verify", "." ]
def get_verify_mode(self): """ Retrieve the Context object's verify mode, as set by :meth:`set_verify`. :return: The verify mode """ return _lib.SSL_CTX_get_verify_mode(self._context)
[ "def", "get_verify_mode", "(", "self", ")", ":", "return", "_lib", ".", "SSL_CTX_get_verify_mode", "(", "self", ".", "_context", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py#L1136-L1143
leela-zero/leela-zero
e3ed6310d33d75078ba74c3adf887d18439fc2e3
scripts/cpplint.py
python
CheckForFunctionLengths
(filename, clean_lines, linenum, function_state, error)
Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found.
Reports for long function bodies.
[ "Reports", "for", "long", "function", "bodies", "." ]
def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count()
[ "def", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "function_state", ",", "error", ")", ":", "lines", "=", "clean_lines", ".", "lines", "line", "=", "lines", "[", "linenum", "]", "joined_line", "=", "''", "starting_func", "=", "False", "regexp", "=", "r'(\\w(\\w|::|\\*|\\&|\\s)*)\\('", "# decls * & space::name( ...", "match_result", "=", "Match", "(", "regexp", ",", "line", ")", "if", "match_result", ":", "# If the name is all caps and underscores, figure it's a macro and", "# ignore it, unless it's TEST or TEST_F.", "function_name", "=", "match_result", ".", "group", "(", "1", ")", ".", "split", "(", ")", "[", "-", "1", "]", "if", "function_name", "==", "'TEST'", "or", "function_name", "==", "'TEST_F'", "or", "(", "not", "Match", "(", "r'[A-Z_]+$'", ",", "function_name", ")", ")", ":", "starting_func", "=", "True", "if", "starting_func", ":", "body_found", "=", "False", "for", "start_linenum", "in", "xrange", "(", "linenum", ",", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "start_line", "=", "lines", "[", "start_linenum", "]", "joined_line", "+=", "' '", "+", "start_line", ".", "lstrip", "(", ")", "if", "Search", "(", "r'(;|})'", ",", "start_line", ")", ":", "# Declarations and trivial functions", "body_found", "=", "True", "break", "# ... ignore", "elif", "Search", "(", "r'{'", ",", "start_line", ")", ":", "body_found", "=", "True", "function", "=", "Search", "(", "r'((\\w|:)*)\\('", ",", "line", ")", ".", "group", "(", "1", ")", "if", "Match", "(", "r'TEST'", ",", "function", ")", ":", "# Handle TEST... macros", "parameter_regexp", "=", "Search", "(", "r'(\\(.*\\))'", ",", "joined_line", ")", "if", "parameter_regexp", ":", "# Ignore bad syntax", "function", "+=", "parameter_regexp", ".", "group", "(", "1", ")", "else", ":", "function", "+=", "'()'", "function_state", ".", "Begin", "(", "function", ")", "break", "if", "not", "body_found", ":", "# No body for the function (or evidence of a non-function) was found.", "error", "(", "filename", ",", "linenum", ",", "'readability/fn_size'", ",", "5", ",", "'Lint failed to find start of function body.'", ")", "elif", "Match", "(", "r'^\\}\\s*$'", ",", "line", ")", ":", "# function end", "function_state", ".", "Check", "(", "error", ",", "filename", ",", "linenum", ")", "function_state", ".", "End", "(", ")", "elif", "not", "Match", "(", "r'^\\s*$'", ",", "line", ")", ":", "function_state", ".", "Count", "(", ")" ]
https://github.com/leela-zero/leela-zero/blob/e3ed6310d33d75078ba74c3adf887d18439fc2e3/scripts/cpplint.py#L2831-L2896
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/tooltip.py
python
OnHoverTooltipBase.hidetip
(self)
hide the tooltip
hide the tooltip
[ "hide", "the", "tooltip" ]
def hidetip(self): """hide the tooltip""" try: self.unschedule() except TclError: # pragma: no cover pass super(OnHoverTooltipBase, self).hidetip()
[ "def", "hidetip", "(", "self", ")", ":", "try", ":", "self", ".", "unschedule", "(", ")", "except", "TclError", ":", "# pragma: no cover", "pass", "super", "(", "OnHoverTooltipBase", ",", "self", ")", ".", "hidetip", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/tooltip.py#L136-L142
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/matlib.py
python
identity
(n,dtype=None)
return b
Returns the square identity matrix of given size. Parameters ---------- n : int Size of the returned identity matrix. dtype : data-type, optional Data-type of the output. Defaults to ``float``. Returns ------- out : matrix `n` x `n` matrix with its main diagonal set to one, and all other elements zero. See Also -------- numpy.identity : Equivalent array function. matlib.eye : More general matrix identity function. Examples -------- >>> import numpy.matlib >>> np.matlib.identity(3, dtype=int) matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
Returns the square identity matrix of given size.
[ "Returns", "the", "square", "identity", "matrix", "of", "given", "size", "." ]
def identity(n,dtype=None): """ Returns the square identity matrix of given size. Parameters ---------- n : int Size of the returned identity matrix. dtype : data-type, optional Data-type of the output. Defaults to ``float``. Returns ------- out : matrix `n` x `n` matrix with its main diagonal set to one, and all other elements zero. See Also -------- numpy.identity : Equivalent array function. matlib.eye : More general matrix identity function. Examples -------- >>> import numpy.matlib >>> np.matlib.identity(3, dtype=int) matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) """ a = array([1]+n*[0], dtype=dtype) b = empty((n, n), dtype=dtype) b.flat = a return b
[ "def", "identity", "(", "n", ",", "dtype", "=", "None", ")", ":", "a", "=", "array", "(", "[", "1", "]", "+", "n", "*", "[", "0", "]", ",", "dtype", "=", "dtype", ")", "b", "=", "empty", "(", "(", "n", ",", "n", ")", ",", "dtype", "=", "dtype", ")", "b", ".", "flat", "=", "a", "return", "b" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/matlib.py#L151-L185
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
HeaderColumn.GetBitmap
(*args, **kwargs)
return _core_.HeaderColumn_GetBitmap(*args, **kwargs)
GetBitmap(self) -> Bitmap
GetBitmap(self) -> Bitmap
[ "GetBitmap", "(", "self", ")", "-", ">", "Bitmap" ]
def GetBitmap(*args, **kwargs): """GetBitmap(self) -> Bitmap""" return _core_.HeaderColumn_GetBitmap(*args, **kwargs)
[ "def", "GetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "HeaderColumn_GetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L16388-L16390
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/spatial/transform/rotation.py
python
Rotation.as_quat
(self)
Represent as quaternions. Rotations in 3 dimensions can be represented using unit norm quaternions [1]_. The mapping from quaternions to rotations is two-to-one, i.e. quaternions `q` and `-q`, where `-q` simply reverses the sign of each component, represent the same spatial rotation. Returns ------- quat : `numpy.ndarray`, shape (4,) or (N, 4) Shape depends on shape of inputs used for initialization. References ---------- .. [1] `Quaternions and Spatial Rotation <https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation>`_ Examples -------- >>> from scipy.spatial.transform import Rotation as R Represent a single rotation: >>> r = R.from_dcm([ ... [0, -1, 0], ... [1, 0, 0], ... [0, 0, 1]]) >>> r.as_quat() array([0. , 0. , 0.70710678, 0.70710678]) >>> r.as_quat().shape (4,) Represent a stack with a single rotation: >>> r = R.from_quat([[0, 0, 0, 1]]) >>> r.as_quat().shape (1, 4) Represent multiple rotaions in a single object: >>> r = R.from_rotvec([[np.pi, 0, 0], [0, 0, np.pi/2]]) >>> r.as_quat().shape (2, 4)
Represent as quaternions.
[ "Represent", "as", "quaternions", "." ]
def as_quat(self): """Represent as quaternions. Rotations in 3 dimensions can be represented using unit norm quaternions [1]_. The mapping from quaternions to rotations is two-to-one, i.e. quaternions `q` and `-q`, where `-q` simply reverses the sign of each component, represent the same spatial rotation. Returns ------- quat : `numpy.ndarray`, shape (4,) or (N, 4) Shape depends on shape of inputs used for initialization. References ---------- .. [1] `Quaternions and Spatial Rotation <https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation>`_ Examples -------- >>> from scipy.spatial.transform import Rotation as R Represent a single rotation: >>> r = R.from_dcm([ ... [0, -1, 0], ... [1, 0, 0], ... [0, 0, 1]]) >>> r.as_quat() array([0. , 0. , 0.70710678, 0.70710678]) >>> r.as_quat().shape (4,) Represent a stack with a single rotation: >>> r = R.from_quat([[0, 0, 0, 1]]) >>> r.as_quat().shape (1, 4) Represent multiple rotaions in a single object: >>> r = R.from_rotvec([[np.pi, 0, 0], [0, 0, np.pi/2]]) >>> r.as_quat().shape (2, 4) """ if self._single: return self._quat[0].copy() else: return self._quat.copy()
[ "def", "as_quat", "(", "self", ")", ":", "if", "self", ".", "_single", ":", "return", "self", ".", "_quat", "[", "0", "]", ".", "copy", "(", ")", "else", ":", "return", "self", ".", "_quat", ".", "copy", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/spatial/transform/rotation.py#L846-L895
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_view.py
python
PlottingCanvasView.clear_all_workspaces_from_plot
(self)
Clears all workspaces from the plot
Clears all workspaces from the plot
[ "Clears", "all", "workspaces", "from", "the", "plot" ]
def clear_all_workspaces_from_plot(self): """Clears all workspaces from the plot""" for ax in self.fig.axes: ax.cla() ax.tracked_workspaces.clear() ax.set_prop_cycle(None) for color_queue in self._color_queue: color_queue.reset() for shaded_region in self._shaded_regions: shaded_region.remove() self._shaded_regions={} self._plot_information_list = []
[ "def", "clear_all_workspaces_from_plot", "(", "self", ")", ":", "for", "ax", "in", "self", ".", "fig", ".", "axes", ":", "ax", ".", "cla", "(", ")", "ax", ".", "tracked_workspaces", ".", "clear", "(", ")", "ax", ".", "set_prop_cycle", "(", "None", ")", "for", "color_queue", "in", "self", ".", "_color_queue", ":", "color_queue", ".", "reset", "(", ")", "for", "shaded_region", "in", "self", ".", "_shaded_regions", ":", "shaded_region", ".", "remove", "(", ")", "self", ".", "_shaded_regions", "=", "{", "}", "self", ".", "_plot_information_list", "=", "[", "]" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_view.py#L163-L177
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/embedded_find_replace_dialog/presenter.py
python
EmbeddedFindReplaceDialog.strings_different
(self, string1, string2, case_sensitive)
return (not case_sensitive and string1.lower() != string2.lower()) or (case_sensitive and string1 != string2)
:param case_sensitive: If case_sensitive is NOT selected, then both strings will be made lowercase Else the strings will be compared as they are without changes
[]
def strings_different(self, string1, string2, case_sensitive): """ :param case_sensitive: If case_sensitive is NOT selected, then both strings will be made lowercase Else the strings will be compared as they are without changes """ return (not case_sensitive and string1.lower() != string2.lower()) or (case_sensitive and string1 != string2)
[ "def", "strings_different", "(", "self", ",", "string1", ",", "string2", ",", "case_sensitive", ")", ":", "return", "(", "not", "case_sensitive", "and", "string1", ".", "lower", "(", ")", "!=", "string2", ".", "lower", "(", ")", ")", "or", "(", "case_sensitive", "and", "string1", "!=", "string2", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/embedded_find_replace_dialog/presenter.py#L129-L135
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/msvc.py
python
msvc14_get_vc_env
(plat_spec)
Patched "distutils._msvccompiler._get_vc_env" for support extra Microsoft Visual C++ 14.X compilers. Set environment without use of "vcvarsall.bat". Parameters ---------- plat_spec: str Target architecture. Return ------ dict environment
Patched "distutils._msvccompiler._get_vc_env" for support extra Microsoft Visual C++ 14.X compilers.
[ "Patched", "distutils", ".", "_msvccompiler", ".", "_get_vc_env", "for", "support", "extra", "Microsoft", "Visual", "C", "++", "14", ".", "X", "compilers", "." ]
def msvc14_get_vc_env(plat_spec): """ Patched "distutils._msvccompiler._get_vc_env" for support extra Microsoft Visual C++ 14.X compilers. Set environment without use of "vcvarsall.bat". Parameters ---------- plat_spec: str Target architecture. Return ------ dict environment """ # Always use backport from CPython 3.8 try: return _msvc14_get_vc_env(plat_spec) except distutils.errors.DistutilsPlatformError as exc: _augment_exception(exc, 14.0) raise
[ "def", "msvc14_get_vc_env", "(", "plat_spec", ")", ":", "# Always use backport from CPython 3.8", "try", ":", "return", "_msvc14_get_vc_env", "(", "plat_spec", ")", "except", "distutils", ".", "errors", ".", "DistutilsPlatformError", "as", "exc", ":", "_augment_exception", "(", "exc", ",", "14.0", ")", "raise" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/msvc.py#L294-L317
apple/foundationdb
f7118ad406f44ab7a33970fc8370647ed0085e18
layers/taskbucket/__init__.py
python
TaskBucket.get_one
(self, tr)
return taskDict
Gets a single task from the bucket, locks it so that only the caller will work on it for a while, and returns its taskDict. If there are no tasks in the bucket, returns None.
Gets a single task from the bucket, locks it so that only the caller will work on it for a while, and returns its taskDict. If there are no tasks in the bucket, returns None.
[ "Gets", "a", "single", "task", "from", "the", "bucket", "locks", "it", "so", "that", "only", "the", "caller", "will", "work", "on", "it", "for", "a", "while", "and", "returns", "its", "taskDict", ".", "If", "there", "are", "no", "tasks", "in", "the", "bucket", "returns", "None", "." ]
def get_one(self, tr): """Gets a single task from the bucket, locks it so that only the caller will work on it for a while, and returns its taskDict. If there are no tasks in the bucket, returns None.""" if self.system_access: tr.options.set_access_system_keys() k = tr.snapshot.get_key(fdb.KeySelector.last_less_or_equal(self.available.pack((random_key(),)))) if not k or k < self.available.pack(("",)): k = tr.snapshot.get_key(fdb.KeySelector.last_less_or_equal(self.available.pack((chr(255) * 16,)))) if not k or k < self.available.pack(("",)): if self.check_timeouts(tr): return self.get_one(tr) return None key = self.available.unpack(k)[0] avail = self.available[key] timeout = tr.get_read_version().wait() + long(self.timeout * (0.9 + 0.2 * random.random())) taskDict = {} for k, v in tr[avail.range(())]: tk, = avail.unpack(k) taskDict[tk] = v if tk != "type" or v != "": tr[self.timeouts.pack((timeout, key, tk))] = v del tr[avail.range(())] tr[self.active.key()] = random_key() taskDict["__task_key"] = key taskDict["__task_timeout"] = timeout return taskDict
[ "def", "get_one", "(", "self", ",", "tr", ")", ":", "if", "self", ".", "system_access", ":", "tr", ".", "options", ".", "set_access_system_keys", "(", ")", "k", "=", "tr", ".", "snapshot", ".", "get_key", "(", "fdb", ".", "KeySelector", ".", "last_less_or_equal", "(", "self", ".", "available", ".", "pack", "(", "(", "random_key", "(", ")", ",", ")", ")", ")", ")", "if", "not", "k", "or", "k", "<", "self", ".", "available", ".", "pack", "(", "(", "\"\"", ",", ")", ")", ":", "k", "=", "tr", ".", "snapshot", ".", "get_key", "(", "fdb", ".", "KeySelector", ".", "last_less_or_equal", "(", "self", ".", "available", ".", "pack", "(", "(", "chr", "(", "255", ")", "*", "16", ",", ")", ")", ")", ")", "if", "not", "k", "or", "k", "<", "self", ".", "available", ".", "pack", "(", "(", "\"\"", ",", ")", ")", ":", "if", "self", ".", "check_timeouts", "(", "tr", ")", ":", "return", "self", ".", "get_one", "(", "tr", ")", "return", "None", "key", "=", "self", ".", "available", ".", "unpack", "(", "k", ")", "[", "0", "]", "avail", "=", "self", ".", "available", "[", "key", "]", "timeout", "=", "tr", ".", "get_read_version", "(", ")", ".", "wait", "(", ")", "+", "long", "(", "self", ".", "timeout", "*", "(", "0.9", "+", "0.2", "*", "random", ".", "random", "(", ")", ")", ")", "taskDict", "=", "{", "}", "for", "k", ",", "v", "in", "tr", "[", "avail", ".", "range", "(", "(", ")", ")", "]", ":", "tk", ",", "=", "avail", ".", "unpack", "(", "k", ")", "taskDict", "[", "tk", "]", "=", "v", "if", "tk", "!=", "\"type\"", "or", "v", "!=", "\"\"", ":", "tr", "[", "self", ".", "timeouts", ".", "pack", "(", "(", "timeout", ",", "key", ",", "tk", ")", ")", "]", "=", "v", "del", "tr", "[", "avail", ".", "range", "(", "(", ")", ")", "]", "tr", "[", "self", ".", "active", ".", "key", "(", ")", "]", "=", "random_key", "(", ")", "taskDict", "[", "\"__task_key\"", "]", "=", "key", "taskDict", "[", "\"__task_timeout\"", "]", "=", "timeout", "return", "taskDict" ]
https://github.com/apple/foundationdb/blob/f7118ad406f44ab7a33970fc8370647ed0085e18/layers/taskbucket/__init__.py#L115-L144
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/web_perf/metrics/webrtc_rendering_stats.py
python
WebMediaPlayerMsRenderingStats._GetSmoothnessStats
(self, norm_drift_time)
return (percent_badly_oos, percent_out_of_sync, smoothness_score)
Get the smoothness stats from the normalized drift time. This method will calculate the smoothness score, along with the percentage of frames badly out of sync and the percentage of frames out of sync. To be considered badly out of sync, a frame has to have missed rendering by at least 2*VSYNC_DURATION. To be considered out of sync, a frame has to have missed rendering by at least one VSYNC_DURATION. The smoothness score is a measure of how out of sync the frames are. Args: norm_drift_time: normalized drift time. Returns: a tuple of (percent_badly_oos, percent_out_of_sync, smoothness_score)
Get the smoothness stats from the normalized drift time.
[ "Get", "the", "smoothness", "stats", "from", "the", "normalized", "drift", "time", "." ]
def _GetSmoothnessStats(self, norm_drift_time): """Get the smoothness stats from the normalized drift time. This method will calculate the smoothness score, along with the percentage of frames badly out of sync and the percentage of frames out of sync. To be considered badly out of sync, a frame has to have missed rendering by at least 2*VSYNC_DURATION. To be considered out of sync, a frame has to have missed rendering by at least one VSYNC_DURATION. The smoothness score is a measure of how out of sync the frames are. Args: norm_drift_time: normalized drift time. Returns: a tuple of (percent_badly_oos, percent_out_of_sync, smoothness_score) """ # How many times is a frame later/earlier than T=2*VSYNC_DURATION. Time is # in microseconds. frames_severely_out_of_sync = len( [x for x in norm_drift_time if abs(x) > 2 * VSYNC_DURATION]) percent_badly_oos = ( 100.0 * frames_severely_out_of_sync / len(norm_drift_time)) # How many times is a frame later/earlier than VSYNC_DURATION. frames_out_of_sync = len( [x for x in norm_drift_time if abs(x) > VSYNC_DURATION]) percent_out_of_sync = ( 100.0 * frames_out_of_sync / len(norm_drift_time)) frames_oos_only_once = frames_out_of_sync - frames_severely_out_of_sync # Calculate smoothness metric. From the formula, we can see that smoothness # score can be negative. smoothness_score = 100.0 - 100.0 * (frames_oos_only_once + SEVERITY * frames_severely_out_of_sync) / len(norm_drift_time) # Minimum smoothness_score value allowed is zero. if smoothness_score < 0: smoothness_score = 0 return (percent_badly_oos, percent_out_of_sync, smoothness_score)
[ "def", "_GetSmoothnessStats", "(", "self", ",", "norm_drift_time", ")", ":", "# How many times is a frame later/earlier than T=2*VSYNC_DURATION. Time is", "# in microseconds.", "frames_severely_out_of_sync", "=", "len", "(", "[", "x", "for", "x", "in", "norm_drift_time", "if", "abs", "(", "x", ")", ">", "2", "*", "VSYNC_DURATION", "]", ")", "percent_badly_oos", "=", "(", "100.0", "*", "frames_severely_out_of_sync", "/", "len", "(", "norm_drift_time", ")", ")", "# How many times is a frame later/earlier than VSYNC_DURATION.", "frames_out_of_sync", "=", "len", "(", "[", "x", "for", "x", "in", "norm_drift_time", "if", "abs", "(", "x", ")", ">", "VSYNC_DURATION", "]", ")", "percent_out_of_sync", "=", "(", "100.0", "*", "frames_out_of_sync", "/", "len", "(", "norm_drift_time", ")", ")", "frames_oos_only_once", "=", "frames_out_of_sync", "-", "frames_severely_out_of_sync", "# Calculate smoothness metric. From the formula, we can see that smoothness", "# score can be negative.", "smoothness_score", "=", "100.0", "-", "100.0", "*", "(", "frames_oos_only_once", "+", "SEVERITY", "*", "frames_severely_out_of_sync", ")", "/", "len", "(", "norm_drift_time", ")", "# Minimum smoothness_score value allowed is zero.", "if", "smoothness_score", "<", "0", ":", "smoothness_score", "=", "0", "return", "(", "percent_badly_oos", ",", "percent_out_of_sync", ",", "smoothness_score", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/web_perf/metrics/webrtc_rendering_stats.py#L264-L304
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/bdb.py
python
Bdb.user_call
(self, frame, argument_list)
This method is called when there is the remote possibility that we ever need to stop in this function.
This method is called when there is the remote possibility that we ever need to stop in this function.
[ "This", "method", "is", "called", "when", "there", "is", "the", "remote", "possibility", "that", "we", "ever", "need", "to", "stop", "in", "this", "function", "." ]
def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" pass
[ "def", "user_call", "(", "self", ",", "frame", ",", "argument_list", ")", ":", "pass" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/bdb.py#L157-L160
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/nn/utils/spectral_norm_hook.py
python
spectral_norm
(layer, name='weight', n_power_iterations=1, eps=1e-12, dim=None)
return layer
r""" This spectral_norm layer applies spectral normalization to a parameter according to the following Calculation: Step 1: Generate vector U in shape of [H], and V in shape of [W]. While H is the :attr:`dim` th dimension of the input weights, and W is the product result of remaining dimensions. Step 2: :attr:`n_power_iterations` should be a positive integer, do following calculations with U and V for :attr:`power_iters` rounds. .. math:: \mathbf{v} := \frac{\mathbf{W}^{T} \mathbf{u}}{\|\mathbf{W}^{T} \mathbf{u}\|_2} \mathbf{u} := \frac{\mathbf{W} \mathbf{v}}{\|\mathbf{W} \mathbf{v}\|_2} Step 3: Calculate :math:`\sigma(\mathbf{W})` and normalize weight values. .. math:: \sigma(\mathbf{W}) = \mathbf{u}^{T} \mathbf{W} \mathbf{v} \mathbf{W} = \frac{\mathbf{W}}{\sigma(\mathbf{W})} Refer to `Spectral Normalization <https://arxiv.org/abs/1802.05957>`_ . Parameters: layer(Layer): Layer of paddle, which has weight. name(str, optional): Name of the weight parameter. Default: 'weight'. n_power_iterations(int, optional): The number of power iterations to calculate spectral norm. Default: 1. eps(float, optional): The epsilon for numerical stability in calculating norms. Default: 1e-12. dim(int, optional): The index of dimension which should be permuted to the first before reshaping Input(Weight) to matrix, it should be set as 0 if Input(Weight) is the weight of fc layer, and should be set as 1 if Input(Weight) is the weight of conv layer. Default: None. Returns: The original layer with the spectral norm hook Examples: .. code-block:: python from paddle.nn import Conv2D from paddle.nn.utils import Spectralnorm conv = Conv2D(3, 1, 3) sn_conv = spectral_norm(conv) print(sn_conv) # Conv2D(3, 1, kernel_size=[3, 3], data_format=NCHW) print(sn_conv.weight) # Tensor(shape=[1, 3, 3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=False, # [[[[-0.21090528, 0.18563725, -0.14127982], # [-0.02310637, 0.03197737, 0.34353802], # [-0.17117859, 0.33152047, -0.28408015]], # # [[-0.13336606, -0.01862637, 0.06959272], # [-0.02236020, -0.27091628, -0.24532901], # [ 0.27254242, 0.15516677, 0.09036587]], # # [[ 0.30169338, -0.28146112, -0.11768346], # [-0.45765871, -0.12504843, -0.17482486], # [-0.36866254, -0.19969313, 0.08783543]]]])
r""" This spectral_norm layer applies spectral normalization to a parameter according to the following Calculation:
[ "r", "This", "spectral_norm", "layer", "applies", "spectral", "normalization", "to", "a", "parameter", "according", "to", "the", "following", "Calculation", ":" ]
def spectral_norm(layer, name='weight', n_power_iterations=1, eps=1e-12, dim=None): r""" This spectral_norm layer applies spectral normalization to a parameter according to the following Calculation: Step 1: Generate vector U in shape of [H], and V in shape of [W]. While H is the :attr:`dim` th dimension of the input weights, and W is the product result of remaining dimensions. Step 2: :attr:`n_power_iterations` should be a positive integer, do following calculations with U and V for :attr:`power_iters` rounds. .. math:: \mathbf{v} := \frac{\mathbf{W}^{T} \mathbf{u}}{\|\mathbf{W}^{T} \mathbf{u}\|_2} \mathbf{u} := \frac{\mathbf{W} \mathbf{v}}{\|\mathbf{W} \mathbf{v}\|_2} Step 3: Calculate :math:`\sigma(\mathbf{W})` and normalize weight values. .. math:: \sigma(\mathbf{W}) = \mathbf{u}^{T} \mathbf{W} \mathbf{v} \mathbf{W} = \frac{\mathbf{W}}{\sigma(\mathbf{W})} Refer to `Spectral Normalization <https://arxiv.org/abs/1802.05957>`_ . Parameters: layer(Layer): Layer of paddle, which has weight. name(str, optional): Name of the weight parameter. Default: 'weight'. n_power_iterations(int, optional): The number of power iterations to calculate spectral norm. Default: 1. eps(float, optional): The epsilon for numerical stability in calculating norms. Default: 1e-12. dim(int, optional): The index of dimension which should be permuted to the first before reshaping Input(Weight) to matrix, it should be set as 0 if Input(Weight) is the weight of fc layer, and should be set as 1 if Input(Weight) is the weight of conv layer. Default: None. Returns: The original layer with the spectral norm hook Examples: .. code-block:: python from paddle.nn import Conv2D from paddle.nn.utils import Spectralnorm conv = Conv2D(3, 1, 3) sn_conv = spectral_norm(conv) print(sn_conv) # Conv2D(3, 1, kernel_size=[3, 3], data_format=NCHW) print(sn_conv.weight) # Tensor(shape=[1, 3, 3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=False, # [[[[-0.21090528, 0.18563725, -0.14127982], # [-0.02310637, 0.03197737, 0.34353802], # [-0.17117859, 0.33152047, -0.28408015]], # # [[-0.13336606, -0.01862637, 0.06959272], # [-0.02236020, -0.27091628, -0.24532901], # [ 0.27254242, 0.15516677, 0.09036587]], # # [[ 0.30169338, -0.28146112, -0.11768346], # [-0.45765871, -0.12504843, -0.17482486], # [-0.36866254, -0.19969313, 0.08783543]]]]) """ if dim is None: if isinstance(layer, (Conv1DTranspose, Conv2DTranspose, Conv3DTranspose, Linear)): dim = 1 else: dim = 0 SpectralNorm.apply(layer, name, n_power_iterations, dim, eps) return layer
[ "def", "spectral_norm", "(", "layer", ",", "name", "=", "'weight'", ",", "n_power_iterations", "=", "1", ",", "eps", "=", "1e-12", ",", "dim", "=", "None", ")", ":", "if", "dim", "is", "None", ":", "if", "isinstance", "(", "layer", ",", "(", "Conv1DTranspose", ",", "Conv2DTranspose", ",", "Conv3DTranspose", ",", "Linear", ")", ")", ":", "dim", "=", "1", "else", ":", "dim", "=", "0", "SpectralNorm", ".", "apply", "(", "layer", ",", "name", ",", "n_power_iterations", ",", "dim", ",", "eps", ")", "return", "layer" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/utils/spectral_norm_hook.py#L131-L210
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
clang/bindings/python/clang/cindex.py
python
Type.is_function_variadic
(self)
return conf.lib.clang_isFunctionTypeVariadic(self)
Determine whether this function Type is a variadic function type.
Determine whether this function Type is a variadic function type.
[ "Determine", "whether", "this", "function", "Type", "is", "a", "variadic", "function", "type", "." ]
def is_function_variadic(self): """Determine whether this function Type is a variadic function type.""" assert self.kind == TypeKind.FUNCTIONPROTO return conf.lib.clang_isFunctionTypeVariadic(self)
[ "def", "is_function_variadic", "(", "self", ")", ":", "assert", "self", ".", "kind", "==", "TypeKind", ".", "FUNCTIONPROTO", "return", "conf", ".", "lib", ".", "clang_isFunctionTypeVariadic", "(", "self", ")" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/bindings/python/clang/cindex.py#L2321-L2325
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/lockfile/pidlockfile.py
python
PIDLockFile.acquire
(self, timeout=None)
Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired.
Acquire the lock.
[ "Acquire", "the", "lock", "." ]
def acquire(self, timeout=None): """ Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired. """ timeout = timeout is not None and timeout or self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout while True: try: write_pid_to_pidfile(self.path) except OSError as exc: if exc.errno == errno.EEXIST: # The lock creation failed. Maybe sleep a bit. if timeout is not None and time.time() > end_time: if timeout > 0: raise LockTimeout("Timeout waiting to acquire" " lock for %s" % self.path) else: raise AlreadyLocked("%s is already locked" % self.path) time.sleep(timeout is not None and timeout/10 or 0.1) else: raise LockFailed("failed to create %s" % self.path) else: return
[ "def", "acquire", "(", "self", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "is", "not", "None", "and", "timeout", "or", "self", ".", "timeout", "end_time", "=", "time", ".", "time", "(", ")", "if", "timeout", "is", "not", "None", "and", "timeout", ">", "0", ":", "end_time", "+=", "timeout", "while", "True", ":", "try", ":", "write_pid_to_pidfile", "(", "self", ".", "path", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "EEXIST", ":", "# The lock creation failed. Maybe sleep a bit.", "if", "timeout", "is", "not", "None", "and", "time", ".", "time", "(", ")", ">", "end_time", ":", "if", "timeout", ">", "0", ":", "raise", "LockTimeout", "(", "\"Timeout waiting to acquire\"", "\" lock for %s\"", "%", "self", ".", "path", ")", "else", ":", "raise", "AlreadyLocked", "(", "\"%s is already locked\"", "%", "self", ".", "path", ")", "time", ".", "sleep", "(", "timeout", "is", "not", "None", "and", "timeout", "/", "10", "or", "0.1", ")", "else", ":", "raise", "LockFailed", "(", "\"failed to create %s\"", "%", "self", ".", "path", ")", "else", ":", "return" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/lockfile/pidlockfile.py#L66-L96
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
resources/osm_importer/osm_objects.py
python
OSMCoord.center_coordinates
(minlat, minlon, maxlat, maxlon)
return xOffset, yOffset
Center the coordinate around (0,0) and returns the offsets between earth and local world coordinate.
Center the coordinate around (0,0) and returns the offsets between earth and local world coordinate.
[ "Center", "the", "coordinate", "around", "(", "0", "0", ")", "and", "returns", "the", "offsets", "between", "earth", "and", "local", "world", "coordinate", "." ]
def center_coordinates(minlat, minlon, maxlat, maxlon): """Center the coordinate around (0,0) and returns the offsets between earth and local world coordinate.""" x1, y1 = Projection.project(minlon, minlat) x2, y2 = Projection.project(maxlon, maxlat) xOffset = (x1 + x2) / 2 yOffset = (y1 + y2) / 2 for osmid in OSMCoord.coordDictionnary: # inverse X, because OSM and Webots X are inversed OSMCoord.coordDictionnary[osmid].x = OSMCoord.coordDictionnary[osmid].x - xOffset OSMCoord.coordDictionnary[osmid].y = OSMCoord.coordDictionnary[osmid].y - yOffset return xOffset, yOffset
[ "def", "center_coordinates", "(", "minlat", ",", "minlon", ",", "maxlat", ",", "maxlon", ")", ":", "x1", ",", "y1", "=", "Projection", ".", "project", "(", "minlon", ",", "minlat", ")", "x2", ",", "y2", "=", "Projection", ".", "project", "(", "maxlon", ",", "maxlat", ")", "xOffset", "=", "(", "x1", "+", "x2", ")", "/", "2", "yOffset", "=", "(", "y1", "+", "y2", ")", "/", "2", "for", "osmid", "in", "OSMCoord", ".", "coordDictionnary", ":", "# inverse X, because OSM and Webots X are inversed", "OSMCoord", ".", "coordDictionnary", "[", "osmid", "]", ".", "x", "=", "OSMCoord", ".", "coordDictionnary", "[", "osmid", "]", ".", "x", "-", "xOffset", "OSMCoord", ".", "coordDictionnary", "[", "osmid", "]", ".", "y", "=", "OSMCoord", ".", "coordDictionnary", "[", "osmid", "]", ".", "y", "-", "yOffset", "return", "xOffset", ",", "yOffset" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/osm_importer/osm_objects.py#L77-L87
enjalot/adventures_in_opencl
c222d15c076ee3f5f81b529eb47e87c8d8057096
python/part2/initialize.py
python
fountain_loopy
(num)
return pos, col, vel
This is a slower way of initializing the points (by 10x for large num) but more illustrative of whats going on
This is a slower way of initializing the points (by 10x for large num) but more illustrative of whats going on
[ "This", "is", "a", "slower", "way", "of", "initializing", "the", "points", "(", "by", "10x", "for", "large", "num", ")", "but", "more", "illustrative", "of", "whats", "going", "on" ]
def fountain_loopy(num): """This is a slower way of initializing the points (by 10x for large num) but more illustrative of whats going on""" from math import sqrt, sin, cos import numpy pos = numpy.ndarray((num, 4), dtype=numpy.float32) col = numpy.ndarray((num, 4), dtype=numpy.float32) vel = numpy.ndarray((num, 4), dtype=numpy.float32) import random random.seed() for i in xrange(0, num): rad = random.uniform(.2, .5); x = sin(2*3.14 * i/num)*rad z = 0. y = cos(2*3.14 * i/num)*rad pos[i,0] = x pos[i,1] = y pos[i,2] = z pos[i,3] = 1. col[i,0] = 0. col[i,1] = 1. col[i,2] = 0. col[i,3] = 1. life = random.random() vel[i,0] = x*2. vel[i,1] = y*2. vel[i,2] = 3. vel[i,3] = life return pos, col, vel
[ "def", "fountain_loopy", "(", "num", ")", ":", "from", "math", "import", "sqrt", ",", "sin", ",", "cos", "import", "numpy", "pos", "=", "numpy", ".", "ndarray", "(", "(", "num", ",", "4", ")", ",", "dtype", "=", "numpy", ".", "float32", ")", "col", "=", "numpy", ".", "ndarray", "(", "(", "num", ",", "4", ")", ",", "dtype", "=", "numpy", ".", "float32", ")", "vel", "=", "numpy", ".", "ndarray", "(", "(", "num", ",", "4", ")", ",", "dtype", "=", "numpy", ".", "float32", ")", "import", "random", "random", ".", "seed", "(", ")", "for", "i", "in", "xrange", "(", "0", ",", "num", ")", ":", "rad", "=", "random", ".", "uniform", "(", ".2", ",", ".5", ")", "x", "=", "sin", "(", "2", "*", "3.14", "*", "i", "/", "num", ")", "*", "rad", "z", "=", "0.", "y", "=", "cos", "(", "2", "*", "3.14", "*", "i", "/", "num", ")", "*", "rad", "pos", "[", "i", ",", "0", "]", "=", "x", "pos", "[", "i", ",", "1", "]", "=", "y", "pos", "[", "i", ",", "2", "]", "=", "z", "pos", "[", "i", ",", "3", "]", "=", "1.", "col", "[", "i", ",", "0", "]", "=", "0.", "col", "[", "i", ",", "1", "]", "=", "1.", "col", "[", "i", ",", "2", "]", "=", "0.", "col", "[", "i", ",", "3", "]", "=", "1.", "life", "=", "random", ".", "random", "(", ")", "vel", "[", "i", ",", "0", "]", "=", "x", "*", "2.", "vel", "[", "i", ",", "1", "]", "=", "y", "*", "2.", "vel", "[", "i", ",", "2", "]", "=", "3.", "vel", "[", "i", ",", "3", "]", "=", "life", "return", "pos", ",", "col", ",", "vel" ]
https://github.com/enjalot/adventures_in_opencl/blob/c222d15c076ee3f5f81b529eb47e87c8d8057096/python/part2/initialize.py#L35-L69
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/platebtn.py
python
PlateButton.GetBitmapDisabled
(self)
return self.BitmapDisabled
Get the bitmap of the disable state :return: :class:`Bitmap` or None
Get the bitmap of the disable state
[ "Get", "the", "bitmap", "of", "the", "disable", "state" ]
def GetBitmapDisabled(self): """Get the bitmap of the disable state :return: :class:`Bitmap` or None """ return self.BitmapDisabled
[ "def", "GetBitmapDisabled", "(", "self", ")", ":", "return", "self", ".", "BitmapDisabled" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/platebtn.py#L467-L473
alibaba/MNN
c4d9566171d589c3ded23aa18ffb197016995a12
pymnn/pip_package/MNN/expr/__init__.py
python
equal
(x, y)
return _F.equal(x, y)
equal(x, y) Return the ``x == y``, element-wise. Parameters ---------- x : var_like, input value. y : var_like, input value. Returns ------- z : Var. The ``x == y`` of `x` and `y`, dtype is int32. Example: ------- >>> expr.equal([-9., 0.5], [1.2, 0.5]) var([0, 1])
equal(x, y) Return the ``x == y``, element-wise.
[ "equal", "(", "x", "y", ")", "Return", "the", "x", "==", "y", "element", "-", "wise", "." ]
def equal(x, y): ''' equal(x, y) Return the ``x == y``, element-wise. Parameters ---------- x : var_like, input value. y : var_like, input value. Returns ------- z : Var. The ``x == y`` of `x` and `y`, dtype is int32. Example: ------- >>> expr.equal([-9., 0.5], [1.2, 0.5]) var([0, 1]) ''' x = _to_var(x) y = _to_var(y) x, y = _match_dtype(x, y) return _F.equal(x, y)
[ "def", "equal", "(", "x", ",", "y", ")", ":", "x", "=", "_to_var", "(", "x", ")", "y", "=", "_to_var", "(", "y", ")", "x", ",", "y", "=", "_match_dtype", "(", "x", ",", "y", ")", "return", "_F", ".", "equal", "(", "x", ",", "y", ")" ]
https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L939-L961
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
vendor/pybind11/tools/clang/cindex.py
python
Cursor.is_converting_constructor
(self)
return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)
Returns True if the cursor refers to a C++ converting constructor.
Returns True if the cursor refers to a C++ converting constructor.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "converting", "constructor", "." ]
def is_converting_constructor(self): """Returns True if the cursor refers to a C++ converting constructor. """ return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)
[ "def", "is_converting_constructor", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXConstructor_isConvertingConstructor", "(", "self", ")" ]
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L1321-L1324
dmlc/nnvm
dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38
python/nnvm/symbol.py
python
Symbol.get_children
(self)
return ret
Gets a new grouped symbol whose output contains inputs to output nodes of the original symbol.
Gets a new grouped symbol whose output contains inputs to output nodes of the original symbol.
[ "Gets", "a", "new", "grouped", "symbol", "whose", "output", "contains", "inputs", "to", "output", "nodes", "of", "the", "original", "symbol", "." ]
def get_children(self): """Gets a new grouped symbol whose output contains inputs to output nodes of the original symbol.""" handle = _base.SymbolHandle() _check_call(_LIB.NNSymbolGetChildren( self.handle, _ctypes.byref(handle))) ret = Symbol(handle=handle) if not ret.list_output_names(): return None return ret
[ "def", "get_children", "(", "self", ")", ":", "handle", "=", "_base", ".", "SymbolHandle", "(", ")", "_check_call", "(", "_LIB", ".", "NNSymbolGetChildren", "(", "self", ".", "handle", ",", "_ctypes", ".", "byref", "(", "handle", ")", ")", ")", "ret", "=", "Symbol", "(", "handle", "=", "handle", ")", "if", "not", "ret", ".", "list_output_names", "(", ")", ":", "return", "None", "return", "ret" ]
https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/symbol.py#L212-L221