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
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
cleanupOutputCallbacks
()
clears the entire output callback table. this includes the compiled-in I/O callbacks.
clears the entire output callback table. this includes the compiled-in I/O callbacks.
[ "clears", "the", "entire", "output", "callback", "table", ".", "this", "includes", "the", "compiled", "-", "in", "I", "/", "O", "callbacks", "." ]
def cleanupOutputCallbacks(): """clears the entire output callback table. this includes the compiled-in I/O callbacks. """ libxml2mod.xmlCleanupOutputCallbacks()
[ "def", "cleanupOutputCallbacks", "(", ")", ":", "libxml2mod", ".", "xmlCleanupOutputCallbacks", "(", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L1878-L1881
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/tools/android/stubify_manifest.py
python
StubifyInstantRun
(manifest_string)
return ElementTree.tostring(manifest)
Stubifies the manifest for Instant Run. Args: manifest_string: the input manifest as a string. Returns: The new manifest as a string. Raises: Exception: if somethign goes wrong
Stubifies the manifest for Instant Run.
[ "Stubifies", "the", "manifest", "for", "Instant", "Run", "." ]
def StubifyInstantRun(manifest_string): """Stubifies the manifest for Instant Run. Args: manifest_string: the input manifest as a string. Returns: The new manifest as a string. Raises: Exception: if somethign goes wrong """ manifest, application = _ParseManifest(manifest_string) old_application = application.get("{%s}name" % ANDROID) if old_application: application.set("name", old_application) application.set("{%s}name" % ANDROID, INSTANT_RUN_BOOTSTRAP_APPLICATION) return ElementTree.tostring(manifest)
[ "def", "StubifyInstantRun", "(", "manifest_string", ")", ":", "manifest", ",", "application", "=", "_ParseManifest", "(", "manifest_string", ")", "old_application", "=", "application", ".", "get", "(", "\"{%s}name\"", "%", "ANDROID", ")", "if", "old_application", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/tools/android/stubify_manifest.py#L91-L106
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/mox.py
python
MockAnything.__nonzero__
(self)
return 1
Return 1 for nonzero so the mock can be used as a conditional.
Return 1 for nonzero so the mock can be used as a conditional.
[ "Return", "1", "for", "nonzero", "so", "the", "mock", "can", "be", "used", "as", "a", "conditional", "." ]
def __nonzero__(self): """Return 1 for nonzero so the mock can be used as a conditional.""" return 1
[ "def", "__nonzero__", "(", "self", ")", ":", "return", "1" ]
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/mox.py#L309-L312
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/instrument_interval.py
python
InstrumentInterval.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(InstrumentInterval, 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", "(", ...
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument_interval.py#L99-L124
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py
python
KeysPage.var_changed_keybinding
(self, *params)
Store change to a keybinding.
Store change to a keybinding.
[ "Store", "change", "to", "a", "keybinding", "." ]
def var_changed_keybinding(self, *params): "Store change to a keybinding." value = self.keybinding.get() key_set = self.custom_name.get() event = self.bindingslist.get(ANCHOR).split()[0] if idleConf.IsCoreBinding(event): changes.add_option('keys', key_set, event, value) else: # Event is an extension binding. ext_name = idleConf.GetExtnNameForEvent(event) ext_keybind_section = ext_name + '_cfgBindings' changes.add_option('extensions', ext_keybind_section, event, value)
[ "def", "var_changed_keybinding", "(", "self", ",", "*", "params", ")", ":", "value", "=", "self", ".", "keybinding", ".", "get", "(", ")", "key_set", "=", "self", ".", "custom_name", ".", "get", "(", ")", "event", "=", "self", ".", "bindingslist", ".",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py#L1580-L1590
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
BitVecRef.__div__
(self, other)
return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
Create the Z3 expression (signed) division `self / other`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x / y x/y >>> (x / y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)'
Create the Z3 expression (signed) division `self / other`.
[ "Create", "the", "Z3", "expression", "(", "signed", ")", "division", "self", "/", "other", "." ]
def __div__(self, other): """Create the Z3 expression (signed) division `self / other`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x / y x/y >>> (x / y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
[ "def", "__div__", "(", "self", ",", "other", ")", ":", "a", ",", "b", "=", "_coerce_exprs", "(", "self", ",", "other", ")", "return", "BitVecRef", "(", "Z3_mk_bvsdiv", "(", "self", ".", "ctx_ref", "(", ")", ",", "a", ".", "as_ast", "(", ")", ",", ...
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L3646-L3663
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/compiler/symbols.py
python
SymbolVisitor.visitAssign
(self, node, scope)
Propagate assignment flag down to child nodes. The Assign node doesn't itself contains the variables being assigned to. Instead, the children in node.nodes are visited with the assign flag set to true. When the names occur in those nodes, they are marked as defs. Some names that occur in an assignment target are not bound by the assignment, e.g. a name occurring inside a slice. The visitor handles these nodes specially; they do not propagate the assign flag to their children.
Propagate assignment flag down to child nodes.
[ "Propagate", "assignment", "flag", "down", "to", "child", "nodes", "." ]
def visitAssign(self, node, scope): """Propagate assignment flag down to child nodes. The Assign node doesn't itself contains the variables being assigned to. Instead, the children in node.nodes are visited with the assign flag set to true. When the names occur in those nodes, they are marked as defs. Some names that occur in an assignment target are not bound by the assignment, e.g. a name occurring inside a slice. The visitor handles these nodes specially; they do not propagate the assign flag to their children. """ for n in node.nodes: self.visit(n, scope, 1) self.visit(node.expr, scope)
[ "def", "visitAssign", "(", "self", ",", "node", ",", "scope", ")", ":", "for", "n", "in", "node", ".", "nodes", ":", "self", ".", "visit", "(", "n", ",", "scope", ",", "1", ")", "self", ".", "visit", "(", "node", ".", "expr", ",", "scope", ")" ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/compiler/symbols.py#L347-L362
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/data_flow_ops.py
python
_as_shape_list
(shapes, dtypes, unknown_dim_allowed=False, unknown_rank_allowed=False)
return shapes
Convert shapes to a list of tuples of int (or None).
Convert shapes to a list of tuples of int (or None).
[ "Convert", "shapes", "to", "a", "list", "of", "tuples", "of", "int", "(", "or", "None", ")", "." ]
def _as_shape_list(shapes, dtypes, unknown_dim_allowed=False, unknown_rank_allowed=False): """Convert shapes to a list of tuples of int (or None).""" del dtypes if unknown_dim_allowed: if (not isinstance(shapes, collections.Sequence) or not shapes or any(shape is None or isinstance(shape, int) for shape in shapes)): raise ValueError( "When providing partial shapes, a list of shapes must be provided.") if shapes is None: return None if isinstance(shapes, tensor_shape.TensorShape): shapes = [shapes] if not isinstance(shapes, (tuple, list)): raise TypeError( "shapes must be a TensorShape or a list or tuple of TensorShapes.") if all(shape is None or isinstance(shape, int) for shape in shapes): # We have a single shape. shapes = [shapes] shapes = [tensor_shape.as_shape(shape) for shape in shapes] if not unknown_dim_allowed: if any([not shape.is_fully_defined() for shape in shapes]): raise ValueError("All shapes must be fully defined: %s" % shapes) if not unknown_rank_allowed: if any([shape.dims is None for shape in shapes]): raise ValueError("All shapes must have a defined rank: %s" % shapes) return shapes
[ "def", "_as_shape_list", "(", "shapes", ",", "dtypes", ",", "unknown_dim_allowed", "=", "False", ",", "unknown_rank_allowed", "=", "False", ")", ":", "del", "dtypes", "if", "unknown_dim_allowed", ":", "if", "(", "not", "isinstance", "(", "shapes", ",", "collec...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L55-L82
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/packaging/specifiers.py
python
BaseSpecifier.__ne__
(self, other)
Returns a boolean representing whether or not the two Specifier like objects are not equal.
Returns a boolean representing whether or not the two Specifier like objects are not equal.
[ "Returns", "a", "boolean", "representing", "whether", "or", "not", "the", "two", "Specifier", "like", "objects", "are", "not", "equal", "." ]
def __ne__(self, other): """ Returns a boolean representing whether or not the two Specifier like objects are not equal. """
[ "def", "__ne__", "(", "self", ",", "other", ")", ":" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/packaging/specifiers.py#L43-L47
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Pen.GetCap
(*args, **kwargs)
return _gdi_.Pen_GetCap(*args, **kwargs)
GetCap(self) -> int
GetCap(self) -> int
[ "GetCap", "(", "self", ")", "-", ">", "int" ]
def GetCap(*args, **kwargs): """GetCap(self) -> int""" return _gdi_.Pen_GetCap(*args, **kwargs)
[ "def", "GetCap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Pen_GetCap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L400-L402
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/monitoring.py
python
SamplerCell.value
(self)
return histogram_proto
Retrieves the current distribution of samples. Returns: A HistogramProto describing the distribution of samples.
Retrieves the current distribution of samples.
[ "Retrieves", "the", "current", "distribution", "of", "samples", "." ]
def value(self): """Retrieves the current distribution of samples. Returns: A HistogramProto describing the distribution of samples. """ with c_api_util.tf_buffer() as buffer_: pywrap_tensorflow.TFE_MonitoringSamplerCellValue(self._cell, buffer_) proto_data = pywrap_tensorflow.TF_GetBuffer(buffer_) histogram_proto = summary_pb2.HistogramProto() histogram_proto.ParseFromString(compat.as_bytes(proto_data)) return histogram_proto
[ "def", "value", "(", "self", ")", ":", "with", "c_api_util", ".", "tf_buffer", "(", ")", "as", "buffer_", ":", "pywrap_tensorflow", ".", "TFE_MonitoringSamplerCellValue", "(", "self", ".", "_cell", ",", "buffer_", ")", "proto_data", "=", "pywrap_tensorflow", "...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/monitoring.py#L356-L367
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/head.py
python
_BinaryLogisticHead.create_model_fn_ops
(self, features, mode, labels=None, train_op_fn=None, logits=None, logits_input=None, scope=None)
See `Head`.
See `Head`.
[ "See", "Head", "." ]
def create_model_fn_ops(self, features, mode, labels=None, train_op_fn=None, logits=None, logits_input=None, scope=None): """See `Head`.""" with variable_scope.variable_scope( scope, default_name=self.head_name or "binary_logistic_head", values=(tuple(six.itervalues(features)) + (labels, logits, logits_input))): labels = self._transform_labels(mode=mode, labels=labels) logits = _logits(logits_input, logits, self.logits_dimension) return _create_model_fn_ops( features=features, mode=mode, loss_fn=self._loss_fn, logits_to_predictions_fn=self._logits_to_predictions, metrics_fn=self._metrics, create_output_alternatives_fn=_classification_output_alternatives( self.head_name, self._problem_type), labels=labels, train_op_fn=train_op_fn, logits=logits, logits_dimension=self.logits_dimension, head_name=self.head_name, weight_column_name=self.weight_column_name, enable_centered_bias=self._enable_centered_bias)
[ "def", "create_model_fn_ops", "(", "self", ",", "features", ",", "mode", ",", "labels", "=", "None", ",", "train_op_fn", "=", "None", ",", "logits", "=", "None", ",", "logits_input", "=", "None", ",", "scope", "=", "None", ")", ":", "with", "variable_sco...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/head.py#L850-L880
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/training/session_manager.py
python
SessionManager.wait_for_session
(self, master, config=None, max_wait_secs=float("Inf"))
Creates a new `Session` and waits for model to be ready. Creates a new `Session` on 'master'. Waits for the model to be initialized or recovered from a checkpoint. It's expected that another thread or process will make the model ready, and that this is intended to be used by threads/processes that participate in a distributed training configuration where a different thread/process is responsible for initializing or recovering the model being trained. NB: The amount of time this method waits for the session is bounded by max_wait_secs. By default, this function will wait indefinitely. Args: master: `String` representation of the TensorFlow master to use. config: Optional ConfigProto proto used to configure the session. max_wait_secs: Maximum time to wait for the session to become available. Returns: A `Session`. May be None if the operation exceeds the timeout specified by config.operation_timeout_in_ms. Raises: tf.DeadlineExceededError: if the session is not available after max_wait_secs.
Creates a new `Session` and waits for model to be ready.
[ "Creates", "a", "new", "Session", "and", "waits", "for", "model", "to", "be", "ready", "." ]
def wait_for_session(self, master, config=None, max_wait_secs=float("Inf")): """Creates a new `Session` and waits for model to be ready. Creates a new `Session` on 'master'. Waits for the model to be initialized or recovered from a checkpoint. It's expected that another thread or process will make the model ready, and that this is intended to be used by threads/processes that participate in a distributed training configuration where a different thread/process is responsible for initializing or recovering the model being trained. NB: The amount of time this method waits for the session is bounded by max_wait_secs. By default, this function will wait indefinitely. Args: master: `String` representation of the TensorFlow master to use. config: Optional ConfigProto proto used to configure the session. max_wait_secs: Maximum time to wait for the session to become available. Returns: A `Session`. May be None if the operation exceeds the timeout specified by config.operation_timeout_in_ms. Raises: tf.DeadlineExceededError: if the session is not available after max_wait_secs. """ self._target = master if max_wait_secs is None: max_wait_secs = float("Inf") timer = _CountDownTimer(max_wait_secs) while True: sess = session.Session(self._target, graph=self._graph, config=config) if self._local_init_op: sess.run([self._local_init_op]) not_ready = self._model_not_ready(sess) if not not_ready: return sess self._safe_close(sess) # Do we have enough time left to try again? remaining_ms_after_wait = ( timer.secs_remaining() - self._recovery_wait_secs) if remaining_ms_after_wait < 0: raise errors.DeadlineExceededError( None, None, "Session was not ready after waiting %d secs." % (max_wait_secs,)) logging.info("Waiting for model to be ready: %s", not_ready) time.sleep(self._recovery_wait_secs)
[ "def", "wait_for_session", "(", "self", ",", "master", ",", "config", "=", "None", ",", "max_wait_secs", "=", "float", "(", "\"Inf\"", ")", ")", ":", "self", ".", "_target", "=", "master", "if", "max_wait_secs", "is", "None", ":", "max_wait_secs", "=", "...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/session_manager.py#L241-L292
Yaafe/Yaafe
f5ed847bdbf540b47e8fe1980dddfb5509ae7f9d
src_python/yaafelib/dataflow.py
python
DataFlow.display
(self)
Print the DataFlow to the standard output
Print the DataFlow to the standard output
[ "Print", "the", "DataFlow", "to", "the", "standard", "output" ]
def display(self): """ Print the DataFlow to the standard output """ yc.dataflow_display(self.ptr)
[ "def", "display", "(", "self", ")", ":", "yc", ".", "dataflow_display", "(", "self", ".", "ptr", ")" ]
https://github.com/Yaafe/Yaafe/blob/f5ed847bdbf540b47e8fe1980dddfb5509ae7f9d/src_python/yaafelib/dataflow.py#L160-L164
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/factory.py
python
ResourceFactory._load_attributes
(self, attrs, meta, resource_name, resource_model, service_context)
Load resource attributes based on the resource shape. The shape name is referenced in the resource JSON, but the shape itself is defined in the Botocore service JSON, hence the need for access to the ``service_model``.
Load resource attributes based on the resource shape. The shape name is referenced in the resource JSON, but the shape itself is defined in the Botocore service JSON, hence the need for access to the ``service_model``.
[ "Load", "resource", "attributes", "based", "on", "the", "resource", "shape", ".", "The", "shape", "name", "is", "referenced", "in", "the", "resource", "JSON", "but", "the", "shape", "itself", "is", "defined", "in", "the", "Botocore", "service", "JSON", "henc...
def _load_attributes(self, attrs, meta, resource_name, resource_model, service_context): """ Load resource attributes based on the resource shape. The shape name is referenced in the resource JSON, but the shape itself is defined in the Botocore service JSON, hence the need for access to the ``service_model``. """ if not resource_model.shape: return shape = service_context.service_model.shape_for( resource_model.shape) identifiers = dict( (i.member_name, i) for i in resource_model.identifiers if i.member_name) attributes = resource_model.get_attributes(shape) for name, (orig_name, member) in attributes.items(): if name in identifiers: prop = self._create_identifier_alias( resource_name=resource_name, identifier=identifiers[name], member_model=member, service_context=service_context ) else: prop = self._create_autoload_property( resource_name=resource_name, name=orig_name, snake_cased=name, member_model=member, service_context=service_context ) attrs[name] = prop
[ "def", "_load_attributes", "(", "self", ",", "attrs", ",", "meta", ",", "resource_name", ",", "resource_model", ",", "service_context", ")", ":", "if", "not", "resource_model", ".", "shape", ":", "return", "shape", "=", "service_context", ".", "service_model", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/factory.py#L170-L203
3drobotics/ardupilot-solo
05a123b002c11dccc905d4d7703a38e5f36ee723
Tools/LogAnalyzer/DataflashLog.py
python
DataflashLogHelper.getTimeAtLine
(logdata, lineNumber)
return logdata.channels["GPS"][timeLabel].max()
returns the nearest GPS timestamp in milliseconds after the given line number
returns the nearest GPS timestamp in milliseconds after the given line number
[ "returns", "the", "nearest", "GPS", "timestamp", "in", "milliseconds", "after", "the", "given", "line", "number" ]
def getTimeAtLine(logdata, lineNumber): '''returns the nearest GPS timestamp in milliseconds after the given line number''' if not "GPS" in logdata.channels: raise Exception("no GPS log data found") # older logs use 'TIme', newer logs use 'TimeMS' timeLabel = "TimeMS" if "Time" in logdata.channels["GPS"]: timeLabel = "Time" while lineNumber <= logdata.lineCount: if lineNumber in logdata.channels["GPS"][timeLabel].dictData: return logdata.channels["GPS"][timeLabel].dictData[lineNumber] lineNumber = lineNumber + 1 sys.stderr.write("didn't find GPS data for " + str(lineNumber) + " - using maxtime\n") return logdata.channels["GPS"][timeLabel].max()
[ "def", "getTimeAtLine", "(", "logdata", ",", "lineNumber", ")", ":", "if", "not", "\"GPS\"", "in", "logdata", ".", "channels", ":", "raise", "Exception", "(", "\"no GPS log data found\"", ")", "# older logs use 'TIme', newer logs use 'TimeMS'", "timeLabel", "=", "\"Ti...
https://github.com/3drobotics/ardupilot-solo/blob/05a123b002c11dccc905d4d7703a38e5f36ee723/Tools/LogAnalyzer/DataflashLog.py#L325-L339
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/tools/pssh/pssh-box.py
python
_parse_playready_data
(data)
return ret
Parses PlayReady PSSH data from the given binary string.
Parses PlayReady PSSH data from the given binary string.
[ "Parses", "PlayReady", "PSSH", "data", "from", "the", "given", "binary", "string", "." ]
def _parse_playready_data(data): """Parses PlayReady PSSH data from the given binary string.""" reader = BinaryReader(data, little_endian=True) size = reader.read_int(4) if size != len(data): raise Exception('Length incorrect') ret = [] count = reader.read_int(2) while count > 0: count -= 1 record_type = reader.read_int(2) record_len = reader.read_int(2) record_data = reader.read_bytes(record_len) ret.append('Record (size %d):' % record_len) if record_type == 1: xml = record_data.decode('utf-16 LE') ret.extend([ ' Record Type: Rights Management Header (1)', ' Record XML:', ' ' + xml ]) elif record_type == 3: ret.extend([ ' Record Type: License Store (1)', ' License Data:', ' ' + base64.b64encode(record_data) ]) else: raise Exception('Invalid record type %d' % record_type) if reader.has_data(): raise Exception('Extra data after records') return ret
[ "def", "_parse_playready_data", "(", "data", ")", ":", "reader", "=", "BinaryReader", "(", "data", ",", "little_endian", "=", "True", ")", "size", "=", "reader", ".", "read_int", "(", "4", ")", "if", "size", "!=", "len", "(", "data", ")", ":", "raise",...
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/tools/pssh/pssh-box.py#L199-L234
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/tools/scan-build-py/lib/libscanbuild/report.py
python
create_counters
()
return predicate
Create counters for bug statistics. Two entries are maintained: 'total' is an integer, represents the number of bugs. The 'categories' is a two level categorisation of bug counters. The first level is 'bug category' the second is 'bug type'. Each entry in this classification is a dictionary of 'count', 'type' and 'label'.
Create counters for bug statistics.
[ "Create", "counters", "for", "bug", "statistics", "." ]
def create_counters(): """ Create counters for bug statistics. Two entries are maintained: 'total' is an integer, represents the number of bugs. The 'categories' is a two level categorisation of bug counters. The first level is 'bug category' the second is 'bug type'. Each entry in this classification is a dictionary of 'count', 'type' and 'label'. """ def predicate(bug): bug_category = bug['bug_category'] bug_type = bug['bug_type'] current_category = predicate.categories.get(bug_category, dict()) current_type = current_category.get(bug_type, { 'bug_type': bug_type, 'bug_type_class': category_type_name(bug), 'bug_count': 0 }) current_type.update({'bug_count': current_type['bug_count'] + 1}) current_category.update({bug_type: current_type}) predicate.categories.update({bug_category: current_category}) predicate.total += 1 predicate.total = 0 predicate.categories = dict() return predicate
[ "def", "create_counters", "(", ")", ":", "def", "predicate", "(", "bug", ")", ":", "bug_category", "=", "bug", "[", "'bug_category'", "]", "bug_type", "=", "bug", "[", "'bug_type'", "]", "current_category", "=", "predicate", ".", "categories", ".", "get", ...
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/tools/scan-build-py/lib/libscanbuild/report.py#L468-L493
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py
python
Decimal.__round__
(self, n=None)
return int(self._rescale(0, ROUND_HALF_EVEN))
Round self to the nearest integer, or to a given precision. If only one argument is supplied, round a finite Decimal instance self to the nearest integer. If self is infinite or a NaN then a Python exception is raised. If self is finite and lies exactly halfway between two integers then it is rounded to the integer with even last digit. >>> round(Decimal('123.456')) 123 >>> round(Decimal('-456.789')) -457 >>> round(Decimal('-3.0')) -3 >>> round(Decimal('2.5')) 2 >>> round(Decimal('3.5')) 4 >>> round(Decimal('Inf')) Traceback (most recent call last): ... OverflowError: cannot round an infinity >>> round(Decimal('NaN')) Traceback (most recent call last): ... ValueError: cannot round a NaN If a second argument n is supplied, self is rounded to n decimal places using the rounding mode for the current context. For an integer n, round(self, -n) is exactly equivalent to self.quantize(Decimal('1En')). >>> round(Decimal('123.456'), 0) Decimal('123') >>> round(Decimal('123.456'), 2) Decimal('123.46') >>> round(Decimal('123.456'), -2) Decimal('1E+2') >>> round(Decimal('-Infinity'), 37) Decimal('NaN') >>> round(Decimal('sNaN123'), 0) Decimal('NaN123')
Round self to the nearest integer, or to a given precision.
[ "Round", "self", "to", "the", "nearest", "integer", "or", "to", "a", "given", "precision", "." ]
def __round__(self, n=None): """Round self to the nearest integer, or to a given precision. If only one argument is supplied, round a finite Decimal instance self to the nearest integer. If self is infinite or a NaN then a Python exception is raised. If self is finite and lies exactly halfway between two integers then it is rounded to the integer with even last digit. >>> round(Decimal('123.456')) 123 >>> round(Decimal('-456.789')) -457 >>> round(Decimal('-3.0')) -3 >>> round(Decimal('2.5')) 2 >>> round(Decimal('3.5')) 4 >>> round(Decimal('Inf')) Traceback (most recent call last): ... OverflowError: cannot round an infinity >>> round(Decimal('NaN')) Traceback (most recent call last): ... ValueError: cannot round a NaN If a second argument n is supplied, self is rounded to n decimal places using the rounding mode for the current context. For an integer n, round(self, -n) is exactly equivalent to self.quantize(Decimal('1En')). >>> round(Decimal('123.456'), 0) Decimal('123') >>> round(Decimal('123.456'), 2) Decimal('123.46') >>> round(Decimal('123.456'), -2) Decimal('1E+2') >>> round(Decimal('-Infinity'), 37) Decimal('NaN') >>> round(Decimal('sNaN123'), 0) Decimal('NaN123') """ if n is not None: # two-argument form: use the equivalent quantize call if not isinstance(n, int): raise TypeError('Second argument to round should be integral') exp = _dec_from_triple(0, '1', -n) return self.quantize(exp) # one-argument form if self._is_special: if self.is_nan(): raise ValueError("cannot round a NaN") else: raise OverflowError("cannot round an infinity") return int(self._rescale(0, ROUND_HALF_EVEN))
[ "def", "__round__", "(", "self", ",", "n", "=", "None", ")", ":", "if", "n", "is", "not", "None", ":", "# two-argument form: use the equivalent quantize call", "if", "not", "isinstance", "(", "n", ",", "int", ")", ":", "raise", "TypeError", "(", "'Second arg...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L1830-L1890
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ComboBox.IsTextEmpty
(*args, **kwargs)
return _controls_.ComboBox_IsTextEmpty(*args, **kwargs)
IsTextEmpty(self) -> bool
IsTextEmpty(self) -> bool
[ "IsTextEmpty", "(", "self", ")", "-", ">", "bool" ]
def IsTextEmpty(*args, **kwargs): """IsTextEmpty(self) -> bool""" return _controls_.ComboBox_IsTextEmpty(*args, **kwargs)
[ "def", "IsTextEmpty", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ComboBox_IsTextEmpty", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L636-L638
mozilla/DeepSpeech
aa1d28530d531d0d92289bf5f11a49fe516fdc86
training/deepspeech_training/util/evaluate_tools.py
python
save_samples_json
(samples, output_path)
Save decoded tuples as JSON, converting NumPy floats to Python floats. We set ensure_ascii=True to prevent json from escaping non-ASCII chars in the texts.
Save decoded tuples as JSON, converting NumPy floats to Python floats.
[ "Save", "decoded", "tuples", "as", "JSON", "converting", "NumPy", "floats", "to", "Python", "floats", "." ]
def save_samples_json(samples, output_path): ''' Save decoded tuples as JSON, converting NumPy floats to Python floats. We set ensure_ascii=True to prevent json from escaping non-ASCII chars in the texts. ''' with open_remote(output_path, 'w') as fout: json.dump(samples, fout, default=float, ensure_ascii=False, indent=2)
[ "def", "save_samples_json", "(", "samples", ",", "output_path", ")", ":", "with", "open_remote", "(", "output_path", ",", "'w'", ")", "as", "fout", ":", "json", ".", "dump", "(", "samples", ",", "fout", ",", "default", "=", "float", ",", "ensure_ascii", ...
https://github.com/mozilla/DeepSpeech/blob/aa1d28530d531d0d92289bf5f11a49fe516fdc86/training/deepspeech_training/util/evaluate_tools.py#L121-L128
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exodus3.in.py
python
exodus.put_node_set_variable_values
(self, object_id, name, step, values)
return True
store a list of node set variable values for a specified node set, node set variable name, and time step; the list has one variable value per node in the set >>> status = ... exo.put_node_set_variable_values(node_set_id, ... nsvar_name, time_step, nsvar_vals) Parameters ---------- <int> node_set_id node set *ID* (not *INDEX*) <string> nsvar_name name of node set variable <int> time_step 1-based index of time step <list<float>> nsvar_vals Returns ------- status : bool True = successful execution
store a list of node set variable values for a specified node set, node set variable name, and time step; the list has one variable value per node in the set
[ "store", "a", "list", "of", "node", "set", "variable", "values", "for", "a", "specified", "node", "set", "node", "set", "variable", "name", "and", "time", "step", ";", "the", "list", "has", "one", "variable", "value", "per", "node", "in", "the", "set" ]
def put_node_set_variable_values(self, object_id, name, step, values): """ store a list of node set variable values for a specified node set, node set variable name, and time step; the list has one variable value per node in the set >>> status = ... exo.put_node_set_variable_values(node_set_id, ... nsvar_name, time_step, nsvar_vals) Parameters ---------- <int> node_set_id node set *ID* (not *INDEX*) <string> nsvar_name name of node set variable <int> time_step 1-based index of time step <list<float>> nsvar_vals Returns ------- status : bool True = successful execution """ self.put_variable_values('EX_NODE_SET', object_id, name, step, values) return True
[ "def", "put_node_set_variable_values", "(", "self", ",", "object_id", ",", "name", ",", "step", ",", "values", ")", ":", "self", ".", "put_variable_values", "(", "'EX_NODE_SET'", ",", "object_id", ",", "name", ",", "step", ",", "values", ")", "return", "True...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L3529-L3552
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/config.py
python
ConfigMetadataHandler._parse_version
(self, value)
return version
Parses `version` option value. :param value: :rtype: str
Parses `version` option value.
[ "Parses", "version", "option", "value", "." ]
def _parse_version(self, value): """Parses `version` option value. :param value: :rtype: str """ version = self._parse_file(value) if version != value: version = version.strip() # Be strict about versions loaded from file because it's easy to # accidentally include newlines and other unintended content if isinstance(parse(version), LegacyVersion): tmpl = ( 'Version loaded from {value} does not ' 'comply with PEP 440: {version}' ) raise DistutilsOptionError(tmpl.format(**locals())) return version version = self._parse_attr(value, self.package_dir) if callable(version): version = version() if not isinstance(version, string_types): if hasattr(version, '__iter__'): version = '.'.join(map(str, version)) else: version = '%s' % version return version
[ "def", "_parse_version", "(", "self", ",", "value", ")", ":", "version", "=", "self", ".", "_parse_file", "(", "value", ")", "if", "version", "!=", "value", ":", "version", "=", "version", ".", "strip", "(", ")", "# Be strict about versions loaded from file be...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/config.py#L493-L526
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/pot/openvino/tools/pot/utils/launcher.py
python
IELauncher._load_model
(self, path)
return self._ie.read_model(model=path['model'], weights=path['weights'])
Loads IT model from disk :param path: dictionary: 'model': path to xml 'weights': path to bin :return IE model instance
Loads IT model from disk :param path: dictionary: 'model': path to xml 'weights': path to bin :return IE model instance
[ "Loads", "IT", "model", "from", "disk", ":", "param", "path", ":", "dictionary", ":", "model", ":", "path", "to", "xml", "weights", ":", "path", "to", "bin", ":", "return", "IE", "model", "instance" ]
def _load_model(self, path): """ Loads IT model from disk :param path: dictionary: 'model': path to xml 'weights': path to bin :return IE model instance """ return self._ie.read_model(model=path['model'], weights=path['weights'])
[ "def", "_load_model", "(", "self", ",", "path", ")", ":", "return", "self", ".", "_ie", ".", "read_model", "(", "model", "=", "path", "[", "'model'", "]", ",", "weights", "=", "path", "[", "'weights'", "]", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/openvino/tools/pot/utils/launcher.py#L63-L70
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_style.py
python
StyleItem.SetSize
(self, size, ex=wx.EmptyString)
Sets the Font Size Value @param size: font point size, or None to clear attribute @keyword ex: extra attribute (i.e bold, italic, underline)
Sets the Font Size Value @param size: font point size, or None to clear attribute @keyword ex: extra attribute (i.e bold, italic, underline)
[ "Sets", "the", "Font", "Size", "Value", "@param", "size", ":", "font", "point", "size", "or", "None", "to", "clear", "attribute", "@keyword", "ex", ":", "extra", "attribute", "(", "i", ".", "e", "bold", "italic", "underline", ")" ]
def SetSize(self, size, ex=wx.EmptyString): """Sets the Font Size Value @param size: font point size, or None to clear attribute @keyword ex: extra attribute (i.e bold, italic, underline) """ self.null = False if size is None: size = u'' self.size = unicode(size) if ex and ex not in self._exattr: self._exattr.append(ex)
[ "def", "SetSize", "(", "self", ",", "size", ",", "ex", "=", "wx", ".", "EmptyString", ")", ":", "self", ".", "null", "=", "False", "if", "size", "is", "None", ":", "size", "=", "u''", "self", ".", "size", "=", "unicode", "(", "size", ")", "if", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_style.py#L290-L301
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/google/protobuf/internal/cpp_message.py
python
GetFieldDescriptor
(full_field_name)
return _pool.FindFieldByName(full_field_name)
Searches for a field descriptor given a full field name.
Searches for a field descriptor given a full field name.
[ "Searches", "for", "a", "field", "descriptor", "given", "a", "full", "field", "name", "." ]
def GetFieldDescriptor(full_field_name): """Searches for a field descriptor given a full field name.""" return _pool.FindFieldByName(full_field_name)
[ "def", "GetFieldDescriptor", "(", "full_field_name", ")", ":", "return", "_pool", ".", "FindFieldByName", "(", "full_field_name", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/cpp_message.py#L58-L60
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/framework/common_shapes.py
python
bias_add_shape
(op)
return [output_shape]
Shape function for a BiasAdd op.
Shape function for a BiasAdd op.
[ "Shape", "function", "for", "a", "BiasAdd", "op", "." ]
def bias_add_shape(op): """Shape function for a BiasAdd op.""" input_shape = op.inputs[0].get_shape().with_rank_at_least(2) bias_shape = op.inputs[1].get_shape().with_rank(1) if input_shape.ndims is not None: # Output has the same shape as input, and matches the length of # bias in its bias dimension. try: data_format = op.get_attr("data_format") except ValueError: data_format = None if data_format == b"NCHW": # Merge the length of bias_shape into the third-to-last dimension. output_shape = input_shape[0:-3].concatenate(input_shape[-3].merge_with( bias_shape[0])).concatenate(input_shape[-2:]) else: output_shape = input_shape[0:-1].concatenate(input_shape[-1].merge_with( bias_shape[0])) else: output_shape = tensor_shape.unknown_shape() return [output_shape]
[ "def", "bias_add_shape", "(", "op", ")", ":", "input_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", ".", "with_rank_at_least", "(", "2", ")", "bias_shape", "=", "op", ".", "inputs", "[", "1", "]", ".", "get_shape", "(", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/common_shapes.py#L98-L118
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/graphy/graphy/bar_chart.py
python
BarChart.GetIndependentAxis
(self)
Get the main independendant axis, which depends on orientation.
Get the main independendant axis, which depends on orientation.
[ "Get", "the", "main", "independendant", "axis", "which", "depends", "on", "orientation", "." ]
def GetIndependentAxis(self): """Get the main independendant axis, which depends on orientation.""" if self.vertical: return self.bottom else: return self.left
[ "def", "GetIndependentAxis", "(", "self", ")", ":", "if", "self", ".", "vertical", ":", "return", "self", ".", "bottom", "else", ":", "return", "self", ".", "left" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/bar_chart.py#L145-L150
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/cookielib.py
python
unmatched
(match)
return match.string[:start]+match.string[end:]
Return unmatched part of re.Match object.
Return unmatched part of re.Match object.
[ "Return", "unmatched", "part", "of", "re", ".", "Match", "object", "." ]
def unmatched(match): """Return unmatched part of re.Match object.""" start, end = match.span(0) return match.string[:start]+match.string[end:]
[ "def", "unmatched", "(", "match", ")", ":", "start", ",", "end", "=", "match", ".", "span", "(", "0", ")", "return", "match", ".", "string", "[", ":", "start", "]", "+", "match", ".", "string", "[", "end", ":", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/cookielib.py#L317-L320
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/mac_tool.py
python
MacTool._DetectInputEncoding
(self, file_name)
Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.
Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.
[ "Reads", "the", "first", "few", "bytes", "from", "file_name", "and", "tries", "to", "guess", "the", "text", "encoding", ".", "Returns", "None", "as", "a", "guess", "if", "it", "can", "t", "detect", "it", "." ]
def _DetectInputEncoding(self, file_name): """Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.""" fp = open(file_name, 'rb') try: header = fp.read(3) except e: fp.close() return None fp.close() if header.startswith("\xFE\xFF"): return "UTF-16" elif header.startswith("\xFF\xFE"): return "UTF-16" elif header.startswith("\xEF\xBB\xBF"): return "UTF-8" else: return None
[ "def", "_DetectInputEncoding", "(", "self", ",", "file_name", ")", ":", "fp", "=", "open", "(", "file_name", ",", "'rb'", ")", "try", ":", "header", "=", "fp", ".", "read", "(", "3", ")", "except", "e", ":", "fp", ".", "close", "(", ")", "return", ...
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/mac_tool.py#L122-L139
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/distutils/command/config.py
python
config._check_compiler
(self)
Check that 'self.compiler' really is a CCompiler object; if not, make it one.
Check that 'self.compiler' really is a CCompiler object; if not, make it one.
[ "Check", "that", "self", ".", "compiler", "really", "is", "a", "CCompiler", "object", ";", "if", "not", "make", "it", "one", "." ]
def _check_compiler (self): """Check that 'self.compiler' really is a CCompiler object; if not, make it one. """ # We do this late, and only on-demand, because this is an expensive # import. from distutils.ccompiler import CCompiler, new_compiler if not isinstance(self.compiler, CCompiler): self.compiler = new_compiler(compiler=self.compiler, dry_run=self.dry_run, force=1) customize_compiler(self.compiler) if self.include_dirs: self.compiler.set_include_dirs(self.include_dirs) if self.libraries: self.compiler.set_libraries(self.libraries) if self.library_dirs: self.compiler.set_library_dirs(self.library_dirs)
[ "def", "_check_compiler", "(", "self", ")", ":", "# We do this late, and only on-demand, because this is an expensive", "# import.", "from", "distutils", ".", "ccompiler", "import", "CCompiler", ",", "new_compiler", "if", "not", "isinstance", "(", "self", ".", "compiler",...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/command/config.py#L98-L114
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/gluon/parameter.py
python
Parameter.reset_ctx
(self, ctx)
Re-assign Parameter to other contexts. Parameters ---------- ctx : Context or list of Context, default ``context.current_context()``. Assign Parameter to given context. If ctx is a list of Context, a copy will be made for each context.
Re-assign Parameter to other contexts.
[ "Re", "-", "assign", "Parameter", "to", "other", "contexts", "." ]
def reset_ctx(self, ctx): """Re-assign Parameter to other contexts. Parameters ---------- ctx : Context or list of Context, default ``context.current_context()``. Assign Parameter to given context. If ctx is a list of Context, a copy will be made for each context. """ if ctx is None: ctx = [context.current_context()] if isinstance(ctx, Context): ctx = [ctx] if self._data: data = self._reduce() with autograd.pause(): self._init_impl(data, ctx) elif self._deferred_init: init, _, default_init, data = self._deferred_init self._deferred_init = (init, ctx, default_init, data) else: raise ValueError("Cannot reset context for Parameter '%s' because it " "has not been initialized."%self.name)
[ "def", "reset_ctx", "(", "self", ",", "ctx", ")", ":", "if", "ctx", "is", "None", ":", "ctx", "=", "[", "context", ".", "current_context", "(", ")", "]", "if", "isinstance", "(", "ctx", ",", "Context", ")", ":", "ctx", "=", "[", "ctx", "]", "if",...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/gluon/parameter.py#L442-L464
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/descriptor.py
python
DescriptorBase._SetOptions
(self, options, options_class_name)
Sets the descriptor's options This function is used in generated proto2 files to update descriptor options. It must not be used outside proto2.
Sets the descriptor's options
[ "Sets", "the", "descriptor", "s", "options" ]
def _SetOptions(self, options, options_class_name): """Sets the descriptor's options This function is used in generated proto2 files to update descriptor options. It must not be used outside proto2. """ self._options = options self._options_class_name = options_class_name # Does this descriptor have non-default options? self.has_options = options is not None
[ "def", "_SetOptions", "(", "self", ",", "options", ",", "options_class_name", ")", ":", "self", ".", "_options", "=", "options", "self", ".", "_options_class_name", "=", "options_class_name", "# Does this descriptor have non-default options?", "self", ".", "has_options"...
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/descriptor.py#L145-L155
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py
python
NeuralNetworkBuilder.add_asin
(self, name, input_name, output_name)
return spec_layer
Add an asin layer to the model that computes element-wise arc-sine for the input tensor. Refer to the **AsinLayerParams** message in specification (NeuralNetwork.proto) for more details. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output blob name of this layer. See Also -------- add_sin, add_sinh, add_asinh
Add an asin layer to the model that computes element-wise arc-sine for the input tensor. Refer to the **AsinLayerParams** message in specification (NeuralNetwork.proto) for more details.
[ "Add", "an", "asin", "layer", "to", "the", "model", "that", "computes", "element", "-", "wise", "arc", "-", "sine", "for", "the", "input", "tensor", ".", "Refer", "to", "the", "**", "AsinLayerParams", "**", "message", "in", "specification", "(", "NeuralNet...
def add_asin(self, name, input_name, output_name): """ Add an asin layer to the model that computes element-wise arc-sine for the input tensor. Refer to the **AsinLayerParams** message in specification (NeuralNetwork.proto) for more details. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output blob name of this layer. See Also -------- add_sin, add_sinh, add_asinh """ spec_layer = self._add_generic_layer(name, [input_name], [output_name]) spec_layer.asin.MergeFromString(b"") return spec_layer
[ "def", "add_asin", "(", "self", ",", "name", ",", "input_name", ",", "output_name", ")", ":", "spec_layer", "=", "self", ".", "_add_generic_layer", "(", "name", ",", "[", "input_name", "]", ",", "[", "output_name", "]", ")", "spec_layer", ".", "asin", "....
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L4759-L4781
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/construction.py
python
array
( data: Sequence[object] | AnyArrayLike, dtype: Dtype | None = None, copy: bool = True, )
return PandasArray._from_sequence(data, dtype=dtype, copy=copy)
Create an array. Parameters ---------- data : Sequence of objects The scalars inside `data` should be instances of the scalar type for `dtype`. It's expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`. dtype : str, np.dtype, or ExtensionDtype, optional The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas using :meth:`pandas.api.extensions.register_extension_dtype`. If not specified, there are two possibilities: 1. When `data` is a :class:`Series`, :class:`Index`, or :class:`ExtensionArray`, the `dtype` will be taken from the data. 2. Otherwise, pandas will attempt to infer the `dtype` from the data. Note that when `data` is a NumPy array, ``data.dtype`` is *not* used for inferring the array type. This is because NumPy cannot represent all the types of data that can be held in extension arrays. Currently, pandas will infer an extension dtype for sequences of ============================== ======================================= Scalar Type Array Type ============================== ======================================= :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray` :class:`pandas.Period` :class:`pandas.arrays.PeriodArray` :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray` :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray` :class:`int` :class:`pandas.arrays.IntegerArray` :class:`float` :class:`pandas.arrays.FloatingArray` :class:`str` :class:`pandas.arrays.StringArray` or :class:`pandas.arrays.ArrowStringArray` :class:`bool` :class:`pandas.arrays.BooleanArray` ============================== ======================================= The ExtensionArray created when the scalar type is :class:`str` is determined by ``pd.options.mode.string_storage`` if the dtype is not explicitly given. For all other cases, NumPy's usual inference rules will be used. .. versionchanged:: 1.0.0 Pandas infers nullable-integer dtype for integer data, string dtype for string data, and nullable-boolean dtype for boolean data. .. versionchanged:: 1.2.0 Pandas now also infers nullable-floating dtype for float-like input data copy : bool, default True Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if ``copy=False``. Returns ------- ExtensionArray The newly created array. Raises ------ ValueError When `data` is not 1-dimensional. See Also -------- numpy.array : Construct a NumPy array. Series : Construct a pandas Series. Index : Construct a pandas Index. arrays.PandasArray : ExtensionArray wrapping a NumPy array. Series.array : Extract the array stored within a Series. Notes ----- Omitting the `dtype` argument means pandas will attempt to infer the best array type from the values in the data. As new array types are added by pandas and 3rd party libraries, the "best" array type may change. We recommend specifying `dtype` to ensure that 1. the correct array type for the data is returned 2. the returned array type doesn't change as new extension types are added by pandas and third-party libraries Additionally, if the underlying memory representation of the returned array matters, we recommend specifying the `dtype` as a concrete object rather than a string alias or allowing it to be inferred. For example, a future version of pandas or a 3rd-party library may include a dedicated ExtensionArray for string data. In this event, the following would no longer return a :class:`arrays.PandasArray` backed by a NumPy array. >>> pd.array(['a', 'b'], dtype=str) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 This would instead return the new ExtensionArray dedicated for string data. If you really need the new array to be backed by a NumPy array, specify that in the dtype. >>> pd.array(['a', 'b'], dtype=np.dtype("<U1")) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 Finally, Pandas has arrays that mostly overlap with NumPy * :class:`arrays.DatetimeArray` * :class:`arrays.TimedeltaArray` When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray`` rather than a ``PandasArray``. This is for symmetry with the case of timezone-aware data, which NumPy does not natively support. >>> pd.array(['2015', '2016'], dtype='datetime64[ns]') <DatetimeArray> ['2015-01-01 00:00:00', '2016-01-01 00:00:00'] Length: 2, dtype: datetime64[ns] >>> pd.array(["1H", "2H"], dtype='timedelta64[ns]') <TimedeltaArray> ['0 days 01:00:00', '0 days 02:00:00'] Length: 2, dtype: timedelta64[ns] Examples -------- If a dtype is not specified, pandas will infer the best dtype from the values. See the description of `dtype` for the types pandas infers for. >>> pd.array([1, 2]) <IntegerArray> [1, 2] Length: 2, dtype: Int64 >>> pd.array([1, 2, np.nan]) <IntegerArray> [1, 2, <NA>] Length: 3, dtype: Int64 >>> pd.array([1.1, 2.2]) <FloatingArray> [1.1, 2.2] Length: 2, dtype: Float64 >>> pd.array(["a", None, "c"]) <StringArray> ['a', <NA>, 'c'] Length: 3, dtype: string >>> with pd.option_context("string_storage", "pyarrow"): ... arr = pd.array(["a", None, "c"]) ... >>> arr <ArrowStringArray> ['a', <NA>, 'c'] Length: 3, dtype: string >>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")]) <PeriodArray> ['2000-01-01', '2000-01-01'] Length: 2, dtype: period[D] You can use the string alias for `dtype` >>> pd.array(['a', 'b', 'a'], dtype='category') ['a', 'b', 'a'] Categories (2, object): ['a', 'b'] Or specify the actual dtype >>> pd.array(['a', 'b', 'a'], ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True)) ['a', 'b', 'a'] Categories (3, object): ['a' < 'b' < 'c'] If pandas does not infer a dedicated extension type a :class:`arrays.PandasArray` is returned. >>> pd.array([1 + 1j, 3 + 2j]) <PandasArray> [(1+1j), (3+2j)] Length: 2, dtype: complex128 As mentioned in the "Notes" section, new extension types may be added in the future (by pandas or 3rd party libraries), causing the return value to no longer be a :class:`arrays.PandasArray`. Specify the `dtype` as a NumPy dtype if you need to ensure there's no future change in behavior. >>> pd.array([1, 2], dtype=np.dtype("int32")) <PandasArray> [1, 2] Length: 2, dtype: int32 `data` must be 1-dimensional. A ValueError is raised when the input has the wrong dimensionality. >>> pd.array(1) Traceback (most recent call last): ... ValueError: Cannot pass scalar '1' to 'pandas.array'.
Create an array.
[ "Create", "an", "array", "." ]
def array( data: Sequence[object] | AnyArrayLike, dtype: Dtype | None = None, copy: bool = True, ) -> ExtensionArray: """ Create an array. Parameters ---------- data : Sequence of objects The scalars inside `data` should be instances of the scalar type for `dtype`. It's expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`. dtype : str, np.dtype, or ExtensionDtype, optional The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas using :meth:`pandas.api.extensions.register_extension_dtype`. If not specified, there are two possibilities: 1. When `data` is a :class:`Series`, :class:`Index`, or :class:`ExtensionArray`, the `dtype` will be taken from the data. 2. Otherwise, pandas will attempt to infer the `dtype` from the data. Note that when `data` is a NumPy array, ``data.dtype`` is *not* used for inferring the array type. This is because NumPy cannot represent all the types of data that can be held in extension arrays. Currently, pandas will infer an extension dtype for sequences of ============================== ======================================= Scalar Type Array Type ============================== ======================================= :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray` :class:`pandas.Period` :class:`pandas.arrays.PeriodArray` :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray` :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray` :class:`int` :class:`pandas.arrays.IntegerArray` :class:`float` :class:`pandas.arrays.FloatingArray` :class:`str` :class:`pandas.arrays.StringArray` or :class:`pandas.arrays.ArrowStringArray` :class:`bool` :class:`pandas.arrays.BooleanArray` ============================== ======================================= The ExtensionArray created when the scalar type is :class:`str` is determined by ``pd.options.mode.string_storage`` if the dtype is not explicitly given. For all other cases, NumPy's usual inference rules will be used. .. versionchanged:: 1.0.0 Pandas infers nullable-integer dtype for integer data, string dtype for string data, and nullable-boolean dtype for boolean data. .. versionchanged:: 1.2.0 Pandas now also infers nullable-floating dtype for float-like input data copy : bool, default True Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if ``copy=False``. Returns ------- ExtensionArray The newly created array. Raises ------ ValueError When `data` is not 1-dimensional. See Also -------- numpy.array : Construct a NumPy array. Series : Construct a pandas Series. Index : Construct a pandas Index. arrays.PandasArray : ExtensionArray wrapping a NumPy array. Series.array : Extract the array stored within a Series. Notes ----- Omitting the `dtype` argument means pandas will attempt to infer the best array type from the values in the data. As new array types are added by pandas and 3rd party libraries, the "best" array type may change. We recommend specifying `dtype` to ensure that 1. the correct array type for the data is returned 2. the returned array type doesn't change as new extension types are added by pandas and third-party libraries Additionally, if the underlying memory representation of the returned array matters, we recommend specifying the `dtype` as a concrete object rather than a string alias or allowing it to be inferred. For example, a future version of pandas or a 3rd-party library may include a dedicated ExtensionArray for string data. In this event, the following would no longer return a :class:`arrays.PandasArray` backed by a NumPy array. >>> pd.array(['a', 'b'], dtype=str) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 This would instead return the new ExtensionArray dedicated for string data. If you really need the new array to be backed by a NumPy array, specify that in the dtype. >>> pd.array(['a', 'b'], dtype=np.dtype("<U1")) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 Finally, Pandas has arrays that mostly overlap with NumPy * :class:`arrays.DatetimeArray` * :class:`arrays.TimedeltaArray` When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray`` rather than a ``PandasArray``. This is for symmetry with the case of timezone-aware data, which NumPy does not natively support. >>> pd.array(['2015', '2016'], dtype='datetime64[ns]') <DatetimeArray> ['2015-01-01 00:00:00', '2016-01-01 00:00:00'] Length: 2, dtype: datetime64[ns] >>> pd.array(["1H", "2H"], dtype='timedelta64[ns]') <TimedeltaArray> ['0 days 01:00:00', '0 days 02:00:00'] Length: 2, dtype: timedelta64[ns] Examples -------- If a dtype is not specified, pandas will infer the best dtype from the values. See the description of `dtype` for the types pandas infers for. >>> pd.array([1, 2]) <IntegerArray> [1, 2] Length: 2, dtype: Int64 >>> pd.array([1, 2, np.nan]) <IntegerArray> [1, 2, <NA>] Length: 3, dtype: Int64 >>> pd.array([1.1, 2.2]) <FloatingArray> [1.1, 2.2] Length: 2, dtype: Float64 >>> pd.array(["a", None, "c"]) <StringArray> ['a', <NA>, 'c'] Length: 3, dtype: string >>> with pd.option_context("string_storage", "pyarrow"): ... arr = pd.array(["a", None, "c"]) ... >>> arr <ArrowStringArray> ['a', <NA>, 'c'] Length: 3, dtype: string >>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")]) <PeriodArray> ['2000-01-01', '2000-01-01'] Length: 2, dtype: period[D] You can use the string alias for `dtype` >>> pd.array(['a', 'b', 'a'], dtype='category') ['a', 'b', 'a'] Categories (2, object): ['a', 'b'] Or specify the actual dtype >>> pd.array(['a', 'b', 'a'], ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True)) ['a', 'b', 'a'] Categories (3, object): ['a' < 'b' < 'c'] If pandas does not infer a dedicated extension type a :class:`arrays.PandasArray` is returned. >>> pd.array([1 + 1j, 3 + 2j]) <PandasArray> [(1+1j), (3+2j)] Length: 2, dtype: complex128 As mentioned in the "Notes" section, new extension types may be added in the future (by pandas or 3rd party libraries), causing the return value to no longer be a :class:`arrays.PandasArray`. Specify the `dtype` as a NumPy dtype if you need to ensure there's no future change in behavior. >>> pd.array([1, 2], dtype=np.dtype("int32")) <PandasArray> [1, 2] Length: 2, dtype: int32 `data` must be 1-dimensional. A ValueError is raised when the input has the wrong dimensionality. >>> pd.array(1) Traceback (most recent call last): ... ValueError: Cannot pass scalar '1' to 'pandas.array'. """ from pandas.core.arrays import ( BooleanArray, DatetimeArray, FloatingArray, IntegerArray, IntervalArray, PandasArray, PeriodArray, TimedeltaArray, ) from pandas.core.arrays.string_ import StringDtype if lib.is_scalar(data): msg = f"Cannot pass scalar '{data}' to 'pandas.array'." raise ValueError(msg) if dtype is None and isinstance(data, (ABCSeries, ABCIndex, ABCExtensionArray)): # Note: we exclude np.ndarray here, will do type inference on it dtype = data.dtype data = extract_array(data, extract_numpy=True) # this returns None for not-found dtypes. if isinstance(dtype, str): dtype = registry.find(dtype) or dtype if is_extension_array_dtype(dtype): cls = cast(ExtensionDtype, dtype).construct_array_type() return cls._from_sequence(data, dtype=dtype, copy=copy) if dtype is None: inferred_dtype = lib.infer_dtype(data, skipna=True) if inferred_dtype == "period": return PeriodArray._from_sequence(data, copy=copy) elif inferred_dtype == "interval": return IntervalArray(data, copy=copy) elif inferred_dtype.startswith("datetime"): # datetime, datetime64 try: return DatetimeArray._from_sequence(data, copy=copy) except ValueError: # Mixture of timezones, fall back to PandasArray pass elif inferred_dtype.startswith("timedelta"): # timedelta, timedelta64 return TimedeltaArray._from_sequence(data, copy=copy) elif inferred_dtype == "string": # StringArray/ArrowStringArray depending on pd.options.mode.string_storage return StringDtype().construct_array_type()._from_sequence(data, copy=copy) elif inferred_dtype == "integer": return IntegerArray._from_sequence(data, copy=copy) elif inferred_dtype in ("floating", "mixed-integer-float"): return FloatingArray._from_sequence(data, copy=copy) elif inferred_dtype == "boolean": return BooleanArray._from_sequence(data, copy=copy) # Pandas overrides NumPy for # 1. datetime64[ns] # 2. timedelta64[ns] # so that a DatetimeArray is returned. if is_datetime64_ns_dtype(dtype): return DatetimeArray._from_sequence(data, dtype=dtype, copy=copy) elif is_timedelta64_ns_dtype(dtype): return TimedeltaArray._from_sequence(data, dtype=dtype, copy=copy) return PandasArray._from_sequence(data, dtype=dtype, copy=copy)
[ "def", "array", "(", "data", ":", "Sequence", "[", "object", "]", "|", "AnyArrayLike", ",", "dtype", ":", "Dtype", "|", "None", "=", "None", ",", "copy", ":", "bool", "=", "True", ",", ")", "->", "ExtensionArray", ":", "from", "pandas", ".", "core", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/construction.py#L72-L366
martinmoene/lest
f3e9dfe4a66c3e60dfdac7a3d3e4ddc0dcf06b26
script/create-cov-rpt.py
python
executable_name
( f )
return os.path.basename( f )
Folder where the executable is
Folder where the executable is
[ "Folder", "where", "the", "executable", "is" ]
def executable_name( f ): """Folder where the executable is""" return os.path.basename( f )
[ "def", "executable_name", "(", "f", ")", ":", "return", "os", ".", "path", ".", "basename", "(", "f", ")" ]
https://github.com/martinmoene/lest/blob/f3e9dfe4a66c3e60dfdac7a3d3e4ddc0dcf06b26/script/create-cov-rpt.py#L37-L39
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/posixpath.py
python
expandvars
(path)
return path
Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.
Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.
[ "Expand", "shell", "variables", "of", "form", "$var", "and", "$", "{", "var", "}", ".", "Unknown", "variables", "are", "left", "unchanged", "." ]
def expandvars(path): """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.""" path = os.fspath(path) global _varprog, _varprogb if isinstance(path, bytes): if b'$' not in path: return path if not _varprogb: import re _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII) search = _varprogb.search start = b'{' end = b'}' environ = getattr(os, 'environb', None) else: if '$' not in path: return path if not _varprog: import re _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII) search = _varprog.search start = '{' end = '}' environ = os.environ i = 0 while True: m = search(path, i) if not m: break i, j = m.span(0) name = m.group(1) if name.startswith(start) and name.endswith(end): name = name[1:-1] try: if environ is None: value = os.fsencode(os.environ[os.fsdecode(name)]) else: value = environ[name] except KeyError: i = j else: tail = path[j:] path = path[:i] + value i = len(path) path += tail return path
[ "def", "expandvars", "(", "path", ")", ":", "path", "=", "os", ".", "fspath", "(", "path", ")", "global", "_varprog", ",", "_varprogb", "if", "isinstance", "(", "path", ",", "bytes", ")", ":", "if", "b'$'", "not", "in", "path", ":", "return", "path",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/posixpath.py#L285-L331
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel._get_external_element_faces
(self, element_block_ids='all')
return [ value for value in list(external_faces.values()) if value is not None ]
Return a list of external element faces. External faces are element faces which are shared by no other elements. A list is returned with members of the form: * '(element_block_id, element_index, face_index)'
Return a list of external element faces.
[ "Return", "a", "list", "of", "external", "element", "faces", "." ]
def _get_external_element_faces(self, element_block_ids='all'): """ Return a list of external element faces. External faces are element faces which are shared by no other elements. A list is returned with members of the form: * '(element_block_id, element_index, face_index)' """ element_block_ids = self._format_element_block_id_list( element_block_ids) external_faces = dict() for id_ in element_block_ids: info = self._get_block_info(id_) connectivity = self.get_connectivity(id_) face_mapping = self._get_face_mapping_from_id(id_) for element_index in range(info[1]): for face_index, (_, face) in enumerate(face_mapping): sorted_nodes = tuple( sorted([ connectivity[element_index * info[2] + x] for x in face ])) if sorted_nodes in external_faces: external_faces[sorted_nodes] = None else: this_face = (id_, element_index, face_index) external_faces[sorted_nodes] = this_face return [ value for value in list(external_faces.values()) if value is not None ]
[ "def", "_get_external_element_faces", "(", "self", ",", "element_block_ids", "=", "'all'", ")", ":", "element_block_ids", "=", "self", ".", "_format_element_block_id_list", "(", "element_block_ids", ")", "external_faces", "=", "dict", "(", ")", "for", "id_", "in", ...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L1319-L1351
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
third_party/gpus/find_cuda_config.py
python
_find_header
(base_paths, header_name, required_version, get_version)
return _find_versioned_file(base_paths, _header_paths(), header_name, required_version, get_version)
Returns first valid path to a header that matches the requested version.
Returns first valid path to a header that matches the requested version.
[ "Returns", "first", "valid", "path", "to", "a", "header", "that", "matches", "the", "requested", "version", "." ]
def _find_header(base_paths, header_name, required_version, get_version): """Returns first valid path to a header that matches the requested version.""" return _find_versioned_file(base_paths, _header_paths(), header_name, required_version, get_version)
[ "def", "_find_header", "(", "base_paths", ",", "header_name", ",", "required_version", ",", "get_version", ")", ":", "return", "_find_versioned_file", "(", "base_paths", ",", "_header_paths", "(", ")", ",", "header_name", ",", "required_version", ",", "get_version",...
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/third_party/gpus/find_cuda_config.py#L224-L227
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
CustomTreeCtrl.SetBorderPen
(self, pen)
Sets the pen used to draw the selected item border. :param `pen`: an instance of :class:`Pen`. :note: The border pen is not used if the Windows Vista selection style is applied.
Sets the pen used to draw the selected item border.
[ "Sets", "the", "pen", "used", "to", "draw", "the", "selected", "item", "border", "." ]
def SetBorderPen(self, pen): """ Sets the pen used to draw the selected item border. :param `pen`: an instance of :class:`Pen`. :note: The border pen is not used if the Windows Vista selection style is applied. """ self._borderPen = pen self.RefreshSelected()
[ "def", "SetBorderPen", "(", "self", ",", "pen", ")", ":", "self", ".", "_borderPen", "=", "pen", "self", ".", "RefreshSelected", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L4148-L4158
bairdzhang/smallhardface
76fa1d87a9602d9b13d7a7fe693fc7aec91cab80
caffe/scripts/cpp_lint.py
python
ProcessLine
(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[])
Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Processes a single line in the file.
[ "Processes", "a", "single", "line", "in", "the", "file", "." ]
def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM: return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckCaffeAlternatives(filename, clean_lines, line, error) CheckCaffeDataLayerSetUp(filename, clean_lines, line, error) CheckCaffeRandom(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error)
[ "def", "ProcessLine", "(", "filename", ",", "file_extension", ",", "clean_lines", ",", "line", ",", "include_state", ",", "function_state", ",", "nesting_state", ",", "error", ",", "extra_check_functions", "=", "[", "]", ")", ":", "raw_lines", "=", "clean_lines"...
https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/scripts/cpp_lint.py#L4604-L4646
tkn-tub/ns3-gym
19bfe0a583e641142609939a090a09dfc63a095f
src/visualizer/visualizer/core.py
python
Visualizer._create_advanced_controls
(self)
return expander
! Create advanced controls. @param self: class object. @return expander
! Create advanced controls.
[ "!", "Create", "advanced", "controls", "." ]
def _create_advanced_controls(self): """! Create advanced controls. @param self: class object. @return expander """ expander = Gtk.Expander.new("Advanced") expander.show() main_vbox = GObject.new(Gtk.VBox, border_width=8, visible=True) expander.add(main_vbox) main_hbox1 = GObject.new(Gtk.HBox, border_width=8, visible=True) main_vbox.pack_start(main_hbox1, True, True, 0) show_transmissions_group = GObject.new(Gtk.HeaderBar, title="Show transmissions", visible=True) main_hbox1.pack_start(show_transmissions_group, False, False, 8) vbox = Gtk.VBox(homogeneous=True, spacing=4) vbox.show() show_transmissions_group.add(vbox) all_nodes = Gtk.RadioButton.new(None) all_nodes.set_label("All nodes") all_nodes.set_active(True) all_nodes.show() vbox.add(all_nodes) selected_node = Gtk.RadioButton.new_from_widget(all_nodes) selected_node.show() selected_node.set_label("Selected node") selected_node.set_active(False) vbox.add(selected_node) no_node = Gtk.RadioButton.new_from_widget(all_nodes) no_node.show() no_node.set_label("Disabled") no_node.set_active(False) vbox.add(no_node) def toggled(radio): if radio.get_active(): self.set_show_transmissions_mode(ShowTransmissionsMode.ALL) all_nodes.connect("toggled", toggled) def toggled(radio): if radio.get_active(): self.set_show_transmissions_mode(ShowTransmissionsMode.NONE) no_node.connect("toggled", toggled) def toggled(radio): if radio.get_active(): self.set_show_transmissions_mode(ShowTransmissionsMode.SELECTED) selected_node.connect("toggled", toggled) # -- misc settings misc_settings_group = GObject.new(Gtk.HeaderBar, title="Misc Settings", visible=True) main_hbox1.pack_start(misc_settings_group, False, False, 8) settings_hbox = GObject.new(Gtk.HBox, border_width=8, visible=True) misc_settings_group.add(settings_hbox) # --> node size vbox = GObject.new(Gtk.VBox, border_width=0, visible=True) scale = GObject.new(Gtk.HScale, visible=True, digits=2) vbox.pack_start(scale, True, True, 0) vbox.pack_start(GObject.new(Gtk.Label, label="Node Size", visible=True), True, True, 0) settings_hbox.pack_start(vbox, False, False, 6) self.node_size_adjustment = scale.get_adjustment() def node_size_changed(adj): for node in self.nodes.itervalues(): node.set_size(adj.get_value()) self.node_size_adjustment.connect("value-changed", node_size_changed) self.node_size_adjustment.set_lower(0.01) self.node_size_adjustment.set_upper(20) self.node_size_adjustment.set_step_increment(0.1) self.node_size_adjustment.set_value(DEFAULT_NODE_SIZE) # --> transmissions smooth factor vbox = GObject.new(Gtk.VBox, border_width=0, visible=True) scale = GObject.new(Gtk.HScale, visible=True, digits=1) vbox.pack_start(scale, True, True, 0) vbox.pack_start(GObject.new(Gtk.Label, label="Tx. Smooth Factor (s)", visible=True), True, True, 0) settings_hbox.pack_start(vbox, False, False, 6) self.transmissions_smoothing_adjustment = scale.get_adjustment() adj = self.transmissions_smoothing_adjustment adj.set_lower(0.1) adj.set_upper(10) adj.set_step_increment(0.1) adj.set_value(DEFAULT_TRANSMISSIONS_MEMORY*0.1) return expander
[ "def", "_create_advanced_controls", "(", "self", ")", ":", "expander", "=", "Gtk", ".", "Expander", ".", "new", "(", "\"Advanced\"", ")", "expander", ".", "show", "(", ")", "main_vbox", "=", "GObject", ".", "new", "(", "Gtk", ".", "VBox", ",", "border_wi...
https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/src/visualizer/visualizer/core.py#L785-L878
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py
python
Window._fill_bg
( self, screen: Screen, write_position: WritePosition, erase_bg: bool )
Erase/fill the background. (Useful for floats and when a `char` has been given.)
Erase/fill the background. (Useful for floats and when a `char` has been given.)
[ "Erase", "/", "fill", "the", "background", ".", "(", "Useful", "for", "floats", "and", "when", "a", "char", "has", "been", "given", ".", ")" ]
def _fill_bg( self, screen: Screen, write_position: WritePosition, erase_bg: bool ) -> None: """ Erase/fill the background. (Useful for floats and when a `char` has been given.) """ char: Optional[str] if callable(self.char): char = self.char() else: char = self.char if erase_bg or char: wp = write_position char_obj = _CHAR_CACHE[char or " ", ""] for y in range(wp.ypos, wp.ypos + wp.height): row = screen.data_buffer[y] for x in range(wp.xpos, wp.xpos + wp.width): row[x] = char_obj
[ "def", "_fill_bg", "(", "self", ",", "screen", ":", "Screen", ",", "write_position", ":", "WritePosition", ",", "erase_bg", ":", "bool", ")", "->", "None", ":", "char", ":", "Optional", "[", "str", "]", "if", "callable", "(", "self", ".", "char", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py#L2183-L2203
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Modules/Scripted/EditorLib/EditUtil.py
python
EditUtil.toggleForegroundBackground
()
Swap the foreground and background volumes for all composite nodes in the scene
Swap the foreground and background volumes for all composite nodes in the scene
[ "Swap", "the", "foreground", "and", "background", "volumes", "for", "all", "composite", "nodes", "in", "the", "scene" ]
def toggleForegroundBackground(): """Swap the foreground and background volumes for all composite nodes in the scene""" for sliceCompositeNode in slicer.util.getNodes('vtkMRMLSliceCompositeNode*').values(): oldForeground = sliceCompositeNode.GetForegroundVolumeID() sliceCompositeNode.SetForegroundVolumeID(sliceCompositeNode.GetBackgroundVolumeID()) sliceCompositeNode.SetBackgroundVolumeID(oldForeground)
[ "def", "toggleForegroundBackground", "(", ")", ":", "for", "sliceCompositeNode", "in", "slicer", ".", "util", ".", "getNodes", "(", "'vtkMRMLSliceCompositeNode*'", ")", ".", "values", "(", ")", ":", "oldForeground", "=", "sliceCompositeNode", ".", "GetForegroundVolu...
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/EditUtil.py#L280-L285
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
scripts/cpp_lint.py
python
_ClassifyInclude
(fileinfo, include, is_system)
return _OTHER_HEADER
Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER
Figures out what kind of header 'include' is.
[ "Figures", "out", "what", "kind", "of", "header", "include", "is", "." ]
def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER """ # This is a list of all standard c++ header files, except # those already checked for above. is_cpp_h = include in _CPP_HEADERS if is_system: if is_cpp_h: return _CPP_SYS_HEADER else: return _C_SYS_HEADER # If the target file and the include we're checking share a # basename when we drop common extensions, and the include # lives in . , then it's likely to be owned by the target file. target_dir, target_base = ( os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) if target_base == include_base and ( include_dir == target_dir or include_dir == os.path.normpath(target_dir + '/../public')): return _LIKELY_MY_HEADER # If the target and include share some initial basename # component, it's possible the target is implementing the # include, so it's allowed to be first, but we'll never # complain if it's not there. target_first_component = _RE_FIRST_COMPONENT.match(target_base) include_first_component = _RE_FIRST_COMPONENT.match(include_base) if (target_first_component and include_first_component and target_first_component.group(0) == include_first_component.group(0)): return _POSSIBLE_MY_HEADER return _OTHER_HEADER
[ "def", "_ClassifyInclude", "(", "fileinfo", ",", "include", ",", "is_system", ")", ":", "# This is a list of all standard c++ header files, except", "# those already checked for above.", "is_cpp_h", "=", "include", "in", "_CPP_HEADERS", "if", "is_system", ":", "if", "is_cpp...
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L3624-L3680
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/resmokelib/selector.py
python
_Selector.__init__
(self, test_file_explorer, tests_are_files=True)
Initialize the _Selector. Args: test_file_explorer: a TestFileExplorer instance.
Initialize the _Selector.
[ "Initialize", "the", "_Selector", "." ]
def __init__(self, test_file_explorer, tests_are_files=True): """Initialize the _Selector. Args: test_file_explorer: a TestFileExplorer instance. """ self._test_file_explorer = test_file_explorer self._tests_are_files = tests_are_files
[ "def", "__init__", "(", "self", ",", "test_file_explorer", ",", "tests_are_files", "=", "True", ")", ":", "self", ".", "_test_file_explorer", "=", "test_file_explorer", "self", ".", "_tests_are_files", "=", "tests_are_files" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/selector.py#L420-L427
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_2_5_2.py
python
MiroInterpreter.do_items
(self, line)
items -- Lists the items in the feed/playlist/tab selected.
items -- Lists the items in the feed/playlist/tab selected.
[ "items", "--", "Lists", "the", "items", "in", "the", "feed", "/", "playlist", "/", "tab", "selected", "." ]
def do_items(self, line): """items -- Lists the items in the feed/playlist/tab selected.""" if self.selection_type is None: print "Error: No tab/feed/playlist selected" return elif self.selection_type == 'feed': feed = self.tab view = feed.items self.printout_item_list(view) elif self.selection_type == 'playlist': playlist = self.tab.obj self.printout_item_list(playlist.getView()) elif self.selection_type == 'downloads': self.printout_item_list(item.Item.downloading_view(), item.Item.paused_view()) elif self.selection_type == 'channel-folder': folder = self.tab.obj allItems = views.items.filterWithIndex( indexes.itemsByChannelFolder, folder) allItemsSorted = allItems.sort(folder.itemSort.sort) self.printout_item_list(allItemsSorted) allItemsSorted.unlink() else: raise ValueError("Unknown tab type")
[ "def", "do_items", "(", "self", ",", "line", ")", ":", "if", "self", ".", "selection_type", "is", "None", ":", "print", "\"Error: No tab/feed/playlist selected\"", "return", "elif", "self", ".", "selection_type", "==", "'feed'", ":", "feed", "=", "self", ".", ...
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_2_5_2.py#L527-L550
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py
python
mbox.__init__
(self, path, factory=None, create=True)
Initialize an mbox mailbox.
Initialize an mbox mailbox.
[ "Initialize", "an", "mbox", "mailbox", "." ]
def __init__(self, path, factory=None, create=True): """Initialize an mbox mailbox.""" self._message_factory = mboxMessage _mboxMMDF.__init__(self, path, factory, create)
[ "def", "__init__", "(", "self", ",", "path", ",", "factory", "=", "None", ",", "create", "=", "True", ")", ":", "self", ".", "_message_factory", "=", "mboxMessage", "_mboxMMDF", ".", "__init__", "(", "self", ",", "path", ",", "factory", ",", "create", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L819-L822
verilog-to-routing/vtr-verilog-to-routing
d9719cf7374821156c3cee31d66991cb85578562
vtr_flow/scripts/python_libs/vtr/util.py
python
file_replace
(filename, search_replace_dict)
searches file for specified values and replaces them with specified values.
searches file for specified values and replaces them with specified values.
[ "searches", "file", "for", "specified", "values", "and", "replaces", "them", "with", "specified", "values", "." ]
def file_replace(filename, search_replace_dict): """ searches file for specified values and replaces them with specified values. """ lines = [] with open(filename, "r") as file: lines = file.readlines() with open(filename, "w") as file: for line in lines: for search, replace in search_replace_dict.items(): line = line.replace(search, str(replace)) print(line, file=file)
[ "def", "file_replace", "(", "filename", ",", "search_replace_dict", ")", ":", "lines", "=", "[", "]", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "file", ":", "lines", "=", "file", ".", "readlines", "(", ")", "with", "open", "(", "filenam...
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/util.py#L315-L327
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/gflags_validators.py
python
SimpleValidator.__init__
(self, flag_name, checker, message)
Constructor. Args: flag_name: string, name of the flag. checker: function to verify the validator. input - value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied
Constructor.
[ "Constructor", "." ]
def __init__(self, flag_name, checker, message): """Constructor. Args: flag_name: string, name of the flag. checker: function to verify the validator. input - value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(SimpleValidator, self).__init__(checker, message) self.flag_name = flag_name
[ "def", "__init__", "(", "self", ",", "flag_name", ",", "checker", ",", "message", ")", ":", "super", "(", "SimpleValidator", ",", "self", ")", ".", "__init__", "(", "checker", ",", "message", ")", "self", ".", "flag_name", "=", "flag_name" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/gflags_validators.py#L111-L125
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/core/arrayprint.py
python
get_printoptions
()
return d
Return the current print options. Returns ------- print_opts : dict Dictionary of current print options with keys - precision : int - threshold : int - edgeitems : int - linewidth : int - suppress : bool - nanstr : str - infstr : str For a full description of these options, see `set_printoptions`. See Also -------- set_printoptions, set_string_function
Return the current print options.
[ "Return", "the", "current", "print", "options", "." ]
def get_printoptions(): """ Return the current print options. Returns ------- print_opts : dict Dictionary of current print options with keys - precision : int - threshold : int - edgeitems : int - linewidth : int - suppress : bool - nanstr : str - infstr : str For a full description of these options, see `set_printoptions`. See Also -------- set_printoptions, set_string_function """ d = dict(precision=_float_output_precision, threshold=_summaryThreshold, edgeitems=_summaryEdgeItems, linewidth=_line_width, suppress=_float_output_suppress_small, nanstr=_nan_str, infstr=_inf_str) return d
[ "def", "get_printoptions", "(", ")", ":", "d", "=", "dict", "(", "precision", "=", "_float_output_precision", ",", "threshold", "=", "_summaryThreshold", ",", "edgeitems", "=", "_summaryEdgeItems", ",", "linewidth", "=", "_line_width", ",", "suppress", "=", "_fl...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/core/arrayprint.py#L118-L149
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/jedi/jedi/evaluate/docstrings.py
python
_search_return_in_numpydocstr
(docstr)
Search `docstr` (in numpydoc format) for type(-s) of function returns.
Search `docstr` (in numpydoc format) for type(-s) of function returns.
[ "Search", "docstr", "(", "in", "numpydoc", "format", ")", "for", "type", "(", "-", "s", ")", "of", "function", "returns", "." ]
def _search_return_in_numpydocstr(docstr): """ Search `docstr` (in numpydoc format) for type(-s) of function returns. """ try: doc = _get_numpy_doc_string_cls()(docstr) except ImportError: return try: # This is a non-public API. If it ever changes we should be # prepared and return gracefully. returns = doc._parsed_data['Returns'] returns += doc._parsed_data['Yields'] except (KeyError, AttributeError): return for r_name, r_type, r_descr in returns: # Return names are optional and if so the type is in the name if not r_type: r_type = r_name for type_ in _expand_typestr(r_type): yield type_
[ "def", "_search_return_in_numpydocstr", "(", "docstr", ")", ":", "try", ":", "doc", "=", "_get_numpy_doc_string_cls", "(", ")", "(", "docstr", ")", "except", "ImportError", ":", "return", "try", ":", "# This is a non-public API. If it ever changes we should be", "# prep...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/evaluate/docstrings.py#L78-L98
vigsterkr/libjingle
92dcbb1aac08c35d1c002c4dd7e978528b8173d2
talk/site_scons/site_tools/talk_linux.py
python
_GetPkgConfigCommand
()
return os.environ.get('PKG_CONFIG') or 'pkg-config'
Return the pkg-config command line to use. Returns: A string specifying the pkg-config command line to use.
Return the pkg-config command line to use.
[ "Return", "the", "pkg", "-", "config", "command", "line", "to", "use", "." ]
def _GetPkgConfigCommand(): """Return the pkg-config command line to use. Returns: A string specifying the pkg-config command line to use. """ return os.environ.get('PKG_CONFIG') or 'pkg-config'
[ "def", "_GetPkgConfigCommand", "(", ")", ":", "return", "os", ".", "environ", ".", "get", "(", "'PKG_CONFIG'", ")", "or", "'pkg-config'" ]
https://github.com/vigsterkr/libjingle/blob/92dcbb1aac08c35d1c002c4dd7e978528b8173d2/talk/site_scons/site_tools/talk_linux.py#L167-L173
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/pylib/forwarder.py
python
Forwarder.__init__
(self, tool)
Constructs a new instance of Forwarder. Note that Forwarder is a singleton therefore this constructor should be called only once. Args: tool: Tool class to use to get wrapper, if necessary, for executing the forwarder (see valgrind_tools.py).
Constructs a new instance of Forwarder.
[ "Constructs", "a", "new", "instance", "of", "Forwarder", "." ]
def __init__(self, tool): """Constructs a new instance of Forwarder. Note that Forwarder is a singleton therefore this constructor should be called only once. Args: tool: Tool class to use to get wrapper, if necessary, for executing the forwarder (see valgrind_tools.py). """ assert not Forwarder._instance self._tool = tool self._initialized_devices = set() self._device_to_host_port_map = dict() self._host_to_device_port_map = dict() self._host_forwarder_path = os.path.join( constants.GetOutDirectory(), 'host_forwarder') assert os.path.exists(self._host_forwarder_path), 'Please build forwarder2' self._device_forwarder_path_on_host = os.path.join( constants.GetOutDirectory(), 'forwarder_dist') self._InitHostLocked()
[ "def", "__init__", "(", "self", ",", "tool", ")", ":", "assert", "not", "Forwarder", ".", "_instance", "self", ".", "_tool", "=", "tool", "self", ".", "_initialized_devices", "=", "set", "(", ")", "self", ".", "_device_to_host_port_map", "=", "dict", "(", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/forwarder.py#L187-L207
goldeneye-source/ges-code
2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d
thirdparty/protobuf-2.3.0/python/google/protobuf/message.py
python
Message.ParseFromString
(self, serialized)
Like MergeFromString(), except we clear the object first.
Like MergeFromString(), except we clear the object first.
[ "Like", "MergeFromString", "()", "except", "we", "clear", "the", "object", "first", "." ]
def ParseFromString(self, serialized): """Like MergeFromString(), except we clear the object first.""" self.Clear() self.MergeFromString(serialized)
[ "def", "ParseFromString", "(", "self", ",", "serialized", ")", ":", "self", ".", "Clear", "(", ")", "self", ".", "MergeFromString", "(", "serialized", ")" ]
https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/google/protobuf/message.py#L165-L168
mousebird-consulting-inc/WhirlyGlobe
436478011c847c729b485009ed4db0645e304763
common/local_libs/nanopb/generator/nanopb_generator.py
python
get_nanopb_suboptions
(subdesc, options, name)
return new_options
Get copy of options, and merge information from subdesc.
Get copy of options, and merge information from subdesc.
[ "Get", "copy", "of", "options", "and", "merge", "information", "from", "subdesc", "." ]
def get_nanopb_suboptions(subdesc, options, name): '''Get copy of options, and merge information from subdesc.''' new_options = nanopb_pb2.NanoPBOptions() new_options.CopyFrom(options) if hasattr(subdesc, 'syntax') and subdesc.syntax == "proto3": new_options.proto3 = True # Handle options defined in a separate file dotname = '.'.join(name.parts) for namemask, options in Globals.separate_options: if fnmatchcase(dotname, namemask): Globals.matched_namemasks.add(namemask) new_options.MergeFrom(options) # Handle options defined in .proto if isinstance(subdesc.options, descriptor.FieldOptions): ext_type = nanopb_pb2.nanopb elif isinstance(subdesc.options, descriptor.FileOptions): ext_type = nanopb_pb2.nanopb_fileopt elif isinstance(subdesc.options, descriptor.MessageOptions): ext_type = nanopb_pb2.nanopb_msgopt elif isinstance(subdesc.options, descriptor.EnumOptions): ext_type = nanopb_pb2.nanopb_enumopt else: raise Exception("Unknown options type") if subdesc.options.HasExtension(ext_type): ext = subdesc.options.Extensions[ext_type] new_options.MergeFrom(ext) if Globals.verbose_options: sys.stderr.write("Options for " + dotname + ": ") sys.stderr.write(text_format.MessageToString(new_options) + "\n") return new_options
[ "def", "get_nanopb_suboptions", "(", "subdesc", ",", "options", ",", "name", ")", ":", "new_options", "=", "nanopb_pb2", ".", "NanoPBOptions", "(", ")", "new_options", ".", "CopyFrom", "(", "options", ")", "if", "hasattr", "(", "subdesc", ",", "'syntax'", ")...
https://github.com/mousebird-consulting-inc/WhirlyGlobe/blob/436478011c847c729b485009ed4db0645e304763/common/local_libs/nanopb/generator/nanopb_generator.py#L1809-L1844
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py
python
_normalize_host
(host, scheme)
return host
Normalize hosts for comparisons and use with sockets.
[]
def _normalize_host(host, scheme): """ Normalize hosts for comparisons and use with sockets. """ host = normalize_host(host, scheme) # httplib doesn't like it when we include brackets in IPv6 addresses # Specifically, if we include brackets but also pass the port then # httplib crazily doubles up the square brackets on the Host header. # Instead, we need to make sure we never pass ``None`` as the port. # However, for backward compatibility reasons we can't actually # *assert* that. See http://bugs.python.org/issue28539 if host.startswith("[") and host.endswith("]"): host = host[1:-1] return host
[ "def", "_normalize_host", "(", "host", ",", "scheme", ")", ":", "host", "=", "normalize_host", "(", "host", ",", "scheme", ")", "# httplib doesn't like it when we include brackets in IPv6 addresses", "# Specifically, if we include brackets but also pass the port then", "# httplib...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py#L2103-L2133
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py
python
Path.expanduser
(self)
return self
Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)
Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)
[ "Return", "a", "new", "path", "with", "expanded", "~", "and", "~user", "constructs", "(", "as", "returned", "by", "os", ".", "path", ".", "expanduser", ")" ]
def expanduser(self): """ Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser) """ if (not (self._drv or self._root) and self._parts and self._parts[0][:1] == '~'): homedir = self._flavour.gethomedir(self._parts[0][1:]) return self._from_parts([homedir] + self._parts[1:]) return self
[ "def", "expanduser", "(", "self", ")", ":", "if", "(", "not", "(", "self", ".", "_drv", "or", "self", ".", "_root", ")", "and", "self", ".", "_parts", "and", "self", ".", "_parts", "[", "0", "]", "[", ":", "1", "]", "==", "'~'", ")", ":", "ho...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py#L1480-L1489
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/keras/python/keras/backend.py
python
softplus
(x)
return nn.softplus(x)
Softplus of a tensor. Arguments: x: A tensor or variable. Returns: A tensor.
Softplus of a tensor.
[ "Softplus", "of", "a", "tensor", "." ]
def softplus(x): """Softplus of a tensor. Arguments: x: A tensor or variable. Returns: A tensor. """ return nn.softplus(x)
[ "def", "softplus", "(", "x", ")", ":", "return", "nn", ".", "softplus", "(", "x", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L2853-L2862
Lavender105/DFF
152397cec4a3dac2aa86e92a65cc27e6c8016ab9
pytorch-encoding/encoding/models/plain.py
python
get_plain
(dataset='pascal_voc', backbone='resnet50', pretrained=False, root='./pretrain_models', **kwargs)
return model
r"""PlainNet model from the paper `"Dual Attention Network for Scene Segmentation" <https://arxiv.org/abs/1809.02983.pdf>`
r"""PlainNet model from the paper `"Dual Attention Network for Scene Segmentation" <https://arxiv.org/abs/1809.02983.pdf>`
[ "r", "PlainNet", "model", "from", "the", "paper", "Dual", "Attention", "Network", "for", "Scene", "Segmentation", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1809", ".", "02983", ".", "pdf", ">" ]
def get_plain(dataset='pascal_voc', backbone='resnet50', pretrained=False, root='./pretrain_models', **kwargs): r"""PlainNet model from the paper `"Dual Attention Network for Scene Segmentation" <https://arxiv.org/abs/1809.02983.pdf>` """ acronyms = { 'pascal_voc': 'voc', 'pascal_aug': 'voc', 'pcontext': 'pcontext', 'ade20k': 'ade', 'cityscapes': 'cityscapes', } # infer number of classes from ..datasets import datasets, VOCSegmentation, VOCAugSegmentation, ADE20KSegmentation model = PlainNet(datasets[dataset.lower()].NUM_CLASS, backbone=backbone, root=root, **kwargs) if pretrained: from .model_store import get_model_file model.load_state_dict(torch.load( get_model_file('fcn_%s_%s'%(backbone, acronyms[dataset]), root=root)), strict=False) return model
[ "def", "get_plain", "(", "dataset", "=", "'pascal_voc'", ",", "backbone", "=", "'resnet50'", ",", "pretrained", "=", "False", ",", "root", "=", "'./pretrain_models'", ",", "*", "*", "kwargs", ")", ":", "acronyms", "=", "{", "'pascal_voc'", ":", "'voc'", ",...
https://github.com/Lavender105/DFF/blob/152397cec4a3dac2aa86e92a65cc27e6c8016ab9/pytorch-encoding/encoding/models/plain.py#L86-L106
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/math_grad.py
python
_RsqrtGradGrad
(op, grad)
Returns backprop gradient for f(a,b) = -0.5 * b * conj(a)^3.
Returns backprop gradient for f(a,b) = -0.5 * b * conj(a)^3.
[ "Returns", "backprop", "gradient", "for", "f", "(", "a", "b", ")", "=", "-", "0", ".", "5", "*", "b", "*", "conj", "(", "a", ")", "^3", "." ]
def _RsqrtGradGrad(op, grad): """Returns backprop gradient for f(a,b) = -0.5 * b * conj(a)^3.""" a = op.inputs[0] # a = x^{-1/2} b = op.inputs[1] # backprop gradient for a with ops.control_dependencies([grad]): ca = math_ops.conj(a) cg = math_ops.conj(grad) grad_a = -1.5 * cg * b * math_ops.square(ca) # pylint: disable=protected-access grad_b = gen_math_ops._rsqrt_grad(ca, grad) return grad_a, grad_b
[ "def", "_RsqrtGradGrad", "(", "op", ",", "grad", ")", ":", "a", "=", "op", ".", "inputs", "[", "0", "]", "# a = x^{-1/2}", "b", "=", "op", ".", "inputs", "[", "1", "]", "# backprop gradient for a", "with", "ops", ".", "control_dependencies", "(", "[", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_grad.py#L338-L348
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/traceback.py
python
print_last
(limit=None, file=None, chain=True)
This is a shorthand for 'print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)'.
This is a shorthand for 'print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)'.
[ "This", "is", "a", "shorthand", "for", "print_exception", "(", "sys", ".", "last_type", "sys", ".", "last_value", "sys", ".", "last_traceback", "limit", "file", ")", "." ]
def print_last(limit=None, file=None, chain=True): """This is a shorthand for 'print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)'.""" if not hasattr(sys, "last_type"): raise ValueError("no last exception") print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain)
[ "def", "print_last", "(", "limit", "=", "None", ",", "file", "=", "None", ",", "chain", "=", "True", ")", ":", "if", "not", "hasattr", "(", "sys", ",", "\"last_type\"", ")", ":", "raise", "ValueError", "(", "\"no last exception\"", ")", "print_exception", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/traceback.py#L169-L175
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
GraphicsRenderer.CreatePen
(*args, **kwargs)
return _gdi_.GraphicsRenderer_CreatePen(*args, **kwargs)
CreatePen(self, Pen pen) -> GraphicsPen
CreatePen(self, Pen pen) -> GraphicsPen
[ "CreatePen", "(", "self", "Pen", "pen", ")", "-", ">", "GraphicsPen" ]
def CreatePen(*args, **kwargs): """CreatePen(self, Pen pen) -> GraphicsPen""" return _gdi_.GraphicsRenderer_CreatePen(*args, **kwargs)
[ "def", "CreatePen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "GraphicsRenderer_CreatePen", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L6623-L6625
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
avl_tree/avl_tree.py
python
AVLTree.get_height
(node)
return node.height
returns height of node
returns height of node
[ "returns", "height", "of", "node" ]
def get_height(node): """ returns height of node """ if node is None: return 0 return node.height
[ "def", "get_height", "(", "node", ")", ":", "if", "node", "is", "None", ":", "return", "0", "return", "node", ".", "height" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/avl_tree/avl_tree.py#L157-L162
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/layers/merge.py
python
multiply
(inputs, **kwargs)
return Multiply(**kwargs)(inputs)
Functional interface to the `Multiply` layer. Arguments: inputs: A list of input tensors (at least 2). **kwargs: Standard layer keyword arguments. Returns: A tensor, the element-wise product of the inputs.
Functional interface to the `Multiply` layer.
[ "Functional", "interface", "to", "the", "Multiply", "layer", "." ]
def multiply(inputs, **kwargs): """Functional interface to the `Multiply` layer. Arguments: inputs: A list of input tensors (at least 2). **kwargs: Standard layer keyword arguments. Returns: A tensor, the element-wise product of the inputs. """ return Multiply(**kwargs)(inputs)
[ "def", "multiply", "(", "inputs", ",", "*", "*", "kwargs", ")", ":", "return", "Multiply", "(", "*", "*", "kwargs", ")", "(", "inputs", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/layers/merge.py#L620-L630
gv22ga/dlib-face-recognition-android
42d6305cbd85833f2b85bb79b70ab9ab004153c9
tools/lint/cpplint.py
python
_BlockInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
[ "Run", "checks", "that", "applies", "to", "text", "after", "the", "closing", "brace", ".", "This", "is", "mostly", "used", "for", "checking", "end", "of", "namespace", "comments", ".", "Args", ":", "filename", ":", "The", "name", "of", "the", "current", ...
def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "pass" ]
https://github.com/gv22ga/dlib-face-recognition-android/blob/42d6305cbd85833f2b85bb79b70ab9ab004153c9/tools/lint/cpplint.py#L2016-L2025
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/writers/AbstractWriter.py
python
AbstractWriter.DictHeaderWrite
(self, obj)
Defined to generate header for Python command class.
Defined to generate header for Python command class.
[ "Defined", "to", "generate", "header", "for", "Python", "command", "class", "." ]
def DictHeaderWrite(self, obj): """ Defined to generate header for Python command class. """ raise Exception( "# DictStartWrite.commandHeaderWrite() - Implementation Error: you must supply your own concrete implementation." )
[ "def", "DictHeaderWrite", "(", "self", ",", "obj", ")", ":", "raise", "Exception", "(", "\"# DictStartWrite.commandHeaderWrite() - Implementation Error: you must supply your own concrete implementation.\"", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/writers/AbstractWriter.py#L157-L163
zhaoweicai/hwgq
ebc706bee3e2d145de1da4be446ce8de8740738f
python/caffe/net_spec.py
python
Top.to_proto
(self)
return to_proto(self)
Generate a NetParameter that contains all layers needed to compute this top.
Generate a NetParameter that contains all layers needed to compute this top.
[ "Generate", "a", "NetParameter", "that", "contains", "all", "layers", "needed", "to", "compute", "this", "top", "." ]
def to_proto(self): """Generate a NetParameter that contains all layers needed to compute this top.""" return to_proto(self)
[ "def", "to_proto", "(", "self", ")", ":", "return", "to_proto", "(", "self", ")" ]
https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/python/caffe/net_spec.py#L90-L94
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
elle/drake/src/drake/go/__init__.py
python
Config.add_ldflags
(self, flags)
return self
Add ldflags at the end of current ldflags. :param flags: A list of flags. :type flags: list of str :return: self.
Add ldflags at the end of current ldflags.
[ "Add", "ldflags", "at", "the", "end", "of", "current", "ldflags", "." ]
def add_ldflags(self, flags): """ Add ldflags at the end of current ldflags. :param flags: A list of flags. :type flags: list of str :return: self. """ collections.deque(map(self.__ldflags.add, flags)) return self
[ "def", "add_ldflags", "(", "self", ",", "flags", ")", ":", "collections", ".", "deque", "(", "map", "(", "self", ".", "__ldflags", ".", "add", ",", "flags", ")", ")", "return", "self" ]
https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/go/__init__.py#L82-L92
martinmoene/optional-lite
a006f229a77b3b2dacf927e4029b8c1c60c86b52
script/create-vcpkg.py
python
control_path
( args )
return tpl_path_vcpkg_control.format( vcpkg=args.vcpkg_root, prj=args.project )
Create path like vcpks/ports/_project_/CONTROL
Create path like vcpks/ports/_project_/CONTROL
[ "Create", "path", "like", "vcpks", "/", "ports", "/", "_project_", "/", "CONTROL" ]
def control_path( args ): """Create path like vcpks/ports/_project_/CONTROL""" return tpl_path_vcpkg_control.format( vcpkg=args.vcpkg_root, prj=args.project )
[ "def", "control_path", "(", "args", ")", ":", "return", "tpl_path_vcpkg_control", ".", "format", "(", "vcpkg", "=", "args", ".", "vcpkg_root", ",", "prj", "=", "args", ".", "project", ")" ]
https://github.com/martinmoene/optional-lite/blob/a006f229a77b3b2dacf927e4029b8c1c60c86b52/script/create-vcpkg.py#L114-L116
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py
python
Block.internal_values
(self, dtype=None)
return self.values
return an internal format, currently just the ndarray this should be the pure internal API format
return an internal format, currently just the ndarray this should be the pure internal API format
[ "return", "an", "internal", "format", "currently", "just", "the", "ndarray", "this", "should", "be", "the", "pure", "internal", "API", "format" ]
def internal_values(self, dtype=None): """ return an internal format, currently just the ndarray this should be the pure internal API format """ return self.values
[ "def", "internal_values", "(", "self", ",", "dtype", "=", "None", ")", ":", "return", "self", ".", "values" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L213-L217
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
FileCtrlEvent.GetFilterIndex
(*args, **kwargs)
return _controls_.FileCtrlEvent_GetFilterIndex(*args, **kwargs)
GetFilterIndex(self) -> int
GetFilterIndex(self) -> int
[ "GetFilterIndex", "(", "self", ")", "-", ">", "int" ]
def GetFilterIndex(*args, **kwargs): """GetFilterIndex(self) -> int""" return _controls_.FileCtrlEvent_GetFilterIndex(*args, **kwargs)
[ "def", "GetFilterIndex", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "FileCtrlEvent_GetFilterIndex", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L7757-L7759
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/hypertreelist.py
python
TreeListMainWindow.SetMainColumn
(self, column)
Sets the :class:`HyperTreeList` main column (i.e. the position of the underlying :class:`~lib.agw.customtreectrl.CustomTreeCtrl`. :param `column`: if not ``None``, an integer specifying the column index. If it is ``None``, the main column index is used.
Sets the :class:`HyperTreeList` main column (i.e. the position of the underlying :class:`~lib.agw.customtreectrl.CustomTreeCtrl`.
[ "Sets", "the", ":", "class", ":", "HyperTreeList", "main", "column", "(", "i", ".", "e", ".", "the", "position", "of", "the", "underlying", ":", "class", ":", "~lib", ".", "agw", ".", "customtreectrl", ".", "CustomTreeCtrl", "." ]
def SetMainColumn(self, column): """ Sets the :class:`HyperTreeList` main column (i.e. the position of the underlying :class:`~lib.agw.customtreectrl.CustomTreeCtrl`. :param `column`: if not ``None``, an integer specifying the column index. If it is ``None``, the main column index is used. """ if column >= 0 and column < self.GetColumnCount(): self._main_column = column
[ "def", "SetMainColumn", "(", "self", ",", "column", ")", ":", "if", "column", ">=", "0", "and", "column", "<", "self", ".", "GetColumnCount", "(", ")", ":", "self", ".", "_main_column", "=", "column" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L2614-L2624
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/openpgp/sap/list.py
python
find_compressed_msg
(pkts)
Find a compressed OpenPGP message in a list of packets. :Parameters: - `pkts`: list of OpenPGP packet instances :Returns: - tuple (CompressedMsg_instance, leftover_pkts): - `CompressedMsg_instance`: instance of the CompressedMsg class - `leftover_pkts`: list of packets that did not contribute to the message
Find a compressed OpenPGP message in a list of packets.
[ "Find", "a", "compressed", "OpenPGP", "message", "in", "a", "list", "of", "packets", "." ]
def find_compressed_msg(pkts): """Find a compressed OpenPGP message in a list of packets. :Parameters: - `pkts`: list of OpenPGP packet instances :Returns: - tuple (CompressedMsg_instance, leftover_pkts): - `CompressedMsg_instance`: instance of the CompressedMsg class - `leftover_pkts`: list of packets that did not contribute to the message """ if PKT_COMPRESSED == pkts[0].tag.type: msg = CompressedMsg() msg._seq = [pkts[0]] msg.compressed = pkts[0] return msg, pkts[1:] else: return None, pkts
[ "def", "find_compressed_msg", "(", "pkts", ")", ":", "if", "PKT_COMPRESSED", "==", "pkts", "[", "0", "]", ".", "tag", ".", "type", ":", "msg", "=", "CompressedMsg", "(", ")", "msg", ".", "_seq", "=", "[", "pkts", "[", "0", "]", "]", "msg", ".", "...
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/list.py#L139-L158
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/psutil/psutil/_psbsd.py
python
Process.get_cpu_times
(self)
return nt_cputimes(user, system)
return a tuple containing process user/kernel time.
return a tuple containing process user/kernel time.
[ "return", "a", "tuple", "containing", "process", "user", "/", "kernel", "time", "." ]
def get_cpu_times(self): """return a tuple containing process user/kernel time.""" user, system = _psutil_bsd.get_process_cpu_times(self.pid) return nt_cputimes(user, system)
[ "def", "get_cpu_times", "(", "self", ")", ":", "user", ",", "system", "=", "_psutil_bsd", ".", "get_process_cpu_times", "(", "self", ".", "pid", ")", "return", "nt_cputimes", "(", "user", ",", "system", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/_psbsd.py#L247-L250
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TIntIntVV.GetSecHashCd
(self)
return _snap.TIntIntVV_GetSecHashCd(self)
GetSecHashCd(TIntIntVV self) -> int Parameters: self: TVec< TVec< TInt,int >,int > const *
GetSecHashCd(TIntIntVV self) -> int
[ "GetSecHashCd", "(", "TIntIntVV", "self", ")", "-", ">", "int" ]
def GetSecHashCd(self): """ GetSecHashCd(TIntIntVV self) -> int Parameters: self: TVec< TVec< TInt,int >,int > const * """ return _snap.TIntIntVV_GetSecHashCd(self)
[ "def", "GetSecHashCd", "(", "self", ")", ":", "return", "_snap", ".", "TIntIntVV_GetSecHashCd", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L16643-L16651
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py
python
_IsMessageSetExtension
(field)
return (field.is_extension and field.containing_type.has_options and field.containing_type.GetOptions().message_set_wire_format and field.type == _TYPE_MESSAGE and field.message_type == field.extension_scope and field.label == _LABEL_OPTIONAL)
Checks if a field is a message set extension.
Checks if a field is a message set extension.
[ "Checks", "if", "a", "field", "is", "a", "message", "set", "extension", "." ]
def _IsMessageSetExtension(field): """Checks if a field is a message set extension.""" return (field.is_extension and field.containing_type.has_options and field.containing_type.GetOptions().message_set_wire_format and field.type == _TYPE_MESSAGE and field.message_type == field.extension_scope and field.label == _LABEL_OPTIONAL)
[ "def", "_IsMessageSetExtension", "(", "field", ")", ":", "return", "(", "field", ".", "is_extension", "and", "field", ".", "containing_type", ".", "has_options", "and", "field", ".", "containing_type", ".", "GetOptions", "(", ")", ".", "message_set_wire_format", ...
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py#L498-L505
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py
python
Element.copy_attr_coerce
(self, attr, value, replace)
If attr is an attribute of self and either self[attr] or value is a list, convert all non-sequence values to a sequence of 1 element and then concatenate the two sequence, setting the result to self[attr]. If both self[attr] and value are non-sequences and replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing.
If attr is an attribute of self and either self[attr] or value is a list, convert all non-sequence values to a sequence of 1 element and then concatenate the two sequence, setting the result to self[attr]. If both self[attr] and value are non-sequences and replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing.
[ "If", "attr", "is", "an", "attribute", "of", "self", "and", "either", "self", "[", "attr", "]", "or", "value", "is", "a", "list", "convert", "all", "non", "-", "sequence", "values", "to", "a", "sequence", "of", "1", "element", "and", "then", "concatena...
def copy_attr_coerce(self, attr, value, replace): """ If attr is an attribute of self and either self[attr] or value is a list, convert all non-sequence values to a sequence of 1 element and then concatenate the two sequence, setting the result to self[attr]. If both self[attr] and value are non-sequences and replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing. """ if self.get(attr) is not value: if isinstance(self.get(attr), list) or \ isinstance(value, list): self.coerce_append_attr_list(attr, value) else: self.replace_attr(attr, value, replace)
[ "def", "copy_attr_coerce", "(", "self", ",", "attr", ",", "value", ",", "replace", ")", ":", "if", "self", ".", "get", "(", "attr", ")", "is", "not", "value", ":", "if", "isinstance", "(", "self", ".", "get", "(", "attr", ")", ",", "list", ")", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py#L755-L769
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/genericpath.py
python
commonprefix
(m)
return s1
Given a list of pathnames, returns the longest common leading component
Given a list of pathnames, returns the longest common leading component
[ "Given", "a", "list", "of", "pathnames", "returns", "the", "longest", "common", "leading", "component" ]
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
[ "def", "commonprefix", "(", "m", ")", ":", "if", "not", "m", ":", "return", "''", "s1", "=", "min", "(", "m", ")", "s2", "=", "max", "(", "m", ")", "for", "i", ",", "c", "in", "enumerate", "(", "s1", ")", ":", "if", "c", "!=", "s2", "[", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/genericpath.py#L76-L84
hcdth011/ROS-Hydro-SLAM
629448eecd2c9a3511158115fa53ea9e4ae41359
rpg_svo/svo_analysis/src/svo_analysis/tum_benchmark_tools/evaluate_rpe.py
python
compute_distance
(transform)
return numpy.linalg.norm(transform[0:3,3])
Compute the distance of the translational component of a 4x4 homogeneous matrix.
Compute the distance of the translational component of a 4x4 homogeneous matrix.
[ "Compute", "the", "distance", "of", "the", "translational", "component", "of", "a", "4x4", "homogeneous", "matrix", "." ]
def compute_distance(transform): """ Compute the distance of the translational component of a 4x4 homogeneous matrix. """ return numpy.linalg.norm(transform[0:3,3])
[ "def", "compute_distance", "(", "transform", ")", ":", "return", "numpy", ".", "linalg", ".", "norm", "(", "transform", "[", "0", ":", "3", ",", "3", "]", ")" ]
https://github.com/hcdth011/ROS-Hydro-SLAM/blob/629448eecd2c9a3511158115fa53ea9e4ae41359/rpg_svo/svo_analysis/src/svo_analysis/tum_benchmark_tools/evaluate_rpe.py#L162-L166
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py
python
_AddConditionalProperty
(properties, condition, name, value)
Adds a property / conditional value pair to a dictionary. Arguments: properties: The dictionary to be modified. The key is the name of the property. The value is itself a dictionary; its key is the value and the value a list of condition for which this value is true. condition: The condition under which the named property has the value. name: The name of the property. value: The value of the property.
Adds a property / conditional value pair to a dictionary.
[ "Adds", "a", "property", "/", "conditional", "value", "pair", "to", "a", "dictionary", "." ]
def _AddConditionalProperty(properties, condition, name, value): """Adds a property / conditional value pair to a dictionary. Arguments: properties: The dictionary to be modified. The key is the name of the property. The value is itself a dictionary; its key is the value and the value a list of condition for which this value is true. condition: The condition under which the named property has the value. name: The name of the property. value: The value of the property. """ if name not in properties: properties[name] = {} values = properties[name] if value not in values: values[value] = [] conditions = values[value] conditions.append(condition)
[ "def", "_AddConditionalProperty", "(", "properties", ",", "condition", ",", "name", ",", "value", ")", ":", "if", "name", "not", "in", "properties", ":", "properties", "[", "name", "]", "=", "{", "}", "values", "=", "properties", "[", "name", "]", "if", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py#L2676-L2693
anestisb/oatdump_plus
ba858c1596598f0d9ae79c14d08c708cecc50af3
tools/common/common.py
python
DeviceTestEnv.PushClasspath
(self, classpath)
return ':'.join(device_paths)
Push classpath to on-device test directory. Classpath can contain multiple colon separated file paths, each file is pushed. Returns analogous classpath with paths valid on device. Args: classpath: string, classpath in format 'a/b/c:d/e/f'. Returns: string, classpath valid on device.
Push classpath to on-device test directory.
[ "Push", "classpath", "to", "on", "-", "device", "test", "directory", "." ]
def PushClasspath(self, classpath): """Push classpath to on-device test directory. Classpath can contain multiple colon separated file paths, each file is pushed. Returns analogous classpath with paths valid on device. Args: classpath: string, classpath in format 'a/b/c:d/e/f'. Returns: string, classpath valid on device. """ paths = classpath.split(':') device_paths = [] for path in paths: device_paths.append('{0}/{1}'.format( self._device_env_path, os.path.basename(path))) self._AdbPush(path, self._device_env_path) return ':'.join(device_paths)
[ "def", "PushClasspath", "(", "self", ",", "classpath", ")", ":", "paths", "=", "classpath", ".", "split", "(", "':'", ")", "device_paths", "=", "[", "]", "for", "path", "in", "paths", ":", "device_paths", ".", "append", "(", "'{0}/{1}'", ".", "format", ...
https://github.com/anestisb/oatdump_plus/blob/ba858c1596598f0d9ae79c14d08c708cecc50af3/tools/common/common.py#L482-L499
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/randomimpl.py
python
get_np_state_ptr
(context, builder)
return get_state_ptr(context, builder, 'np')
Get a pointer to the thread-local Numpy random state.
Get a pointer to the thread-local Numpy random state.
[ "Get", "a", "pointer", "to", "the", "thread", "-", "local", "Numpy", "random", "state", "." ]
def get_np_state_ptr(context, builder): """ Get a pointer to the thread-local Numpy random state. """ return get_state_ptr(context, builder, 'np')
[ "def", "get_np_state_ptr", "(", "context", ",", "builder", ")", ":", "return", "get_state_ptr", "(", "context", ",", "builder", ",", "'np'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/randomimpl.py#L76-L80
15172658790/Blog
46e5036f5fbcad535af2255dc0e095cebcd8d710
计算机与信息类/算法基础/lab-徐云/2018/lab3/lcs.py
python
lcs2
(a,b)
return board[n]
time: O(mn); space: O(min(m,n))
time: O(mn); space: O(min(m,n))
[ "time", ":", "O", "(", "mn", ")", ";", "space", ":", "O", "(", "min", "(", "m", "n", "))" ]
def lcs2(a,b): '''time: O(mn); space: O(min(m,n))''' if len(b)>len(a): a,b= b,a m,n = len(a),len(b) board = [[] for i in range(n+1)] for i in range(m): upperLevel = board[0].copy() for j in range(n): tmp = board[j+1].copy() if a[i]==b[j]: board[j+1] = upperLevel+[a[i]] elif len(board[j+1]) < len(board[j]): board[j+1] = board[j].copy() # copy is needed upperLevel = tmp return board[n]
[ "def", "lcs2", "(", "a", ",", "b", ")", ":", "if", "len", "(", "b", ")", ">", "len", "(", "a", ")", ":", "a", ",", "b", "=", "b", ",", "a", "m", ",", "n", "=", "len", "(", "a", ")", ",", "len", "(", "b", ")", "board", "=", "[", "[",...
https://github.com/15172658790/Blog/blob/46e5036f5fbcad535af2255dc0e095cebcd8d710/计算机与信息类/算法基础/lab-徐云/2018/lab3/lcs.py#L27-L42
apache/incubator-weex
5c25f0b59f7ac90703c363e7261f60bd06356dbe
weex_core/Source/base/android/jniprebuild/jni_generator.py
python
GetEnvCall
(is_constructor, is_static, return_type)
return 'Call' + call + 'Method'
Maps the types availabe via env->Call__Method.
Maps the types availabe via env->Call__Method.
[ "Maps", "the", "types", "availabe", "via", "env", "-", ">", "Call__Method", "." ]
def GetEnvCall(is_constructor, is_static, return_type): """Maps the types availabe via env->Call__Method.""" if is_constructor: return 'NewObject' env_call_map = {'boolean': 'Boolean', 'byte': 'Byte', 'char': 'Char', 'short': 'Short', 'int': 'Int', 'long': 'Long', 'float': 'Float', 'void': 'Void', 'double': 'Double', 'Object': 'Object', } call = env_call_map.get(return_type, 'Object') if is_static: call = 'Static' + call return 'Call' + call + 'Method'
[ "def", "GetEnvCall", "(", "is_constructor", ",", "is_static", ",", "return_type", ")", ":", "if", "is_constructor", ":", "return", "'NewObject'", "env_call_map", "=", "{", "'boolean'", ":", "'Boolean'", ",", "'byte'", ":", "'Byte'", ",", "'char'", ":", "'Char'...
https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/Source/base/android/jniprebuild/jni_generator.py#L456-L474
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/optimize/linesearch.py
python
_zoom
(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2, extra_condition)
return a_star, val_star, valprime_star
Part of the optimization algorithm in `scalar_search_wolfe2`.
Part of the optimization algorithm in `scalar_search_wolfe2`.
[ "Part", "of", "the", "optimization", "algorithm", "in", "scalar_search_wolfe2", "." ]
def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2, extra_condition): """ Part of the optimization algorithm in `scalar_search_wolfe2`. """ maxiter = 10 i = 0 delta1 = 0.2 # cubic interpolant check delta2 = 0.1 # quadratic interpolant check phi_rec = phi0 a_rec = 0 while True: # interpolate to find a trial step length between a_lo and # a_hi Need to choose interpolation here. Use cubic # interpolation and then if the result is within delta * # dalpha or outside of the interval bounded by a_lo or a_hi # then use quadratic interpolation, if the result is still too # close, then use bisection dalpha = a_hi - a_lo if dalpha < 0: a, b = a_hi, a_lo else: a, b = a_lo, a_hi # minimizer of cubic interpolant # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi) # # if the result is too close to the end points (or out of the # interval) then use quadratic interpolation with phi_lo, # derphi_lo and phi_hi if the result is still too close to the # end points (or out of the interval) then use bisection if (i > 0): cchk = delta1 * dalpha a_j = _cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, a_rec, phi_rec) if (i == 0) or (a_j is None) or (a_j > b - cchk) or (a_j < a + cchk): qchk = delta2 * dalpha a_j = _quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi) if (a_j is None) or (a_j > b-qchk) or (a_j < a+qchk): a_j = a_lo + 0.5*dalpha # Check new value of a_j phi_aj = phi(a_j) if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): phi_rec = phi_hi a_rec = a_hi a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) if abs(derphi_aj) <= -c2*derphi0 and extra_condition(a_j, phi_aj): a_star = a_j val_star = phi_aj valprime_star = derphi_aj break if derphi_aj*(a_hi - a_lo) >= 0: phi_rec = phi_hi a_rec = a_hi a_hi = a_lo phi_hi = phi_lo else: phi_rec = phi_lo a_rec = a_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): # Failed to find a conforming step size a_star = None val_star = None valprime_star = None break return a_star, val_star, valprime_star
[ "def", "_zoom", "(", "a_lo", ",", "a_hi", ",", "phi_lo", ",", "phi_hi", ",", "derphi_lo", ",", "phi", ",", "derphi", ",", "phi0", ",", "derphi0", ",", "c1", ",", "c2", ",", "extra_condition", ")", ":", "maxiter", "=", "10", "i", "=", "0", "delta1",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/linesearch.py#L522-L599
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/distributions/transformed_distribution.py
python
TransformedDistribution._finish_log_prob_for_one_fiber
(self, y, x, ildj)
return log_prob
Finish computation of log_prob on one element of the inverse image.
Finish computation of log_prob on one element of the inverse image.
[ "Finish", "computation", "of", "log_prob", "on", "one", "element", "of", "the", "inverse", "image", "." ]
def _finish_log_prob_for_one_fiber(self, y, x, ildj): """Finish computation of log_prob on one element of the inverse image.""" x = self._maybe_rotate_dims(x, rotate_right=True) log_prob = self.distribution.log_prob(x) if self._is_maybe_event_override: log_prob = math_ops.reduce_sum(log_prob, self._reduce_event_indices) log_prob = ildj + log_prob if self._is_maybe_event_override: log_prob.set_shape(array_ops.broadcast_static_shape( y.get_shape().with_rank_at_least(1)[:-1], self.batch_shape)) return log_prob
[ "def", "_finish_log_prob_for_one_fiber", "(", "self", ",", "y", ",", "x", ",", "ildj", ")", ":", "x", "=", "self", ".", "_maybe_rotate_dims", "(", "x", ",", "rotate_right", "=", "True", ")", "log_prob", "=", "self", ".", "distribution", ".", "log_prob", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/distributions/transformed_distribution.py#L431-L441
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/categorical.py
python
Categorical.__getitem__
(self, key)
return result
Return an item.
Return an item.
[ "Return", "an", "item", "." ]
def __getitem__(self, key): """ Return an item. """ result = super().__getitem__(key) if getattr(result, "ndim", 0) > 1: result = result._ndarray deprecate_ndim_indexing(result) return result
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "result", "=", "super", "(", ")", ".", "__getitem__", "(", "key", ")", "if", "getattr", "(", "result", ",", "\"ndim\"", ",", "0", ")", ">", "1", ":", "result", "=", "result", ".", "_ndarray",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/categorical.py#L2009-L2017
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/findertools.py
python
openwindow
(object)
Open a Finder window for object, Specify object by name or fsspec.
Open a Finder window for object, Specify object by name or fsspec.
[ "Open", "a", "Finder", "window", "for", "object", "Specify", "object", "by", "name", "or", "fsspec", "." ]
def openwindow(object): """Open a Finder window for object, Specify object by name or fsspec.""" finder = _getfinder() object = Carbon.File.FSRef(object) object_alias = object.FSNewAliasMinimal() args = {} attrs = {} _code = 'aevt' _subcode = 'odoc' aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) args['----'] = aeobj_0 _reply, args, attrs = finder.send(_code, _subcode, args, attrs) if 'errn' in args: raise Error, aetools.decodeerror(args)
[ "def", "openwindow", "(", "object", ")", ":", "finder", "=", "_getfinder", "(", ")", "object", "=", "Carbon", ".", "File", ".", "FSRef", "(", "object", ")", "object_alias", "=", "object", ".", "FSNewAliasMinimal", "(", ")", "args", "=", "{", "}", "attr...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/findertools.py#L264-L277
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/stp/rc.py
python
Field.floor_width_m
(self)
return self.__floor_width_m
:return: check on this one
:return: check on this one
[ ":", "return", ":", "check", "on", "this", "one" ]
def floor_width_m(self) -> float: """ :return: check on this one """ return self.__floor_width_m
[ "def", "floor_width_m", "(", "self", ")", "->", "float", ":", "return", "self", ".", "__floor_width_m" ]
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/rc.py#L378-L382
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleControl.py
python
CWSCDReductionControl.set_detector_center
(self, exp_number, center_row, center_col, default=False)
return
Set detector center :param exp_number: :param center_row: :param center_col: :param default: :return:
Set detector center :param exp_number: :param center_row: :param center_col: :param default: :return:
[ "Set", "detector", "center", ":", "param", "exp_number", ":", ":", "param", "center_row", ":", ":", "param", "center_col", ":", ":", "param", "default", ":", ":", "return", ":" ]
def set_detector_center(self, exp_number, center_row, center_col, default=False): """ Set detector center :param exp_number: :param center_row: :param center_col: :param default: :return: """ # check assert isinstance(exp_number, int) and exp_number > 0, 'Experiment number must be integer' assert center_row is None or (isinstance(center_row, int) and center_row >= 0), \ 'Center row number {0} of type {1} must either None or non-negative integer.' \ ''.format(center_row, type(center_row)) assert center_col is None or (isinstance(center_col, int) and center_col >= 0), \ 'Center column number {0} of type {1} must be either None or non-negative integer.' \ ''.format(center_col, type(center_col)) if default: self._defaultDetectorCenter = center_row, center_col else: self._detCenterDict[exp_number] = center_row, center_col return
[ "def", "set_detector_center", "(", "self", ",", "exp_number", ",", "center_row", ",", "center_col", ",", "default", "=", "False", ")", ":", "# check", "assert", "isinstance", "(", "exp_number", ",", "int", ")", "and", "exp_number", ">", "0", ",", "'Experimen...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleControl.py#L2854-L2877
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
FormulaConstant.__unicode__
(self)
return 'Formula constant: ' + self.string
Return a printable representation.
Return a printable representation.
[ "Return", "a", "printable", "representation", "." ]
def __unicode__(self): "Return a printable representation." return 'Formula constant: ' + self.string
[ "def", "__unicode__", "(", "self", ")", ":", "return", "'Formula constant: '", "+", "self", ".", "string" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L2667-L2669
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/categorical.py
python
Categorical.to_dense
(self)
return np.asarray(self)
Return my 'dense' representation For internal compatibility with numpy arrays. Returns ------- dense : array
Return my 'dense' representation
[ "Return", "my", "dense", "representation" ]
def to_dense(self): """ Return my 'dense' representation For internal compatibility with numpy arrays. Returns ------- dense : array """ return np.asarray(self)
[ "def", "to_dense", "(", "self", ")", ":", "return", "np", ".", "asarray", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/categorical.py#L1707-L1717
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/ext.py
python
InternationalizationExtension._make_node
(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num)
return nodes.Output([node])
Generates a useful node from the data provided.
Generates a useful node from the data provided.
[ "Generates", "a", "useful", "node", "from", "the", "data", "provided", "." ]
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_referenced and not self.environment.newstyle_gettext: singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None) # singular and plural else: ngettext = nodes.Name('ngettext', 'load') node = nodes.Call(ngettext, [ nodes.Const(singular), nodes.Const(plural), plural_expr ], [], None, None) # in case newstyle gettext is used, the method is powerful # enough to handle the variable expansion and autoescape # handling itself if self.environment.newstyle_gettext: for key, value in iteritems(variables): # the function adds that later anyways in case num was # called num, so just skip it. if num_called_num and key == 'num': continue node.kwargs.append(nodes.Keyword(key, value)) # otherwise do that here else: # mark the return value as safe if we are in an # environment with autoescaping turned on node = nodes.MarkSafeIfAutoescape(node) if variables: node = nodes.Mod(node, nodes.Dict([ nodes.Pair(nodes.Const(key), value) for key, value in variables.items() ])) return nodes.Output([node])
[ "def", "_make_node", "(", "self", ",", "singular", ",", "plural", ",", "variables", ",", "plural_expr", ",", "vars_referenced", ",", "num_called_num", ")", ":", "# no variables referenced? no need to escape for old style", "# gettext invocations only if there are vars.", "if...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/ext.py#L341-L387
Pay20Y/FOTS_TF
c42ea59a20c28d506fee35cfb4c553b0cb20eee8
nets/resnet_v1.py
python
bottleneck
(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None)
Bottleneck residual unit variant with BN after convolutions. This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] for its definition. Note that we use here the bottleneck variant which has an extra bottleneck layer. When putting together two consecutive ResNet blocks that use this unit, one should use stride = 2 in the last unit of the first block. Args: inputs: A tensor of size [batch, height, width, channels]. depth: The depth of the ResNet unit output. depth_bottleneck: The depth of the bottleneck layers. stride: The ResNet unit's stride. Determines the amount of downsampling of the units output compared to its input. rate: An integer, rate for atrous convolution. outputs_collections: Collection to add the ResNet unit output. scope: Optional variable_scope. Returns: The ResNet unit's output.
Bottleneck residual unit variant with BN after convolutions.
[ "Bottleneck", "residual", "unit", "variant", "with", "BN", "after", "convolutions", "." ]
def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None): """Bottleneck residual unit variant with BN after convolutions. This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] for its definition. Note that we use here the bottleneck variant which has an extra bottleneck layer. When putting together two consecutive ResNet blocks that use this unit, one should use stride = 2 in the last unit of the first block. Args: inputs: A tensor of size [batch, height, width, channels]. depth: The depth of the ResNet unit output. depth_bottleneck: The depth of the bottleneck layers. stride: The ResNet unit's stride. Determines the amount of downsampling of the units output compared to its input. rate: An integer, rate for atrous convolution. outputs_collections: Collection to add the ResNet unit output. scope: Optional variable_scope. Returns: The ResNet unit's output. """ with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc: depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4) if depth == depth_in: shortcut = resnet_utils.subsample(inputs, stride, 'shortcut') else: shortcut = slim.conv2d(inputs, depth, [1, 1], stride=stride, activation_fn=None, scope='shortcut') residual = slim.conv2d(inputs, depth_bottleneck, [1, 1], stride=1, scope='conv1') residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2') residual = slim.conv2d(residual, depth, [1, 1], stride=1, activation_fn=None, scope='conv3') output = tf.nn.relu(shortcut + residual) return slim.utils.collect_named_outputs(outputs_collections, sc.original_name_scope, output)
[ "def", "bottleneck", "(", "inputs", ",", "depth", ",", "depth_bottleneck", ",", "stride", ",", "rate", "=", "1", ",", "outputs_collections", "=", "None", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'bottl...
https://github.com/Pay20Y/FOTS_TF/blob/c42ea59a20c28d506fee35cfb4c553b0cb20eee8/nets/resnet_v1.py#L68-L111
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/ccompiler.py
python
get_default_compiler
(osname=None, platform=None)
return 'unix'
Determine the default compiler to use for the given platform. osname should be one of the standard Python OS names (i.e. the ones returned by os.name) and platform the common value returned by sys.platform for the platform in question. The default values are os.name and sys.platform in case the parameters are not given.
Determine the default compiler to use for the given platform.
[ "Determine", "the", "default", "compiler", "to", "use", "for", "the", "given", "platform", "." ]
def get_default_compiler(osname=None, platform=None): """Determine the default compiler to use for the given platform. osname should be one of the standard Python OS names (i.e. the ones returned by os.name) and platform the common value returned by sys.platform for the platform in question. The default values are os.name and sys.platform in case the parameters are not given. """ if osname is None: osname = os.name if platform is None: platform = sys.platform for pattern, compiler in _default_compilers: if re.match(pattern, platform) is not None or \ re.match(pattern, osname) is not None: return compiler # Default to Unix compiler return 'unix'
[ "def", "get_default_compiler", "(", "osname", "=", "None", ",", "platform", "=", "None", ")", ":", "if", "osname", "is", "None", ":", "osname", "=", "os", ".", "name", "if", "platform", "is", "None", ":", "platform", "=", "sys", ".", "platform", "for",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/ccompiler.py#L937-L956
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/MSCommon/sdk.py
python
get_default_sdk
()
return InstalledSDKList[0]
Set up the default Platform/Windows SDK.
Set up the default Platform/Windows SDK.
[ "Set", "up", "the", "default", "Platform", "/", "Windows", "SDK", "." ]
def get_default_sdk(): """Set up the default Platform/Windows SDK.""" get_installed_sdks() if not InstalledSDKList: return None return InstalledSDKList[0]
[ "def", "get_default_sdk", "(", ")", ":", "get_installed_sdks", "(", ")", "if", "not", "InstalledSDKList", ":", "return", "None", "return", "InstalledSDKList", "[", "0", "]" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/MSCommon/sdk.py#L341-L346
google/sling
f408a148a06bc2d62e853a292a8ba7266c642839
python/task/workflow.py
python
length_of
(l)
return len(l) if isinstance(l, list) else None
Get number of elements in list or None for singletons.
Get number of elements in list or None for singletons.
[ "Get", "number", "of", "elements", "in", "list", "or", "None", "for", "singletons", "." ]
def length_of(l): """Get number of elements in list or None for singletons.""" return len(l) if isinstance(l, list) else None
[ "def", "length_of", "(", "l", ")", ":", "return", "len", "(", "l", ")", "if", "isinstance", "(", "l", ",", "list", ")", "else", "None" ]
https://github.com/google/sling/blob/f408a148a06bc2d62e853a292a8ba7266c642839/python/task/workflow.py#L284-L286
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/msvc.py
python
SystemInfo.WindowsSdkDir
(self)
return sdkdir
Microsoft Windows SDK directory. Return ------ str path
Microsoft Windows SDK directory.
[ "Microsoft", "Windows", "SDK", "directory", "." ]
def WindowsSdkDir(self): """ Microsoft Windows SDK directory. Return ------ str path """ sdkdir = '' for ver in self.WindowsSdkVersion: # Try to get it from registry loc = join(self.ri.windows_sdk, 'v%s' % ver) sdkdir = self.ri.lookup(loc, 'installationfolder') if sdkdir: break if not sdkdir or not isdir(sdkdir): # Try to get "VC++ for Python" version from registry path = join(self.ri.vc_for_python, '%0.1f' % self.vc_ver) install_base = self.ri.lookup(path, 'installdir') if install_base: sdkdir = join(install_base, 'WinSDK') if not sdkdir or not isdir(sdkdir): # If fail, use default new path for ver in self.WindowsSdkVersion: intver = ver[:ver.rfind('.')] path = r'Microsoft SDKs\Windows Kits\%s' % intver d = join(self.ProgramFiles, path) if isdir(d): sdkdir = d if not sdkdir or not isdir(sdkdir): # If fail, use default old path for ver in self.WindowsSdkVersion: path = r'Microsoft SDKs\Windows\v%s' % ver d = join(self.ProgramFiles, path) if isdir(d): sdkdir = d if not sdkdir: # If fail, use Platform SDK sdkdir = join(self.VCInstallDir, 'PlatformSDK') return sdkdir
[ "def", "WindowsSdkDir", "(", "self", ")", ":", "sdkdir", "=", "''", "for", "ver", "in", "self", ".", "WindowsSdkVersion", ":", "# Try to get it from registry", "loc", "=", "join", "(", "self", ".", "ri", ".", "windows_sdk", ",", "'v%s'", "%", "ver", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/msvc.py#L781-L821
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
LymphNodeRFCNNPipeline/pyconvnet/ordereddict.py
python
OrderedDict.fromkeys
(cls, iterable, value=None)
return d
OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).
OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).
[ "OD", ".", "fromkeys", "(", "S", "[", "v", "]", ")", "-", ">", "New", "ordered", "dictionary", "with", "keys", "from", "S", "and", "values", "equal", "to", "v", "(", "which", "defaults", "to", "None", ")", "." ]
def fromkeys(cls, iterable, value=None): '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None). ''' d = cls() for key in iterable: d[key] = value return d
[ "def", "fromkeys", "(", "cls", ",", "iterable", ",", "value", "=", "None", ")", ":", "d", "=", "cls", "(", ")", "for", "key", "in", "iterable", ":", "d", "[", "key", "]", "=", "value", "return", "d" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/LymphNodeRFCNNPipeline/pyconvnet/ordereddict.py#L224-L232