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
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/viewer/mpl/boreholes.py
python
BoreHoles.__init__
(self, fnames)
Load a list of bore hole from filenames.
Load a list of bore hole from filenames.
[ "Load", "a", "list", "of", "bore", "hole", "from", "filenames", "." ]
def __init__(self, fnames): """Load a list of bore hole from filenames.""" self._fnames = fnames if len(fnames) > 0: self.boreholes = [BoreHole(f) for f in fnames] else: raise Warning('No filenames specified!')
[ "def", "__init__", "(", "self", ",", "fnames", ")", ":", "self", ".", "_fnames", "=", "fnames", "if", "len", "(", "fnames", ")", ">", "0", ":", "self", ".", "boreholes", "=", "[", "BoreHole", "(", "f", ")", "for", "f", "in", "fnames", "]", "else"...
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/viewer/mpl/boreholes.py#L104-L110
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/MSVSUserFile.py
python
_FindCommandInPath
(command)
return command
If there are no slashes in the command given, this function searches the PATH env to find the given command, and converts it to an absolute path. We have to do this because MSVS is looking for an actual file to launch a debugger on, not just a command line. Note that this happens at GYP time, so anything needing to be built needs to have a full path.
If there are no slashes in the command given, this function searches the PATH env to find the given command, and converts it to an absolute path. We have to do this because MSVS is looking for an actual file to launch a debugger on, not just a command line. Note that this happens at GYP time, so anything needing to be built needs to have a full path.
[ "If", "there", "are", "no", "slashes", "in", "the", "command", "given", "this", "function", "searches", "the", "PATH", "env", "to", "find", "the", "given", "command", "and", "converts", "it", "to", "an", "absolute", "path", ".", "We", "have", "to", "do",...
def _FindCommandInPath(command): """If there are no slashes in the command given, this function searches the PATH env to find the given command, and converts it to an absolute path. We have to do this because MSVS is looking for an actual file to launch a debugger on, not just a command line. Note that this happens at GYP time, so anything needing to be built needs to have a full path.""" if '/' in command or '\\' in command: # If the command already has path elements (either relative or # absolute), then assume it is constructed properly. return command else: # Search through the path list and find an existing file that # we can access. paths = os.environ.get('PATH','').split(os.pathsep) for path in paths: item = os.path.join(path, command) if os.path.isfile(item) and os.access(item, os.X_OK): return item return command
[ "def", "_FindCommandInPath", "(", "command", ")", ":", "if", "'/'", "in", "command", "or", "'\\\\'", "in", "command", ":", "# If the command already has path elements (either relative or", "# absolute), then assume it is constructed properly.", "return", "command", "else", ":...
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/MSVSUserFile.py#L17-L36
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/re2/re2/unicode.py
python
_UInt
(s)
return v
Converts string to Unicode code point ('263A' => 0x263a). Args: s: string to convert Returns: Unicode code point Raises: InputError: the string is not a valid Unicode value.
Converts string to Unicode code point ('263A' => 0x263a).
[ "Converts", "string", "to", "Unicode", "code", "point", "(", "263A", "=", ">", "0x263a", ")", "." ]
def _UInt(s): """Converts string to Unicode code point ('263A' => 0x263a). Args: s: string to convert Returns: Unicode code point Raises: InputError: the string is not a valid Unicode value. """ try: v = int(s, 16) except ValueError: v = -1 if len(s) < 4 or len(s) > 6 or v < 0 or v > _RUNE_MAX: raise InputError("invalid Unicode value %s" % (s,)) return v
[ "def", "_UInt", "(", "s", ")", ":", "try", ":", "v", "=", "int", "(", "s", ",", "16", ")", "except", "ValueError", ":", "v", "=", "-", "1", "if", "len", "(", "s", ")", "<", "4", "or", "len", "(", "s", ")", ">", "6", "or", "v", "<", "0",...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/re2/re2/unicode.py#L26-L45
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/common/public_api.py
python
PublicAPIVisitor.private_map
(self)
return self._private_map
A map from parents to symbols that should not be included at all. This map can be edited, but it should not be edited once traversal has begun. Returns: The map marking symbols to not include.
A map from parents to symbols that should not be included at all.
[ "A", "map", "from", "parents", "to", "symbols", "that", "should", "not", "be", "included", "at", "all", "." ]
def private_map(self): """A map from parents to symbols that should not be included at all. This map can be edited, but it should not be edited once traversal has begun. Returns: The map marking symbols to not include. """ return self._private_map
[ "def", "private_map", "(", "self", ")", ":", "return", "self", ".", "_private_map" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/common/public_api.py#L78-L87
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/gradients_impl.py
python
_hessian_vector_product
(ys, xs, v)
return gradients(elemwise_products, xs)
Multiply the Hessian of `ys` wrt `xs` by `v`. This is an efficient construction that uses a backprop-like approach to compute the product between the Hessian and another vector. The Hessian is usually too large to be explicitly computed or even represented, but this method allows us to at least multiply by it for the same big-O cost as backprop. Implicit Hessian-vector products are the main practical, scalable way of using second derivatives with neural networks. They allow us to do things like construct Krylov subspaces and approximate conjugate gradient descent. Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y, x, v)` will return an expression that evaluates to the same values as (A + A.T) `v`. Args: ys: A scalar value, or a tensor or list of tensors to be summed to yield a scalar. xs: A list of tensors that we should construct the Hessian over. v: A list of tensors, with the same shapes as xs, that we want to multiply by the Hessian. Returns: A list of tensors (or if the list would be length 1, a single tensor) containing the product between the Hessian and `v`. Raises: ValueError: `xs` and `v` have different length.
Multiply the Hessian of `ys` wrt `xs` by `v`.
[ "Multiply", "the", "Hessian", "of", "ys", "wrt", "xs", "by", "v", "." ]
def _hessian_vector_product(ys, xs, v): """Multiply the Hessian of `ys` wrt `xs` by `v`. This is an efficient construction that uses a backprop-like approach to compute the product between the Hessian and another vector. The Hessian is usually too large to be explicitly computed or even represented, but this method allows us to at least multiply by it for the same big-O cost as backprop. Implicit Hessian-vector products are the main practical, scalable way of using second derivatives with neural networks. They allow us to do things like construct Krylov subspaces and approximate conjugate gradient descent. Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y, x, v)` will return an expression that evaluates to the same values as (A + A.T) `v`. Args: ys: A scalar value, or a tensor or list of tensors to be summed to yield a scalar. xs: A list of tensors that we should construct the Hessian over. v: A list of tensors, with the same shapes as xs, that we want to multiply by the Hessian. Returns: A list of tensors (or if the list would be length 1, a single tensor) containing the product between the Hessian and `v`. Raises: ValueError: `xs` and `v` have different length. """ # Validate the input length = len(xs) if len(v) != length: raise ValueError("xs and v must have the same length.") # First backprop grads = gradients(ys, xs) assert len(grads) == length elemwise_products = [ math_ops.multiply(grad_elem, array_ops.stop_gradient(v_elem)) for grad_elem, v_elem in zip(grads, v) if grad_elem is not None ] # Second backprop return gradients(elemwise_products, xs)
[ "def", "_hessian_vector_product", "(", "ys", ",", "xs", ",", "v", ")", ":", "# Validate the input", "length", "=", "len", "(", "xs", ")", "if", "len", "(", "v", ")", "!=", "length", ":", "raise", "ValueError", "(", "\"xs and v must have the same length.\"", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/gradients_impl.py#L913-L962
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/distribution.py
python
Distribution.construct
(self, name, *args, **kwargs)
return raise_not_implemented_util(name, self.name, *args, **kwargs)
Override `construct` in Cell. Note: Names of supported functions include: 'prob', 'log_prob', 'cdf', 'log_cdf', 'survival_function', 'log_survival', 'var', 'sd', 'mode', 'mean', 'entropy', 'kl_loss', 'cross_entropy', 'sample', 'get_dist_args', and 'get_dist_type'. Args: name (str): The name of the function. *args (list): A list of positional arguments that the function needs. **kwargs (dict): A dictionary of keyword arguments that the function needs.
Override `construct` in Cell.
[ "Override", "construct", "in", "Cell", "." ]
def construct(self, name, *args, **kwargs): """ Override `construct` in Cell. Note: Names of supported functions include: 'prob', 'log_prob', 'cdf', 'log_cdf', 'survival_function', 'log_survival', 'var', 'sd', 'mode', 'mean', 'entropy', 'kl_loss', 'cross_entropy', 'sample', 'get_dist_args', and 'get_dist_type'. Args: name (str): The name of the function. *args (list): A list of positional arguments that the function needs. **kwargs (dict): A dictionary of keyword arguments that the function needs. """ if name == 'log_prob': return self._call_log_prob(*args, **kwargs) if name == 'prob': return self._call_prob(*args, **kwargs) if name == 'cdf': return self._call_cdf(*args, **kwargs) if name == 'log_cdf': return self._call_log_cdf(*args, **kwargs) if name == 'survival_function': return self._call_survival(*args, **kwargs) if name == 'log_survival': return self._call_log_survival(*args, **kwargs) if name == 'kl_loss': return self._kl_loss(*args, **kwargs) if name == 'mean': return self._mean(*args, **kwargs) if name == 'mode': return self._mode(*args, **kwargs) if name == 'sd': return self._call_sd(*args, **kwargs) if name == 'var': return self._call_var(*args, **kwargs) if name == 'entropy': return self._entropy(*args, **kwargs) if name == 'cross_entropy': return self._call_cross_entropy(*args, **kwargs) if name == 'sample': return self._sample(*args, **kwargs) if name == 'get_dist_args': return self._get_dist_args(*args, **kwargs) if name == 'get_dist_type': return self._get_dist_type() return raise_not_implemented_util(name, self.name, *args, **kwargs)
[ "def", "construct", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "name", "==", "'log_prob'", ":", "return", "self", ".", "_call_log_prob", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "name", "==", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/distribution.py#L754-L802
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/logging/__init__.py
python
FileHandler.emit
(self, record)
Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit.
Emit a record.
[ "Emit", "a", "record", "." ]
def emit(self, record): """ Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit. """ if self.stream is None: self.stream = self._open() StreamHandler.emit(self, record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "if", "self", ".", "stream", "is", "None", ":", "self", ".", "stream", "=", "self", ".", "_open", "(", ")", "StreamHandler", ".", "emit", "(", "self", ",", "record", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/logging/__init__.py#L955-L964
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py
python
GenericNodeVisitor.default_departure
(self, node)
Override for generic, uniform traversals.
Override for generic, uniform traversals.
[ "Override", "for", "generic", "uniform", "traversals", "." ]
def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError
[ "def", "default_departure", "(", "self", ",", "node", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py#L1954-L1956
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/metrics/common/path_util.py
python
GetHistogramsFile
()
return GetInputFile('tools/metrics/histograms/histograms.xml')
Returns the path to histograms.xml. Prefer using this function instead of just open("histograms.xml"), so that scripts work properly even if run from outside the histograms directory.
Returns the path to histograms.xml.
[ "Returns", "the", "path", "to", "histograms", ".", "xml", "." ]
def GetHistogramsFile(): """Returns the path to histograms.xml. Prefer using this function instead of just open("histograms.xml"), so that scripts work properly even if run from outside the histograms directory. """ return GetInputFile('tools/metrics/histograms/histograms.xml')
[ "def", "GetHistogramsFile", "(", ")", ":", "return", "GetInputFile", "(", "'tools/metrics/histograms/histograms.xml'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/metrics/common/path_util.py#L10-L16
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBProcess.AppendEventStateReport
(self, *args)
return _lldb.SBProcess_AppendEventStateReport(self, *args)
AppendEventStateReport(self, SBEvent event, SBCommandReturnObject result)
AppendEventStateReport(self, SBEvent event, SBCommandReturnObject result)
[ "AppendEventStateReport", "(", "self", "SBEvent", "event", "SBCommandReturnObject", "result", ")" ]
def AppendEventStateReport(self, *args): """AppendEventStateReport(self, SBEvent event, SBCommandReturnObject result)""" return _lldb.SBProcess_AppendEventStateReport(self, *args)
[ "def", "AppendEventStateReport", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBProcess_AppendEventStateReport", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7010-L7012
BestSonny/SSTD
174d452189f6bf9cf4b6957719392008bd974069
python/caffe/coord_map.py
python
compose
(base_map, next_map)
return ax, a1 * a2, a1 * b2 + b1
Compose a base coord map with scale a1, shift b1 with a further coord map with scale a2, shift b2. The scales multiply and the further shift, b2, is scaled by base coord scale a1.
Compose a base coord map with scale a1, shift b1 with a further coord map with scale a2, shift b2. The scales multiply and the further shift, b2, is scaled by base coord scale a1.
[ "Compose", "a", "base", "coord", "map", "with", "scale", "a1", "shift", "b1", "with", "a", "further", "coord", "map", "with", "scale", "a2", "shift", "b2", ".", "The", "scales", "multiply", "and", "the", "further", "shift", "b2", "is", "scaled", "by", ...
def compose(base_map, next_map): """ Compose a base coord map with scale a1, shift b1 with a further coord map with scale a2, shift b2. The scales multiply and the further shift, b2, is scaled by base coord scale a1. """ ax1, a1, b1 = base_map ax2, a2, b2 = next_map if ax1 is None: ax = ax2 elif ax2 is None or ax1 == ax2: ax = ax1 else: raise AxisMismatchException return ax, a1 * a2, a1 * b2 + b1
[ "def", "compose", "(", "base_map", ",", "next_map", ")", ":", "ax1", ",", "a1", ",", "b1", "=", "base_map", "ax2", ",", "a2", ",", "b2", "=", "next_map", "if", "ax1", "is", "None", ":", "ax", "=", "ax2", "elif", "ax2", "is", "None", "or", "ax1", ...
https://github.com/BestSonny/SSTD/blob/174d452189f6bf9cf4b6957719392008bd974069/python/caffe/coord_map.py#L89-L103
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py
python
__methodDict
(cls, _dict)
helper function for Scrolled Canvas
helper function for Scrolled Canvas
[ "helper", "function", "for", "Scrolled", "Canvas" ]
def __methodDict(cls, _dict): """helper function for Scrolled Canvas""" baseList = list(cls.__bases__) baseList.reverse() for _super in baseList: __methodDict(_super, _dict) for key, value in cls.__dict__.items(): if type(value) == types.FunctionType: _dict[key] = value
[ "def", "__methodDict", "(", "cls", ",", "_dict", ")", ":", "baseList", "=", "list", "(", "cls", ".", "__bases__", ")", "baseList", ".", "reverse", "(", ")", "for", "_super", "in", "baseList", ":", "__methodDict", "(", "_super", ",", "_dict", ")", "for"...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L308-L316
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/aio/_base_channel.py
python
Channel.channel_ready
(self)
Creates a coroutine that blocks until the Channel is READY.
Creates a coroutine that blocks until the Channel is READY.
[ "Creates", "a", "coroutine", "that", "blocks", "until", "the", "Channel", "is", "READY", "." ]
async def channel_ready(self) -> None: """Creates a coroutine that blocks until the Channel is READY."""
[ "async", "def", "channel_ready", "(", "self", ")", "->", "None", ":" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/aio/_base_channel.py#L267-L268
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py
python
ReaderBaseTimeSeriesParser.read_full
(self)
return self._process_records(records)
Reads a full epoch of data into memory.
Reads a full epoch of data into memory.
[ "Reads", "a", "full", "epoch", "of", "data", "into", "memory", "." ]
def read_full(self): """Reads a full epoch of data into memory.""" reader = self._get_reader() # Set a hard limit of 2 epochs through self._filenames. If there are any # records available, we should only end up reading the first record in the # second epoch before exiting the while loop and subsequently resetting the # epoch limit. If there are no records available in any of the files, this # hard limit prevents the reader.read_up_to call from looping infinitely. filename_queue, epoch_limiter = self._get_filename_queue(epoch_limit=2) epoch_reset_op = state_ops.assign(epoch_limiter, 0) with ops.control_dependencies([epoch_reset_op]): first_key, first_value = reader.read_up_to(filename_queue, 1) # Read until we get a duplicate key (one epoch) def _while_condition(current_key, current_value, current_index, collected_records): del current_value, current_index, collected_records # unused return math_ops.not_equal( array_ops.squeeze(current_key, axis=0), array_ops.squeeze(first_key, axis=0)) def _while_body(current_key, current_value, current_index, collected_records): del current_key # unused new_key, new_value = reader.read_up_to(filename_queue, 1) new_key.set_shape([1]) new_value.set_shape([1]) return (new_key, new_value, current_index + 1, collected_records.write(current_index, current_value)) _, _, _, records_ta = control_flow_ops.while_loop( _while_condition, _while_body, [ constant_op.constant([""]), first_value, 0, # current_index starting value tensor_array_ops.TensorArray( # collected_records dtype=dtypes.string, size=0, dynamic_size=True) ]) records = records_ta.concat() # Reset the reader when we're done so that subsequent requests for data get # the dataset in the proper order. with ops.control_dependencies([records]): reader_reset_op = reader.reset() with ops.control_dependencies([reader_reset_op]): records = array_ops.identity(records) return self._process_records(records)
[ "def", "read_full", "(", "self", ")", ":", "reader", "=", "self", ".", "_get_reader", "(", ")", "# Set a hard limit of 2 epochs through self._filenames. If there are any", "# records available, we should only end up reading the first record in the", "# second epoch before exiting the w...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py#L385-L433
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py
python
_AcosGrad
(op, grad)
Returns grad * -1/sqrt(1-x^2).
Returns grad * -1/sqrt(1-x^2).
[ "Returns", "grad", "*", "-", "1", "/", "sqrt", "(", "1", "-", "x^2", ")", "." ]
def _AcosGrad(op, grad): """Returns grad * -1/sqrt(1-x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) den = math_ops.sqrt(math_ops.subtract(one, x2)) if compat.forward_compatible(2019, 9, 14): return -math_ops.xdivy(grad, den) else: inv = math_ops.reciprocal(den) return -grad * inv
[ "def", "_AcosGrad", "(", "op", ",", "grad", ")", ":", "x", "=", "op", ".", "inputs", "[", "0", "]", "with", "ops", ".", "control_dependencies", "(", "[", "grad", "]", ")", ":", "x", "=", "math_ops", ".", "conj", "(", "x", ")", "x2", "=", "math_...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py#L1034-L1046
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits_classes.py
python
find_trivial_constructor
(type_)
return None
Returns reference to trivial constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the trivial constructor
Returns reference to trivial constructor.
[ "Returns", "reference", "to", "trivial", "constructor", "." ]
def find_trivial_constructor(type_): """ Returns reference to trivial constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the trivial constructor """ assert isinstance(type_, class_declaration.class_t) trivial = type_.constructors( lambda x: is_trivial_constructor(x), recursive=False, allow_empty=True) if trivial: return trivial[0] return None
[ "def", "find_trivial_constructor", "(", "type_", ")", ":", "assert", "isinstance", "(", "type_", ",", "class_declaration", ".", "class_t", ")", "trivial", "=", "type_", ".", "constructors", "(", "lambda", "x", ":", "is_trivial_constructor", "(", "x", ")", ",",...
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits_classes.py#L111-L131
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/gzip.py
python
decompress
(data)
Decompress a gzip compressed string in one shot. Return the decompressed string.
Decompress a gzip compressed string in one shot. Return the decompressed string.
[ "Decompress", "a", "gzip", "compressed", "string", "in", "one", "shot", ".", "Return", "the", "decompressed", "string", "." ]
def decompress(data): """Decompress a gzip compressed string in one shot. Return the decompressed string. """ with GzipFile(fileobj=io.BytesIO(data)) as f: return f.read()
[ "def", "decompress", "(", "data", ")", ":", "with", "GzipFile", "(", "fileobj", "=", "io", ".", "BytesIO", "(", "data", ")", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/gzip.py#L538-L543
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_snaps.py
python
ShowSnapBar.GetResources
(self)
return {'Pixmap': 'Draft_Snap', 'MenuText': QT_TRANSLATE_NOOP("Draft_ShowSnapBar","Show snap toolbar"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_ShowSnapBar","Show the snap toolbar if it is hidden.")}
Set icon, menu and tooltip.
Set icon, menu and tooltip.
[ "Set", "icon", "menu", "and", "tooltip", "." ]
def GetResources(self): """Set icon, menu and tooltip.""" return {'Pixmap': 'Draft_Snap', 'MenuText': QT_TRANSLATE_NOOP("Draft_ShowSnapBar","Show snap toolbar"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_ShowSnapBar","Show the snap toolbar if it is hidden.")}
[ "def", "GetResources", "(", "self", ")", ":", "return", "{", "'Pixmap'", ":", "'Draft_Snap'", ",", "'MenuText'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_ShowSnapBar\"", ",", "\"Show snap toolbar\"", ")", ",", "'ToolTip'", ":", "QT_TRANSLATE_NOOP", "(", "\"Draft_Show...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_snaps.py#L585-L590
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/nn/functional/pooling.py
python
max_unpool3d
(x, indices, kernel_size, stride=None, padding=0, data_format="NCDHW", output_size=None, name=None)
return unpool_out
This API implements max unpooling 3d opereation. `max_unpool3d` accepts the output of `max_pool3d` as input, including the indices of the maximum value and calculate the partial inverse. All non-maximum values ​​are set to zero. - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})`, where .. math:: D_{out} = (D_{in} - 1) * stride[0] - 2 * padding[0] + kernel\_size[0] .. math:: H_{out} = (H_{in} - 1) * stride[1] - 2 * padding[1] + kernel\_size[1] .. math:: W_{out} = (W_{in} - 1) * stride[2] - 2 * padding[2] + kernel\_size[2] or as given by :attr:`output_size` in the call operator Args: x (Tensor): The input tensor of unpooling operator which is a 5-D tensor with shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"`, where `N` is batch size, `C` is the number of channels, `D` is the depth of the feature, `H` is the height of the feature, and `W` is the width of the feature. The data type is float32 or float64. indices (Tensor): The indices given out by maxpooling3d which is a 5-D tensor with shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` , where `N` is batch size, `C` is the number of channels, `D` is the depth of the feature, `H` is the height of the feature, and `W` is the width of the feature. The data type is float32 or float64. kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list, it must contain an integer. stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list, it must contain an integer. padding (int | tuple): Padding that was added to the input. output_size(list|tuple, optional): The target output size. If output_size is not specified, the actual output shape will be automatically calculated by (input_shape, kernel_size, stride, padding). data_format (string): The data format of the input and output data. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of unpooling result. Examples: .. code-block:: python import paddle import paddle.nn.functional as F data = paddle.rand(shape=[1, 1, 4, 4, 6]) pool_out, indices = F.max_pool3d(data, kernel_size=2, stride=2, padding=0, return_mask=True) # pool_out shape: [1, 1, 2, 2, 3], indices shape: [1, 1, 2, 2, 3] unpool_out = F.max_unpool3d(pool_out, indices, kernel_size=2, padding=0) # unpool_out shape: [1, 1, 4, 4, 6]
This API implements max unpooling 3d opereation. `max_unpool3d` accepts the output of `max_pool3d` as input, including the indices of the maximum value and calculate the partial inverse. All non-maximum values ​​are set to zero.
[ "This", "API", "implements", "max", "unpooling", "3d", "opereation", ".", "max_unpool3d", "accepts", "the", "output", "of", "max_pool3d", "as", "input", "including", "the", "indices", "of", "the", "maximum", "value", "and", "calculate", "the", "partial", "invers...
def max_unpool3d(x, indices, kernel_size, stride=None, padding=0, data_format="NCDHW", output_size=None, name=None): """ This API implements max unpooling 3d opereation. `max_unpool3d` accepts the output of `max_pool3d` as input, including the indices of the maximum value and calculate the partial inverse. All non-maximum values ​​are set to zero. - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})`, where .. math:: D_{out} = (D_{in} - 1) * stride[0] - 2 * padding[0] + kernel\_size[0] .. math:: H_{out} = (H_{in} - 1) * stride[1] - 2 * padding[1] + kernel\_size[1] .. math:: W_{out} = (W_{in} - 1) * stride[2] - 2 * padding[2] + kernel\_size[2] or as given by :attr:`output_size` in the call operator Args: x (Tensor): The input tensor of unpooling operator which is a 5-D tensor with shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"`, where `N` is batch size, `C` is the number of channels, `D` is the depth of the feature, `H` is the height of the feature, and `W` is the width of the feature. The data type is float32 or float64. indices (Tensor): The indices given out by maxpooling3d which is a 5-D tensor with shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` , where `N` is batch size, `C` is the number of channels, `D` is the depth of the feature, `H` is the height of the feature, and `W` is the width of the feature. The data type is float32 or float64. kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list, it must contain an integer. stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list, it must contain an integer. padding (int | tuple): Padding that was added to the input. output_size(list|tuple, optional): The target output size. If output_size is not specified, the actual output shape will be automatically calculated by (input_shape, kernel_size, stride, padding). data_format (string): The data format of the input and output data. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of unpooling result. Examples: .. code-block:: python import paddle import paddle.nn.functional as F data = paddle.rand(shape=[1, 1, 4, 4, 6]) pool_out, indices = F.max_pool3d(data, kernel_size=2, stride=2, padding=0, return_mask=True) # pool_out shape: [1, 1, 2, 2, 3], indices shape: [1, 1, 2, 2, 3] unpool_out = F.max_unpool3d(pool_out, indices, kernel_size=2, padding=0) # unpool_out shape: [1, 1, 4, 4, 6] """ kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 3, 'pool_stride') padding = utils.convert_to_list(padding, 3, 'padding') if data_format not in ["NCDHW"]: raise ValueError("Attr(data_format) should be 'NCDHW'. Received " "Attr(data_format): %s." % str(data_format)) output_size = _unpool_output_size(x, kernel_size, stride, padding, output_size) if in_dygraph_mode(): output = _C_ops.unpool3d(x, indices, 'unpooling_type', 'max', 'ksize', kernel_size, 'strides', stride, 'paddings', padding, "output_size", output_size, "data_format", data_format) return output op_type = "unpool3d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name="x") unpool_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type=op_type, inputs={"X": x, "Indices": indices}, outputs={"Out": unpool_out}, attrs={ "unpooling_type": "max", "ksize": kernel_size, "strides": stride, "paddings": padding, "output_size": output_size }) return unpool_out
[ "def", "max_unpool3d", "(", "x", ",", "indices", ",", "kernel_size", ",", "stride", "=", "None", ",", "padding", "=", "0", ",", "data_format", "=", "\"NCDHW\"", ",", "output_size", "=", "None", ",", "name", "=", "None", ")", ":", "kernel_size", "=", "u...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/functional/pooling.py#L891-L1000
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PyFontProperty.__init__
(self, *args, **kwargs)
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), Font value=wxFont()) -> PyFontProperty
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), Font value=wxFont()) -> PyFontProperty
[ "__init__", "(", "self", "String", "label", "=", "(", "*", "wxPGProperty", "::", "sm_wxPG_LABEL", ")", "String", "name", "=", "(", "*", "wxPGProperty", "::", "sm_wxPG_LABEL", ")", "Font", "value", "=", "wxFont", "()", ")", "-", ">", "PyFontProperty" ]
def __init__(self, *args, **kwargs): """ __init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL), Font value=wxFont()) -> PyFontProperty """ _propgrid.PyFontProperty_swiginit(self,_propgrid.new_PyFontProperty(*args, **kwargs)) self._SetSelf(self); self._RegisterMethods()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_propgrid", ".", "PyFontProperty_swiginit", "(", "self", ",", "_propgrid", ".", "new_PyFontProperty", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", "."...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L4256-L4262
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py
python
screen.cursor_constrain
(self)
This keeps the cursor within the screen area.
This keeps the cursor within the screen area.
[ "This", "keeps", "the", "cursor", "within", "the", "screen", "area", "." ]
def cursor_constrain (self): '''This keeps the cursor within the screen area. ''' self.cur_r = constrain (self.cur_r, 1, self.rows) self.cur_c = constrain (self.cur_c, 1, self.cols)
[ "def", "cursor_constrain", "(", "self", ")", ":", "self", ".", "cur_r", "=", "constrain", "(", "self", ".", "cur_r", ",", "1", ",", "self", ".", "rows", ")", "self", ".", "cur_c", "=", "constrain", "(", "self", ".", "cur_c", ",", "1", ",", "self", ...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L273-L278
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/transformations.py
python
orthogonalization_matrix
(lengths, angles)
return numpy.array(( ( a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0), (-a*sinb*co, b*sina, 0.0, 0.0), ( a*cosb, b*cosa, c, 0.0), ( 0.0, 0.0, 0.0, 1.0)), dtype=numpy.float64)
Return orthogonalization matrix for crystallographic cell coordinates. Angles are expected in degrees. The de-orthogonalization matrix is the inverse. >>> O = orthogonalization_matrix((10., 10., 10.), (90., 90., 90.)) >>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10) True >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7]) >>> numpy.allclose(numpy.sum(O), 43.063229) True
Return orthogonalization matrix for crystallographic cell coordinates.
[ "Return", "orthogonalization", "matrix", "for", "crystallographic", "cell", "coordinates", "." ]
def orthogonalization_matrix(lengths, angles): """Return orthogonalization matrix for crystallographic cell coordinates. Angles are expected in degrees. The de-orthogonalization matrix is the inverse. >>> O = orthogonalization_matrix((10., 10., 10.), (90., 90., 90.)) >>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10) True >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7]) >>> numpy.allclose(numpy.sum(O), 43.063229) True """ a, b, c = lengths angles = numpy.radians(angles) sina, sinb, _ = numpy.sin(angles) cosa, cosb, cosg = numpy.cos(angles) co = (cosa * cosb - cosg) / (sina * sinb) return numpy.array(( ( a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0), (-a*sinb*co, b*sina, 0.0, 0.0), ( a*cosb, b*cosa, c, 0.0), ( 0.0, 0.0, 0.0, 1.0)), dtype=numpy.float64)
[ "def", "orthogonalization_matrix", "(", "lengths", ",", "angles", ")", ":", "a", ",", "b", ",", "c", "=", "lengths", "angles", "=", "numpy", ".", "radians", "(", "angles", ")", "sina", ",", "sinb", ",", "_", "=", "numpy", ".", "sin", "(", "angles", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/transformations.py#L838-L863
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/util/ssl_.py
python
is_ipaddress
(hostname)
return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))
Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise.
Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs.
[ "Detects", "whether", "the", "hostname", "given", "is", "an", "IPv4", "or", "IPv6", "address", ".", "Also", "detects", "IPv6", "addresses", "with", "Zone", "IDs", "." ]
def is_ipaddress(hostname): """Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise. """ if not six.PY2 and isinstance(hostname, bytes): # IDN A-label bytes are ASCII compatible. hostname = hostname.decode("ascii") return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))
[ "def", "is_ipaddress", "(", "hostname", ")", ":", "if", "not", "six", ".", "PY2", "and", "isinstance", "(", "hostname", ",", "bytes", ")", ":", "# IDN A-label bytes are ASCII compatible.", "hostname", "=", "hostname", ".", "decode", "(", "\"ascii\"", ")", "ret...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/util/ssl_.py#L386-L396
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/meshtools/quality.py
python
_boundaryLengths
(cell)
return np.array( [cell.boundary(i).size() for i in range(cell.boundaryCount())])
Return boundary lengths of a given cell.
Return boundary lengths of a given cell.
[ "Return", "boundary", "lengths", "of", "a", "given", "cell", "." ]
def _boundaryLengths(cell): """Return boundary lengths of a given cell.""" return np.array( [cell.boundary(i).size() for i in range(cell.boundaryCount())])
[ "def", "_boundaryLengths", "(", "cell", ")", ":", "return", "np", ".", "array", "(", "[", "cell", ".", "boundary", "(", "i", ")", ".", "size", "(", ")", "for", "i", "in", "range", "(", "cell", ".", "boundaryCount", "(", ")", ")", "]", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/meshtools/quality.py#L16-L19
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
benchmarks/distributed/rpc/parameter_server/launcher.py
python
run_master
(rank, data, args, extra_configs, rpc_backend_options)
r""" A function that runs the master process in the world. This function obtains remote references to initialized servers, splits the data, runs the trainers, and prints metrics. Args: rank (int): process number in the world data (list): training samples args (parser): benchmark configurations extra_configs (dict): configurations added by the user rpc_backend_options (rpc): configurations/options for the rpc TODO: fix
r""" A function that runs the master process in the world. This function obtains remote references to initialized servers, splits the data, runs the trainers, and prints metrics. Args: rank (int): process number in the world data (list): training samples args (parser): benchmark configurations extra_configs (dict): configurations added by the user rpc_backend_options (rpc): configurations/options for the rpc TODO: fix
[ "r", "A", "function", "that", "runs", "the", "master", "process", "in", "the", "world", ".", "This", "function", "obtains", "remote", "references", "to", "initialized", "servers", "splits", "the", "data", "runs", "the", "trainers", "and", "prints", "metrics", ...
def run_master(rank, data, args, extra_configs, rpc_backend_options): r""" A function that runs the master process in the world. This function obtains remote references to initialized servers, splits the data, runs the trainers, and prints metrics. Args: rank (int): process number in the world data (list): training samples args (parser): benchmark configurations extra_configs (dict): configurations added by the user rpc_backend_options (rpc): configurations/options for the rpc TODO: fix """ world_size = args.ntrainer + args.ncudatrainer + args.nserver + args.ncudaserver + 1 rpc.init_rpc( get_name( rank, args ), rank=rank, world_size=world_size, rpc_backend_options=rpc_backend_options ) server_rrefs = {} for i in range( args.ntrainer + args.ncudatrainer, world_size - 1 ): server_rrefs[i] = get_server_rref(i, args, extra_configs["server_config"]) train_data = split_list( list(DataLoader(data, batch_size=args.batch_size)), args.ntrainer + args.ncudatrainer ) # warmup run the benchmark benchmark_warmup( args, extra_configs["trainer_config"], train_data, server_rrefs ) # run the benchmark trainer_futs = call_trainers( args, extra_configs["trainer_config"], train_data, server_rrefs ) # collect metrics and print metrics_printer = ProcessedMetricsPrinter() rank_metrics_list = wait_all(trainer_futs) metrics_printer.print_metrics("trainer", rank_metrics_list) rank_metrics_list = get_server_metrics(server_rrefs) metrics_printer.print_metrics("server", rank_metrics_list)
[ "def", "run_master", "(", "rank", ",", "data", ",", "args", ",", "extra_configs", ",", "rpc_backend_options", ")", ":", "world_size", "=", "args", ".", "ntrainer", "+", "args", ".", "ncudatrainer", "+", "args", ".", "nserver", "+", "args", ".", "ncudaserve...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/distributed/rpc/parameter_server/launcher.py#L254-L299
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py
python
GroupBy.nth
(self, n: Union[int, List[int]], dropna: Optional[str] = None)
return result
Take the nth row from each group if n is an int, or a subset of rows if n is a list of ints. If dropna, will take the nth non-null row, dropna is either 'all' or 'any'; this is equivalent to calling dropna(how=dropna) before the groupby. Parameters ---------- n : int or list of ints A single nth value for the row or a list of nth values. dropna : None or str, optional Apply the specified dropna operation before counting which row is the nth row. Needs to be None, 'any' or 'all'. Returns ------- Series or DataFrame N-th value within each group. %(see_also)s Examples -------- >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2], ... 'B': [np.nan, 2, 3, 4, 5]}, columns=['A', 'B']) >>> g = df.groupby('A') >>> g.nth(0) B A 1 NaN 2 3.0 >>> g.nth(1) B A 1 2.0 2 5.0 >>> g.nth(-1) B A 1 4.0 2 5.0 >>> g.nth([0, 1]) B A 1 NaN 1 2.0 2 3.0 2 5.0 Specifying `dropna` allows count ignoring ``NaN`` >>> g.nth(0, dropna='any') B A 1 2.0 2 3.0 NaNs denote group exhausted when using dropna >>> g.nth(3, dropna='any') B A 1 NaN 2 NaN Specifying `as_index=False` in `groupby` keeps the original index. >>> df.groupby('A', as_index=False).nth(1) A B 1 1 2.0 4 2 5.0
Take the nth row from each group if n is an int, or a subset of rows if n is a list of ints.
[ "Take", "the", "nth", "row", "from", "each", "group", "if", "n", "is", "an", "int", "or", "a", "subset", "of", "rows", "if", "n", "is", "a", "list", "of", "ints", "." ]
def nth(self, n: Union[int, List[int]], dropna: Optional[str] = None) -> DataFrame: """ Take the nth row from each group if n is an int, or a subset of rows if n is a list of ints. If dropna, will take the nth non-null row, dropna is either 'all' or 'any'; this is equivalent to calling dropna(how=dropna) before the groupby. Parameters ---------- n : int or list of ints A single nth value for the row or a list of nth values. dropna : None or str, optional Apply the specified dropna operation before counting which row is the nth row. Needs to be None, 'any' or 'all'. Returns ------- Series or DataFrame N-th value within each group. %(see_also)s Examples -------- >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2], ... 'B': [np.nan, 2, 3, 4, 5]}, columns=['A', 'B']) >>> g = df.groupby('A') >>> g.nth(0) B A 1 NaN 2 3.0 >>> g.nth(1) B A 1 2.0 2 5.0 >>> g.nth(-1) B A 1 4.0 2 5.0 >>> g.nth([0, 1]) B A 1 NaN 1 2.0 2 3.0 2 5.0 Specifying `dropna` allows count ignoring ``NaN`` >>> g.nth(0, dropna='any') B A 1 2.0 2 3.0 NaNs denote group exhausted when using dropna >>> g.nth(3, dropna='any') B A 1 NaN 2 NaN Specifying `as_index=False` in `groupby` keeps the original index. >>> df.groupby('A', as_index=False).nth(1) A B 1 1 2.0 4 2 5.0 """ valid_containers = (set, list, tuple) if not isinstance(n, (valid_containers, int)): raise TypeError("n needs to be an int or a list/set/tuple of ints") if not dropna: if isinstance(n, int): nth_values = [n] elif isinstance(n, valid_containers): nth_values = list(set(n)) nth_array = np.array(nth_values, dtype=np.intp) self._set_group_selection() mask_left = np.in1d(self._cumcount_array(), nth_array) mask_right = np.in1d(self._cumcount_array(ascending=False) + 1, -nth_array) mask = mask_left | mask_right ids, _, _ = self.grouper.group_info # Drop NA values in grouping mask = mask & (ids != -1) out = self._selected_obj[mask] if not self.as_index: return out result_index = self.grouper.result_index out.index = result_index[ids[mask]] if not self.observed and isinstance(result_index, CategoricalIndex): out = out.reindex(result_index) out = self._reindex_output(out) return out.sort_index() if self.sort else out # dropna is truthy if isinstance(n, valid_containers): raise ValueError("dropna option with a list of nth values is not supported") if dropna not in ["any", "all"]: # Note: when agg-ing picker doesn't raise this, just returns NaN raise ValueError( "For a DataFrame groupby, dropna must be " "either None, 'any' or 'all', " f"(was passed {dropna})." ) # old behaviour, but with all and any support for DataFrames. # modified in GH 7559 to have better perf max_len = n if n >= 0 else -1 - n dropped = self.obj.dropna(how=dropna, axis=self.axis) # get a new grouper for our dropped obj if self.keys is None and self.level is None: # we don't have the grouper info available # (e.g. we have selected out # a column that is not in the current object) axis = self.grouper.axis grouper = axis[axis.isin(dropped.index)] else: # create a grouper with the original parameters, but on dropped # object from pandas.core.groupby.grouper import get_grouper grouper, _, _ = get_grouper( dropped, key=self.keys, axis=self.axis, level=self.level, sort=self.sort, mutated=self.mutated, ) grb = dropped.groupby(grouper, as_index=self.as_index, sort=self.sort) sizes, result = grb.size(), grb.nth(n) mask = (sizes < max_len).values # set the results which don't meet the criteria if len(result) and mask.any(): result.loc[mask] = np.nan # reset/reindex to the original groups if len(self.obj) == len(dropped) or len(result) == len( self.grouper.result_index ): result.index = self.grouper.result_index else: result = result.reindex(self.grouper.result_index) return result
[ "def", "nth", "(", "self", ",", "n", ":", "Union", "[", "int", ",", "List", "[", "int", "]", "]", ",", "dropna", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "DataFrame", ":", "valid_containers", "=", "(", "set", ",", "list", ",", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py#L1671-L1839
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pgen2/driver.py
python
Driver.parse_tokens
(self, tokens, debug=False)
return p.rootnode
Parse a series of tokens and return the syntax tree.
Parse a series of tokens and return the syntax tree.
[ "Parse", "a", "series", "of", "tokens", "and", "return", "the", "syntax", "tree", "." ]
def parse_tokens(self, tokens, debug=False): """Parse a series of tokens and return the syntax tree.""" # XXX Move the prefix computation into a wrapper around tokenize. p = parse.Parser(self.grammar, self.convert) p.setup() lineno = 1 column = 0 type = value = start = end = line_text = None prefix = u"" for quintuple in tokens: type, value, start, end, line_text = quintuple if start != (lineno, column): assert (lineno, column) <= start, ((lineno, column), start) s_lineno, s_column = start if lineno < s_lineno: prefix += "\n" * (s_lineno - lineno) lineno = s_lineno column = 0 if column < s_column: prefix += line_text[column:s_column] column = s_column if type in (tokenize.COMMENT, tokenize.NL): prefix += value lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 continue if type == token.OP: type = grammar.opmap[value] if debug: self.logger.debug("%s %r (prefix=%r)", token.tok_name[type], value, prefix) if p.addtoken(type, value, (prefix, start)): if debug: self.logger.debug("Stop.") break prefix = "" lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 else: # We never broke out -- EOF is too soon (how can this happen???) raise parse.ParseError("incomplete input", type, value, (prefix, start)) return p.rootnode
[ "def", "parse_tokens", "(", "self", ",", "tokens", ",", "debug", "=", "False", ")", ":", "# XXX Move the prefix computation into a wrapper around tokenize.", "p", "=", "parse", ".", "Parser", "(", "self", ".", "grammar", ",", "self", ".", "convert", ")", "p", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pgen2/driver.py#L38-L84
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/pyshell.py
python
PyShell.endexecuting
(self)
Helper for ModifiedInterpreter
Helper for ModifiedInterpreter
[ "Helper", "for", "ModifiedInterpreter" ]
def endexecuting(self): "Helper for ModifiedInterpreter" self.executing = False self.canceled = False self.showprompt()
[ "def", "endexecuting", "(", "self", ")", ":", "self", ".", "executing", "=", "False", "self", ".", "canceled", "=", "False", "self", ".", "showprompt", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/pyshell.py#L997-L1001
JarveeLee/SynthText_Chinese_version
4b2cbc7d14741f21d0bb17966a339ab3574b09a8
colorize3_poisson.py
python
FontColor.complement
(self, rgb_color)
return col_comp
return a color which is complementary to the RGB_COLOR.
return a color which is complementary to the RGB_COLOR.
[ "return", "a", "color", "which", "is", "complementary", "to", "the", "RGB_COLOR", "." ]
def complement(self, rgb_color): """ return a color which is complementary to the RGB_COLOR. """ col_hsv = np.squeeze(cv.cvtColor(rgb_color[None,None,:], cv.cv.CV_RGB2HSV)) col_hsv[0] = col_hsv[0] + 128 #uint8 mods to 255 col_comp = np.squeeze(cv.cvtColor(col_hsv[None,None,:],cv.cv.CV_HSV2RGB)) return col_comp
[ "def", "complement", "(", "self", ",", "rgb_color", ")", ":", "col_hsv", "=", "np", ".", "squeeze", "(", "cv", ".", "cvtColor", "(", "rgb_color", "[", "None", ",", "None", ",", ":", "]", ",", "cv", ".", "cv", ".", "CV_RGB2HSV", ")", ")", "col_hsv",...
https://github.com/JarveeLee/SynthText_Chinese_version/blob/4b2cbc7d14741f21d0bb17966a339ab3574b09a8/colorize3_poisson.py#L104-L111
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/util.py
python
get_logger
()
return _logger
Returns logger used by multiprocessing
Returns logger used by multiprocessing
[ "Returns", "logger", "used", "by", "multiprocessing" ]
def get_logger(): ''' Returns logger used by multiprocessing ''' global _logger import logging, atexit logging._acquireLock() try: if not _logger: _logger = logging.getLogger(LOGGER_NAME) _logger.propagate = 0 logging.addLevelName(SUBDEBUG, 'SUBDEBUG') logging.addLevelName(SUBWARNING, 'SUBWARNING') # XXX multiprocessing should cleanup before logging if hasattr(atexit, 'unregister'): atexit.unregister(_exit_function) atexit.register(_exit_function) else: atexit._exithandlers.remove((_exit_function, (), {})) atexit._exithandlers.append((_exit_function, (), {})) finally: logging._releaseLock() return _logger
[ "def", "get_logger", "(", ")", ":", "global", "_logger", "import", "logging", ",", "atexit", "logging", ".", "_acquireLock", "(", ")", "try", ":", "if", "not", "_logger", ":", "_logger", "=", "logging", ".", "getLogger", "(", "LOGGER_NAME", ")", "_logger",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/util.py#L83-L110
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/otci/otci/otci.py
python
OTCI.udp_bind
(self, ip: str, port: int, netif: NetifIdentifier = NetifIdentifier.THERAD)
Assigns a name (i.e. IPv6 address and port) to the example socket. :param ip: the IPv6 address or the unspecified IPv6 address (::). :param port: the UDP port
Assigns a name (i.e. IPv6 address and port) to the example socket.
[ "Assigns", "a", "name", "(", "i", ".", "e", ".", "IPv6", "address", "and", "port", ")", "to", "the", "example", "socket", "." ]
def udp_bind(self, ip: str, port: int, netif: NetifIdentifier = NetifIdentifier.THERAD): """Assigns a name (i.e. IPv6 address and port) to the example socket. :param ip: the IPv6 address or the unspecified IPv6 address (::). :param port: the UDP port """ bindarg = '' if netif == NetifIdentifier.UNSPECIFIED: bindarg += ' -u' elif netif == NetifIdentifier.BACKBONE: bindarg += ' -b' self.execute_command(f'udp bind{bindarg} {ip} {port}')
[ "def", "udp_bind", "(", "self", ",", "ip", ":", "str", ",", "port", ":", "int", ",", "netif", ":", "NetifIdentifier", "=", "NetifIdentifier", ".", "THERAD", ")", ":", "bindarg", "=", "''", "if", "netif", "==", "NetifIdentifier", ".", "UNSPECIFIED", ":", ...
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L2184-L2196
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/lib/function_base.py
python
_nanop
(op, fill, a, axis=None)
return res
General operation on arrays with not-a-number values. Parameters ---------- op : callable Operation to perform. fill : float NaN values are set to fill before doing the operation. a : array-like Input array. axis : {int, None}, optional Axis along which the operation is computed. By default the input is flattened. Returns ------- y : {ndarray, scalar} Processed data.
General operation on arrays with not-a-number values.
[ "General", "operation", "on", "arrays", "with", "not", "-", "a", "-", "number", "values", "." ]
def _nanop(op, fill, a, axis=None): """ General operation on arrays with not-a-number values. Parameters ---------- op : callable Operation to perform. fill : float NaN values are set to fill before doing the operation. a : array-like Input array. axis : {int, None}, optional Axis along which the operation is computed. By default the input is flattened. Returns ------- y : {ndarray, scalar} Processed data. """ y = array(a, subok=True) # We only need to take care of NaN's in floating point arrays if np.issubdtype(y.dtype, np.integer): return op(y, axis=axis) mask = isnan(a) # y[mask] = fill # We can't use fancy indexing here as it'll mess w/ MaskedArrays # Instead, let's fill the array directly... np.putmask(y, mask, fill) res = op(y, axis=axis) mask_all_along_axis = mask.all(axis=axis) # Along some axes, only nan's were encountered. As such, any values # calculated along that axis should be set to nan. if mask_all_along_axis.any(): if np.isscalar(res): res = np.nan else: res[mask_all_along_axis] = np.nan return res
[ "def", "_nanop", "(", "op", ",", "fill", ",", "a", ",", "axis", "=", "None", ")", ":", "y", "=", "array", "(", "a", ",", "subok", "=", "True", ")", "# We only need to take care of NaN's in floating point arrays", "if", "np", ".", "issubdtype", "(", "y", ...
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/function_base.py#L1337-L1380
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/text_file.py
python
TextFile.__init__
(self, filename=None, file=None, **options)
Construct a new TextFile object. At least one of 'filename' (a string) and 'file' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by 'readline()'.
Construct a new TextFile object. At least one of 'filename' (a string) and 'file' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by 'readline()'.
[ "Construct", "a", "new", "TextFile", "object", ".", "At", "least", "one", "of", "filename", "(", "a", "string", ")", "and", "file", "(", "a", "file", "-", "like", "object", ")", "must", "be", "supplied", ".", "They", "keyword", "argument", "options", "...
def __init__ (self, filename=None, file=None, **options): """Construct a new TextFile object. At least one of 'filename' (a string) and 'file' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by 'readline()'.""" if filename is None and file is None: raise RuntimeError, \ "you must supply either or both of 'filename' and 'file'" # set values for all options -- either from client option hash # or fallback to default_options for opt in self.default_options.keys(): if opt in options: setattr (self, opt, options[opt]) else: setattr (self, opt, self.default_options[opt]) # sanity check client option hash for opt in options.keys(): if opt not in self.default_options: raise KeyError, "invalid TextFile option '%s'" % opt if file is None: self.open (filename) else: self.filename = filename self.file = file self.current_line = 0 # assuming that file is at BOF! # 'linebuf' is a stack of lines that will be emptied before we # actually read from the file; it's only populated by an # 'unreadline()' operation self.linebuf = []
[ "def", "__init__", "(", "self", ",", "filename", "=", "None", ",", "file", "=", "None", ",", "*", "*", "options", ")", ":", "if", "filename", "is", "None", "and", "file", "is", "None", ":", "raise", "RuntimeError", ",", "\"you must supply either or both of...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/text_file.py#L78-L112
ducha-aiki/LSUVinit
a42ecdc0d44c217a29b65e98748d80b90d5c6279
scripts/cpp_lint.py
python
_CppLintState.IncrementErrorCount
(self, category)
Bumps the module's error statistic.
Bumps the module's error statistic.
[ "Bumps", "the", "module", "s", "error", "statistic", "." ]
def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1
[ "def", "IncrementErrorCount", "(", "self", ",", "category", ")", ":", "self", ".", "error_count", "+=", "1", "if", "self", ".", "counting", "in", "(", "'toplevel'", ",", "'detailed'", ")", ":", "if", "self", ".", "counting", "!=", "'detailed'", ":", "cat...
https://github.com/ducha-aiki/LSUVinit/blob/a42ecdc0d44c217a29b65e98748d80b90d5c6279/scripts/cpp_lint.py#L747-L755
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py
python
masked_outside
(x, v1, v2, copy=1)
return array(d, mask = m, copy=copy)
x with mask of all values of x that are outside [v1,v2] v1 and v2 can be given in either order.
x with mask of all values of x that are outside [v1,v2] v1 and v2 can be given in either order.
[ "x", "with", "mask", "of", "all", "values", "of", "x", "that", "are", "outside", "[", "v1", "v2", "]", "v1", "and", "v2", "can", "be", "given", "in", "either", "order", "." ]
def masked_outside(x, v1, v2, copy=1): """x with mask of all values of x that are outside [v1,v2] v1 and v2 can be given in either order. """ if v2 < v1: t = v2 v2 = v1 v1 = t d = filled(x, 0) c = umath.logical_or(umath.less(d, v1), umath.greater(d, v2)) m = mask_or(c, getmask(x)) return array(d, mask = m, copy=copy)
[ "def", "masked_outside", "(", "x", ",", "v1", ",", "v2", ",", "copy", "=", "1", ")", ":", "if", "v2", "<", "v1", ":", "t", "=", "v2", "v2", "=", "v1", "v1", "=", "t", "d", "=", "filled", "(", "x", ",", "0", ")", "c", "=", "umath", ".", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1824-L1835
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/polynomial/polyutils.py
python
mapparms
(old, new)
return off, scl
Linear map parameters between domains. Return the parameters of the linear map ``offset + scale*x`` that maps `old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``. Parameters ---------- old, new : array_like Domains. Each domain must (successfully) convert to a 1-d array containing precisely two values. Returns ------- offset, scale : scalars The map ``L(x) = offset + scale*x`` maps the first domain to the second. See Also -------- getdomain, mapdomain Notes ----- Also works for complex numbers, and thus can be used to calculate the parameters required to map any line in the complex plane to any other line therein. Examples -------- >>> from numpy.polynomial import polyutils as pu >>> pu.mapparms((-1,1),(-1,1)) (0.0, 1.0) >>> pu.mapparms((1,-1),(-1,1)) (0.0, -1.0) >>> i = complex(0,1) >>> pu.mapparms((-i,-1),(1,i)) ((1+1j), (1+0j))
Linear map parameters between domains.
[ "Linear", "map", "parameters", "between", "domains", "." ]
def mapparms(old, new): """ Linear map parameters between domains. Return the parameters of the linear map ``offset + scale*x`` that maps `old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``. Parameters ---------- old, new : array_like Domains. Each domain must (successfully) convert to a 1-d array containing precisely two values. Returns ------- offset, scale : scalars The map ``L(x) = offset + scale*x`` maps the first domain to the second. See Also -------- getdomain, mapdomain Notes ----- Also works for complex numbers, and thus can be used to calculate the parameters required to map any line in the complex plane to any other line therein. Examples -------- >>> from numpy.polynomial import polyutils as pu >>> pu.mapparms((-1,1),(-1,1)) (0.0, 1.0) >>> pu.mapparms((1,-1),(-1,1)) (0.0, -1.0) >>> i = complex(0,1) >>> pu.mapparms((-i,-1),(1,i)) ((1+1j), (1+0j)) """ oldlen = old[1] - old[0] newlen = new[1] - new[0] off = (old[1]*new[0] - old[0]*new[1])/oldlen scl = newlen/oldlen return off, scl
[ "def", "mapparms", "(", "old", ",", "new", ")", ":", "oldlen", "=", "old", "[", "1", "]", "-", "old", "[", "0", "]", "newlen", "=", "new", "[", "1", "]", "-", "new", "[", "0", "]", "off", "=", "(", "old", "[", "1", "]", "*", "new", "[", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/polyutils.py#L300-L345
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/cli/curses_ui.py
python
CursesUI._on_textbox_keypress
(self, x)
Text box key validator: Callback of key strokes. Handles a user's keypress in the input text box. Translates certain keys to terminator keys for the textbox to allow its edit() method to return. Also handles special key-triggered events such as PgUp/PgDown scrolling of the screen output. Args: x: (int) Key code. Returns: (int) A translated key code. In most cases, this is identical to the input x. However, if x is a Return key, the return value will be CLI_TERMINATOR_KEY, so that the text box's edit() method can return. Raises: TypeError: If the input x is not of type int. debugger_cli_common.CommandLineExit: If a mouse-triggered command returns an exit token when dispatched.
Text box key validator: Callback of key strokes.
[ "Text", "box", "key", "validator", ":", "Callback", "of", "key", "strokes", "." ]
def _on_textbox_keypress(self, x): """Text box key validator: Callback of key strokes. Handles a user's keypress in the input text box. Translates certain keys to terminator keys for the textbox to allow its edit() method to return. Also handles special key-triggered events such as PgUp/PgDown scrolling of the screen output. Args: x: (int) Key code. Returns: (int) A translated key code. In most cases, this is identical to the input x. However, if x is a Return key, the return value will be CLI_TERMINATOR_KEY, so that the text box's edit() method can return. Raises: TypeError: If the input x is not of type int. debugger_cli_common.CommandLineExit: If a mouse-triggered command returns an exit token when dispatched. """ if not isinstance(x, int): raise TypeError("Key validator expected type int, received type %s" % type(x)) if x in self.CLI_CR_KEYS: # Make Enter key the terminator self._textbox_curr_terminator = x return self.CLI_TERMINATOR_KEY elif x == self.CLI_TAB_KEY: self._textbox_curr_terminator = self.CLI_TAB_KEY return self.CLI_TERMINATOR_KEY elif x == curses.KEY_PPAGE: self._scroll_output(_SCROLL_UP_A_LINE) return x elif x == curses.KEY_NPAGE: self._scroll_output(_SCROLL_DOWN_A_LINE) return x elif x == curses.KEY_HOME: self._scroll_output(_SCROLL_HOME) return x elif x == curses.KEY_END: self._scroll_output(_SCROLL_END) return x elif x in [curses.KEY_UP, curses.KEY_DOWN]: # Command history navigation. if not self._active_command_history: hist_prefix = self._screen_gather_textbox_str() self._active_command_history = ( self._command_history_store.lookup_prefix( hist_prefix, self._command_history_limit)) if self._active_command_history: if x == curses.KEY_UP: if self._command_pointer < len(self._active_command_history): self._command_pointer += 1 elif x == curses.KEY_DOWN: if self._command_pointer > 0: self._command_pointer -= 1 else: self._command_pointer = 0 self._textbox_curr_terminator = x # Force return from the textbox edit(), so that the textbox can be # redrawn with a history command entered. return self.CLI_TERMINATOR_KEY elif x == curses.KEY_RESIZE: # Respond to terminal resize. self._screen_refresh_size() self._init_layout() self._screen_create_command_window() self._redraw_output() # Force return from the textbox edit(), so that the textbox can be # redrawn. return self.CLI_TERMINATOR_KEY elif x == curses.KEY_MOUSE and self._mouse_enabled: try: _, mouse_x, mouse_y, _, mouse_event_type = self._screen_getmouse() except curses.error: mouse_event_type = None if mouse_event_type == curses.BUTTON1_RELEASED: # Logic for mouse-triggered scrolling. if mouse_x >= self._max_x - 2: scroll_command = self._scroll_bar.get_click_command(mouse_y) if scroll_command is not None: self._scroll_output(scroll_command) return x else: command = self._fetch_hyperlink_command(mouse_x, mouse_y) if command: self._screen_create_command_textbox() exit_token = self._dispatch_command(command) if exit_token is not None: raise debugger_cli_common.CommandLineExit(exit_token=exit_token) else: # Mark the pending command as modified. self._textbox_pending_command_changed = True # Invalidate active command history. self._command_pointer = 0 self._active_command_history = [] return self._KEY_MAP.get(x, x)
[ "def", "_on_textbox_keypress", "(", "self", ",", "x", ")", ":", "if", "not", "isinstance", "(", "x", ",", "int", ")", ":", "raise", "TypeError", "(", "\"Key validator expected type int, received type %s\"", "%", "type", "(", "x", ")", ")", "if", "x", "in", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/curses_ui.py#L775-L878
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Show/Containers.py
python
Container.hasObject
(self, obj)
return obj in self.getAllChildren()
Returns True if the container contains specified object directly.
Returns True if the container contains specified object directly.
[ "Returns", "True", "if", "the", "container", "contains", "specified", "object", "directly", "." ]
def hasObject(self, obj): """Returns True if the container contains specified object directly.""" return obj in self.getAllChildren()
[ "def", "hasObject", "(", "self", ",", "obj", ")", ":", "return", "obj", "in", "self", ".", "getAllChildren", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Show/Containers.py#L148-L150
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/htmllib.py
python
HTMLParser.__init__
(self, formatter, verbose=0)
Creates an instance of the HTMLParser class. The formatter parameter is the formatter instance associated with the parser.
Creates an instance of the HTMLParser class.
[ "Creates", "an", "instance", "of", "the", "HTMLParser", "class", "." ]
def __init__(self, formatter, verbose=0): """Creates an instance of the HTMLParser class. The formatter parameter is the formatter instance associated with the parser. """ sgmllib.SGMLParser.__init__(self, verbose) self.formatter = formatter
[ "def", "__init__", "(", "self", ",", "formatter", ",", "verbose", "=", "0", ")", ":", "sgmllib", ".", "SGMLParser", ".", "__init__", "(", "self", ",", "verbose", ")", "self", ".", "formatter", "=", "formatter" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/htmllib.py#L34-L42
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ListCtrl.SetImageList
(*args, **kwargs)
return _controls_.ListCtrl_SetImageList(*args, **kwargs)
SetImageList(self, ImageList imageList, int which)
SetImageList(self, ImageList imageList, int which)
[ "SetImageList", "(", "self", "ImageList", "imageList", "int", "which", ")" ]
def SetImageList(*args, **kwargs): """SetImageList(self, ImageList imageList, int which)""" return _controls_.ListCtrl_SetImageList(*args, **kwargs)
[ "def", "SetImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_SetImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4613-L4615
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/third_party/Python/module/pexpect-4.6/pexpect/expect.py
python
searcher_re.search
(self, buffer, freshlen, searchwindowsize=None)
return best_index
This searches 'buffer' for the first occurrence of one of the regular expressions. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, returns -1.
This searches 'buffer' for the first occurrence of one of the regular expressions. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before.
[ "This", "searches", "buffer", "for", "the", "first", "occurrence", "of", "one", "of", "the", "regular", "expressions", ".", "freshlen", "must", "indicate", "the", "number", "of", "bytes", "at", "the", "end", "of", "buffer", "which", "have", "not", "been", ...
def search(self, buffer, freshlen, searchwindowsize=None): '''This searches 'buffer' for the first occurrence of one of the regular expressions. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. See class spawn for the 'searchwindowsize' argument. If there is a match this returns the index of that string, and sets 'start', 'end' and 'match'. Otherwise, returns -1.''' first_match = None # 'freshlen' doesn't help here -- we cannot predict the # length of a match, and the re module provides no help. if searchwindowsize is None: searchstart = 0 else: searchstart = max(0, len(buffer) - searchwindowsize) for index, s in self._searches: match = s.search(buffer, searchstart) if match is None: continue n = match.start() if first_match is None or n < first_match: first_match = n the_match = match best_index = index if first_match is None: return -1 self.start = first_match self.match = the_match self.end = self.match.end() return best_index
[ "def", "search", "(", "self", ",", "buffer", ",", "freshlen", ",", "searchwindowsize", "=", "None", ")", ":", "first_match", "=", "None", "# 'freshlen' doesn't help here -- we cannot predict the", "# length of a match, and the re module provides no help.", "if", "searchwindow...
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/expect.py#L275-L306
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/command/egg_info.py
python
FileList._repair
(self)
Replace self.files with only safe paths Because some owners of FileList manipulate the underlying ``files`` attribute directly, this method must be called to repair those paths.
Replace self.files with only safe paths
[ "Replace", "self", ".", "files", "with", "only", "safe", "paths" ]
def _repair(self): """ Replace self.files with only safe paths Because some owners of FileList manipulate the underlying ``files`` attribute directly, this method must be called to repair those paths. """ self.files = list(filter(self._safe_path, self.files))
[ "def", "_repair", "(", "self", ")", ":", "self", ".", "files", "=", "list", "(", "filter", "(", "self", ".", "_safe_path", ",", "self", ".", "files", ")", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/egg_info.py#L484-L492
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ftplib.py
python
FTP.quit
(self)
return resp
Quit, and close the connection.
Quit, and close the connection.
[ "Quit", "and", "close", "the", "connection", "." ]
def quit(self): '''Quit, and close the connection.''' resp = self.voidcmd('QUIT') self.close() return resp
[ "def", "quit", "(", "self", ")", ":", "resp", "=", "self", ".", "voidcmd", "(", "'QUIT'", ")", "self", ".", "close", "(", ")", "return", "resp" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ftplib.py#L663-L667
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/__init__.py
python
run_script
(dist_spec, script_name)
Locate distribution `dist_spec` and run its `script_name` script
Locate distribution `dist_spec` and run its `script_name` script
[ "Locate", "distribution", "dist_spec", "and", "run", "its", "script_name", "script" ]
def run_script(dist_spec, script_name): """Locate distribution `dist_spec` and run its `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name require(dist_spec)[0].run_script(script_name, ns)
[ "def", "run_script", "(", "dist_spec", ",", "script_name", ")", ":", "ns", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", "name", "=", "ns", "[", "'__name__'", "]", "ns", ".", "clear", "(", ")", "ns", "[", "'__name__'", "]", "=", "n...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L463-L469
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/pytorch/rcfr.py
python
RootStateWrapper.counterfactual_regrets_and_reach_weights
(self, regret_player, reach_weight_player, *sequence_weights)
return regrets, reach_weights
Returns counterfactual regrets and reach weights as a tuple. Args: regret_player: The player for whom counterfactual regrets are computed. reach_weight_player: The player for whom reach weights are computed. *sequence_weights: A list of non-negative sequence weights for each player determining the policy profile. Behavioral policies are generated by normalizing sequence weights corresponding to actions in each information state by their sum. Returns: The counterfactual regrets and reach weights as an `np.array`-`np.array` tuple. Raises: ValueError: If there are too few sequence weights at any information state for any player.
Returns counterfactual regrets and reach weights as a tuple.
[ "Returns", "counterfactual", "regrets", "and", "reach", "weights", "as", "a", "tuple", "." ]
def counterfactual_regrets_and_reach_weights(self, regret_player, reach_weight_player, *sequence_weights): """Returns counterfactual regrets and reach weights as a tuple. Args: regret_player: The player for whom counterfactual regrets are computed. reach_weight_player: The player for whom reach weights are computed. *sequence_weights: A list of non-negative sequence weights for each player determining the policy profile. Behavioral policies are generated by normalizing sequence weights corresponding to actions in each information state by their sum. Returns: The counterfactual regrets and reach weights as an `np.array`-`np.array` tuple. Raises: ValueError: If there are too few sequence weights at any information state for any player. """ num_players = len(sequence_weights) regrets = np.zeros(self.num_player_sequences[regret_player]) reach_weights = np.zeros(self.num_player_sequences[reach_weight_player]) def _walk_descendants(state, reach_probabilities, chance_reach_probability): """Compute `state`'s counterfactual regrets and reach weights. Args: state: An OpenSpiel `State`. reach_probabilities: The probability that each player plays to reach `state`'s history. chance_reach_probability: The probability that all chance outcomes in `state`'s history occur. Returns: The counterfactual value of `state`'s history. Raises: ValueError if there are too few sequence weights at any information state for any player. """ if state.is_terminal(): player_reach = ( np.prod(reach_probabilities[:regret_player]) * np.prod(reach_probabilities[regret_player + 1:])) counterfactual_reach_prob = player_reach * chance_reach_probability u = self.terminal_values[state.history_str()] return u[regret_player] * counterfactual_reach_prob elif state.is_chance_node(): v = 0.0 for action, action_prob in state.chance_outcomes(): v += _walk_descendants( state.child(action), reach_probabilities, chance_reach_probability * action_prob) return v player = state.current_player() info_state = state.information_state_string(player) sequence_idx_offset = self.info_state_to_sequence_idx[info_state] actions = state.legal_actions(player) sequence_idx_end = sequence_idx_offset + len(actions) my_sequence_weights = sequence_weights[player][ sequence_idx_offset:sequence_idx_end] if len(my_sequence_weights) < len(actions): raise ValueError( ("Invalid policy: Policy {player} at sequence offset " "{sequence_idx_offset} has only {policy_len} elements but there " "are {num_actions} legal actions.").format( player=player, sequence_idx_offset=sequence_idx_offset, policy_len=len(my_sequence_weights), num_actions=len(actions))) policy = normalized_by_sum(my_sequence_weights) action_values = np.zeros(len(actions)) state_value = 0.0 is_reach_weight_player_node = player == reach_weight_player is_regret_player_node = player == regret_player reach_prob = reach_probabilities[player] for action_idx, action in enumerate(actions): action_prob = policy[action_idx] next_reach_prob = reach_prob * action_prob if is_reach_weight_player_node: reach_weight_player_plays_down_this_line = next_reach_prob > 0 if not reach_weight_player_plays_down_this_line: continue sequence_idx = sequence_idx_offset + action_idx reach_weights[sequence_idx] += next_reach_prob reach_probabilities[player] = next_reach_prob action_value = _walk_descendants( state.child(action), reach_probabilities, chance_reach_probability) if is_regret_player_node: state_value = state_value + action_prob * action_value else: state_value = state_value + action_value action_values[action_idx] = action_value reach_probabilities[player] = reach_prob if is_regret_player_node: regrets[sequence_idx_offset:sequence_idx_end] += ( action_values - state_value) return state_value # End of _walk_descendants _walk_descendants(self.root, np.ones(num_players), 1.0) return regrets, reach_weights
[ "def", "counterfactual_regrets_and_reach_weights", "(", "self", ",", "regret_player", ",", "reach_weight_player", ",", "*", "sequence_weights", ")", ":", "num_players", "=", "len", "(", "sequence_weights", ")", "regrets", "=", "np", ".", "zeros", "(", "self", ".",...
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/pytorch/rcfr.py#L263-L381
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/learn_runner.py
python
tune
(experiment_fn, tuner)
Tune an experiment with hyper-parameters. It iterates trials by running the Experiment for each trial with the corresponding hyper-parameters. For each trial, it retrieves the hyper-parameters from `tuner`, creates an Experiment by calling experiment_fn, and then reports the measure back to `tuner`. Example: ``` def _create_my_experiment(run_config, hparams): hidden_units = [hparams.unit_per_layer] * hparams.num_hidden_layers return tf.contrib.learn.Experiment( estimator=DNNClassifier(config=run_config, hidden_units=hidden_units), train_input_fn=my_train_input, eval_input_fn=my_eval_input) tuner = create_tuner(study_configuration, objective_key) learn_runner.tune(experiment_fn=_create_my_experiment, tuner) ``` Args: experiment_fn: A function that creates an `Experiment`. It should accept an argument `run_config` which should be used to create the `Estimator` ( passed as `config` to its constructor), and an argument `hparams`, which should be used for hyper-parameters tuning. It must return an `Experiment`. tuner: A `Tuner` instance.
Tune an experiment with hyper-parameters.
[ "Tune", "an", "experiment", "with", "hyper", "-", "parameters", "." ]
def tune(experiment_fn, tuner): """Tune an experiment with hyper-parameters. It iterates trials by running the Experiment for each trial with the corresponding hyper-parameters. For each trial, it retrieves the hyper-parameters from `tuner`, creates an Experiment by calling experiment_fn, and then reports the measure back to `tuner`. Example: ``` def _create_my_experiment(run_config, hparams): hidden_units = [hparams.unit_per_layer] * hparams.num_hidden_layers return tf.contrib.learn.Experiment( estimator=DNNClassifier(config=run_config, hidden_units=hidden_units), train_input_fn=my_train_input, eval_input_fn=my_eval_input) tuner = create_tuner(study_configuration, objective_key) learn_runner.tune(experiment_fn=_create_my_experiment, tuner) ``` Args: experiment_fn: A function that creates an `Experiment`. It should accept an argument `run_config` which should be used to create the `Estimator` ( passed as `config` to its constructor), and an argument `hparams`, which should be used for hyper-parameters tuning. It must return an `Experiment`. tuner: A `Tuner` instance. """ while tuner.next_trial(): tuner.run_experiment( _wrapped_experiment_fn_with_uid_check( experiment_fn, require_hparams=True))
[ "def", "tune", "(", "experiment_fn", ",", "tuner", ")", ":", "while", "tuner", ".", "next_trial", "(", ")", ":", "tuner", ".", "run_experiment", "(", "_wrapped_experiment_fn_with_uid_check", "(", "experiment_fn", ",", "require_hparams", "=", "True", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/learn_runner.py#L229-L262
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/TaskGen.py
python
task_gen.get_hook
(self, node)
Returns the ``@extension`` method to call for a Node of a particular extension. :param node: Input file to process :type node: :py:class:`waflib.Tools.Node.Node` :return: A method able to process the input node by looking at the extension :rtype: function
Returns the ``@extension`` method to call for a Node of a particular extension.
[ "Returns", "the", "@extension", "method", "to", "call", "for", "a", "Node", "of", "a", "particular", "extension", "." ]
def get_hook(self, node): """ Returns the ``@extension`` method to call for a Node of a particular extension. :param node: Input file to process :type node: :py:class:`waflib.Tools.Node.Node` :return: A method able to process the input node by looking at the extension :rtype: function """ name = node.name for k in self.mappings: try: if name.endswith(k): return self.mappings[k] except TypeError: # regexps objects if k.match(name): return self.mappings[k] keys = list(self.mappings.keys()) raise Errors.WafError("File %r has no mapping in %r (load a waf tool?)" % (node, keys))
[ "def", "get_hook", "(", "self", ",", "node", ")", ":", "name", "=", "node", ".", "name", "for", "k", "in", "self", ".", "mappings", ":", "try", ":", "if", "name", ".", "endswith", "(", "k", ")", ":", "return", "self", ".", "mappings", "[", "k", ...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/TaskGen.py#L244-L263
zerollzeng/tiny-tensorrt
e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2
third_party/pybind11/tools/clang/cindex.py
python
Cursor.spelling
(self)
return self._spelling
Return the spelling of the entity pointed at by the cursor.
Return the spelling of the entity pointed at by the cursor.
[ "Return", "the", "spelling", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
def spelling(self): """Return the spelling of the entity pointed at by the cursor.""" if not hasattr(self, '_spelling'): self._spelling = conf.lib.clang_getCursorSpelling(self) return self._spelling
[ "def", "spelling", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_spelling'", ")", ":", "self", ".", "_spelling", "=", "conf", ".", "lib", ".", "clang_getCursorSpelling", "(", "self", ")", "return", "self", ".", "_spelling" ]
https://github.com/zerollzeng/tiny-tensorrt/blob/e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2/third_party/pybind11/tools/clang/cindex.py#L1398-L1403
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/gdb/mongo_printers.py
python
DecorablePrinter.children
(self)
Children.
Children.
[ "Children", "." ]
def children(self): """Children.""" decoration_data = get_unique_ptr(self.val["_decorations"]["_decorationData"]) for index in range(self.count): descriptor = self.start[index] dindex = int(descriptor["descriptor"]["_index"]) # In order to get the type stored in the decorable, we examine the type of its # constructor, and do some string manipulations. # TODO: abstract out navigating a std::function type_name = str(descriptor["constructor"]) type_name = type_name[0:len(type_name) - 1] type_name = type_name[0:type_name.rindex(">")] type_name = type_name[type_name.index("constructAt<"):].replace("constructAt<", "") # If the type is a pointer type, strip the * at the end. if type_name.endswith('*'): type_name = type_name[0:len(type_name) - 1] type_name = type_name.rstrip() # Cast the raw char[] into the actual object that is stored there. type_t = gdb.lookup_type(type_name) obj = decoration_data[dindex].cast(type_t) yield ('key', "%d:%s:%s" % (index, obj.address, type_name)) yield ('value', obj)
[ "def", "children", "(", "self", ")", ":", "decoration_data", "=", "get_unique_ptr", "(", "self", ".", "val", "[", "\"_decorations\"", "]", "[", "\"_decorationData\"", "]", ")", "for", "index", "in", "range", "(", "self", ".", "count", ")", ":", "descriptor...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/gdb/mongo_printers.py#L297-L323
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/prefdlg.py
python
NetConfigPage._DoLayout
(self)
Layout the controls in the panel
Layout the controls in the panel
[ "Layout", "the", "controls", "in", "the", "panel" ]
def _DoLayout(self): """Layout the controls in the panel""" msizer = wx.BoxSizer(wx.VERTICAL) sboxsz = wx.StaticBoxSizer(wx.StaticBox(self, label=_("Proxy Settings")), wx.VERTICAL) flexg = wx.FlexGridSizer(4, 2, 10, 5) flexg.AddGrowableCol(1, 1) proxy_val = Profile_Get('PROXY_SETTINGS', default=dict()) use_proxy = wx.CheckBox(self, ID_USE_PROXY, _("Use Proxy")) use_proxy.SetValue(Profile_Get('USE_PROXY', 'bool', False)) sboxsz.AddMany([(use_proxy, 0, wx.ALIGN_LEFT), ((10, 10), 0)]) url_sz = wx.BoxSizer(wx.HORIZONTAL) url_lbl = wx.StaticText(self, label=_("Proxy URL") + u":") url_txt = wx.TextCtrl(self, ID_URL, proxy_val.get('url', '')) port_sep = wx.StaticText(self, label=":") port_txt = wx.TextCtrl(self, ID_PORT, proxy_val.get('port', '')) port_txt.SetToolTipString(_("Port Number")) url_sz.AddMany([(url_txt, 1, wx.EXPAND), ((2, 2)), (port_sep, 0, wx.ALIGN_CENTER_VERTICAL), ((2, 2)), (port_txt, 0, wx.ALIGN_CENTER_VERTICAL)]) flexg.AddMany([(url_lbl, 0, wx.ALIGN_CENTER_VERTICAL), (url_sz, 0, wx.EXPAND)]) usr_sz = wx.BoxSizer(wx.HORIZONTAL) usr_lbl = wx.StaticText(self, label=_("Username") + u":") usr_txt = wx.TextCtrl(self, ID_USERNAME, proxy_val.get('uname', '')) usr_sz.Add(usr_txt, 1, wx.EXPAND) flexg.AddMany([(usr_lbl, 0, wx.ALIGN_CENTER_VERTICAL), (usr_sz, 0, wx.EXPAND)]) pass_sz = wx.BoxSizer(wx.HORIZONTAL) pass_lbl = wx.StaticText(self, label=_("Password") + u":") pass_txt = wx.TextCtrl(self, ID_PASSWORD, ed_crypt.Decrypt(proxy_val.get('passwd', ''), proxy_val.get('pid', '')), style=wx.TE_PASSWORD) pass_sz.Add(pass_txt, 1, wx.EXPAND) flexg.AddMany([(pass_lbl, 0, wx.ALIGN_CENTER_VERTICAL), (pass_sz, 0, wx.EXPAND), ((5, 5), 0)]) apply_b = wx.Button(self, wx.ID_APPLY) flexg.Add(apply_b, 0, wx.ALIGN_RIGHT) if wx.Platform == '__WXMAC__': for lbl in (use_proxy, url_txt, port_sep, port_txt, url_lbl, usr_lbl, usr_txt, pass_lbl, pass_txt, apply_b): lbl.SetWindowVariant(wx.WINDOW_VARIANT_SMALL) self.EnableControls(use_proxy.GetValue()) sboxsz.Add(flexg, 1, wx.EXPAND) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.AddMany([((5, 5)), (sboxsz, 1, wx.EXPAND), ((5, 5))]) msizer.AddMany([((10, 10)), (hsizer, 1, wx.EXPAND), ((10, 10))]) self.SetSizer(msizer)
[ "def", "_DoLayout", "(", "self", ")", ":", "msizer", "=", "wx", ".", "BoxSizer", "(", "wx", ".", "VERTICAL", ")", "sboxsz", "=", "wx", ".", "StaticBoxSizer", "(", "wx", ".", "StaticBox", "(", "self", ",", "label", "=", "_", "(", "\"Proxy Settings\"", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/prefdlg.py#L1418-L1474
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/webencodings/__init__.py
python
ascii_lower
(string)
return string.encode('utf8').lower().decode('utf8')
r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z. :param string: An Unicode string. :returns: A new Unicode string. This is used for `ASCII case-insensitive <http://encoding.spec.whatwg.org/#ascii-case-insensitive>`_ matching of encoding labels. The same matching is also used, among other things, for `CSS keywords <http://dev.w3.org/csswg/css-values/#keywords>`_. This is different from the :meth:`~py:str.lower` method of Unicode strings which also affect non-ASCII characters, sometimes mapping them into the ASCII range: >>> keyword = u'Bac\N{KELVIN SIGN}ground' >>> assert keyword.lower() == u'background' >>> assert ascii_lower(keyword) != keyword.lower() >>> assert ascii_lower(keyword) == u'bac\N{KELVIN SIGN}ground'
r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.
[ "r", "Transform", "(", "only", ")", "ASCII", "letters", "to", "lower", "case", ":", "A", "-", "Z", "is", "mapped", "to", "a", "-", "z", "." ]
def ascii_lower(string): r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z. :param string: An Unicode string. :returns: A new Unicode string. This is used for `ASCII case-insensitive <http://encoding.spec.whatwg.org/#ascii-case-insensitive>`_ matching of encoding labels. The same matching is also used, among other things, for `CSS keywords <http://dev.w3.org/csswg/css-values/#keywords>`_. This is different from the :meth:`~py:str.lower` method of Unicode strings which also affect non-ASCII characters, sometimes mapping them into the ASCII range: >>> keyword = u'Bac\N{KELVIN SIGN}ground' >>> assert keyword.lower() == u'background' >>> assert ascii_lower(keyword) != keyword.lower() >>> assert ascii_lower(keyword) == u'bac\N{KELVIN SIGN}ground' """ # This turns out to be faster than unicode.translate() return string.encode('utf8').lower().decode('utf8')
[ "def", "ascii_lower", "(", "string", ")", ":", "# This turns out to be faster than unicode.translate()", "return", "string", ".", "encode", "(", "'utf8'", ")", ".", "lower", "(", ")", ".", "decode", "(", "'utf8'", ")" ]
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/webencodings/__init__.py#L35-L58
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/html5lib-python/html5lib/inputstream.py
python
HTMLBinaryInputStream.detectEncodingMeta
(self)
return encoding
Report the encoding declared by the meta element
Report the encoding declared by the meta element
[ "Report", "the", "encoding", "declared", "by", "the", "meta", "element" ]
def detectEncodingMeta(self): """Report the encoding declared by the meta element """ buffer = self.rawStream.read(self.numBytesMeta) assert isinstance(buffer, bytes) parser = EncodingParser(buffer) self.rawStream.seek(0) encoding = parser.getEncoding() if encoding in ("utf-16", "utf-16-be", "utf-16-le"): encoding = "utf-8" return encoding
[ "def", "detectEncodingMeta", "(", "self", ")", ":", "buffer", "=", "self", ".", "rawStream", ".", "read", "(", "self", ".", "numBytesMeta", ")", "assert", "isinstance", "(", "buffer", ",", "bytes", ")", "parser", "=", "EncodingParser", "(", "buffer", ")", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/html5lib-python/html5lib/inputstream.py#L553-L565
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/adidas_utils/solvers/symmetric/qre.py
python
Solver.record_aux_errors
(self, grads)
Record errors for the auxiliary variables.
Record errors for the auxiliary variables.
[ "Record", "errors", "for", "the", "auxiliary", "variables", "." ]
def record_aux_errors(self, grads): """Record errors for the auxiliary variables.""" grad_y = grads[1] self.aux_errors.append([np.linalg.norm(grad_y)])
[ "def", "record_aux_errors", "(", "self", ",", "grads", ")", ":", "grad_y", "=", "grads", "[", "1", "]", "self", ".", "aux_errors", ".", "append", "(", "[", "np", ".", "linalg", ".", "norm", "(", "grad_y", ")", "]", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/symmetric/qre.py#L70-L73
TimoSaemann/caffe-segnet-cudnn5
abcf30dca449245e101bf4ced519f716177f0885
scripts/cpp_lint.py
python
_NestingState.CheckCompletedBlocks
(self, filename, error)
Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
Checks that all classes and namespaces have been completely parsed.
[ "Checks", "that", "all", "classes", "and", "namespaces", "have", "been", "completely", "parsed", "." ]
def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name)
[ "def", "CheckCompletedBlocks", "(", "self", ",", "filename", ",", "error", ")", ":", "# Note: This test can result in false positives if #ifdef constructs", "# get in the way of brace matching. See the testBuildClass test in", "# cpplint_unittest.py for an example of this.", "for", "obj"...
https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L2172-L2191
mapsme/omim
1892903b63f2c85b16ed4966d21fe76aba06b9ba
tools/python/maps_generator/generator/generation.py
python
Generation.reset_to_stage
(self, stage_name: AnyStr)
Resets generation state to stage_name. Status files are overwritten new statuses according stage_name. It supposes that stages have next representation: stage1, ..., stage_mwm[country_stage_1, ..., country_stage_M], ..., stageN
Resets generation state to stage_name. Status files are overwritten new statuses according stage_name. It supposes that stages have next representation: stage1, ..., stage_mwm[country_stage_1, ..., country_stage_M], ..., stageN
[ "Resets", "generation", "state", "to", "stage_name", ".", "Status", "files", "are", "overwritten", "new", "statuses", "according", "stage_name", ".", "It", "supposes", "that", "stages", "have", "next", "representation", ":", "stage1", "...", "stage_mwm", "[", "c...
def reset_to_stage(self, stage_name: AnyStr): """ Resets generation state to stage_name. Status files are overwritten new statuses according stage_name. It supposes that stages have next representation: stage1, ..., stage_mwm[country_stage_1, ..., country_stage_M], ..., stageN """ high_level_stages = [get_stage_name(s) for s in self.runnable_stages] if not ( stage_name in high_level_stages or any(stage_name == get_stage_name(s) for s in stages.countries_stages) ): raise ContinueError(f"{stage_name} not in {', '.join(high_level_stages)}.") if not os.path.exists(self.env.paths.status_path): raise ContinueError(f"Status path {self.env.paths.status_path} not found.") if not os.path.exists(self.env.paths.main_status_path): raise ContinueError( f"Status file {self.env.paths.main_status_path} not found." ) countries_statuses_paths = [] countries = set(self.env.countries) for f in os.listdir(self.env.paths.status_path): full_name = os.path.join(self.env.paths.status_path, f) if ( os.path.isfile(full_name) and full_name != self.env.paths.main_status_path and without_stat_ext(f) in countries ): countries_statuses_paths.append(full_name) def set_countries_stage(st): for path in countries_statuses_paths: Status(path, st).update_status() def finish_countries_stage(): for path in countries_statuses_paths: Status(path).finish() def index(l: List, val): try: return l.index(val) except ValueError: return -1 mwm_stage_name = get_stage_name(stages.mwm_stage) stage_mwm_index = index(high_level_stages, mwm_stage_name) main_status = None if ( stage_mwm_index == -1 or stage_name in high_level_stages[: stage_mwm_index + 1] ): main_status = stage_name set_countries_stage("") elif stage_name in high_level_stages[stage_mwm_index + 1 :]: main_status = stage_name finish_countries_stage() else: main_status = get_stage_name(stages.mwm_stage) set_countries_stage(stage_name) Status(self.env.paths.main_status_path, main_status).update_status()
[ "def", "reset_to_stage", "(", "self", ",", "stage_name", ":", "AnyStr", ")", ":", "high_level_stages", "=", "[", "get_stage_name", "(", "s", ")", "for", "s", "in", "self", ".", "runnable_stages", "]", "if", "not", "(", "stage_name", "in", "high_level_stages"...
https://github.com/mapsme/omim/blob/1892903b63f2c85b16ed4966d21fe76aba06b9ba/tools/python/maps_generator/generator/generation.py#L87-L151
apache/trafodion
8455c839ad6b6d7b6e04edda5715053095b78046
core/sqf/src/seatrans/hbase-trx/src/main/python/thrift1/gen-py/hbase/Hbase.py
python
Iface.getRowsWithColumnsTs
(self, tableName, rows, columns, timestamp, attributes)
Get the specified columns for the specified table and rows at the specified timestamp. Returns an empty list if no rows exist. @return TRowResult containing the rows and map of columns to TCells Parameters: - tableName: name of table - rows: row keys - columns: List of columns to return, null for all columns - timestamp - attributes: Get attributes
Get the specified columns for the specified table and rows at the specified timestamp. Returns an empty list if no rows exist.
[ "Get", "the", "specified", "columns", "for", "the", "specified", "table", "and", "rows", "at", "the", "specified", "timestamp", ".", "Returns", "an", "empty", "list", "if", "no", "rows", "exist", "." ]
def getRowsWithColumnsTs(self, tableName, rows, columns, timestamp, attributes): """ Get the specified columns for the specified table and rows at the specified timestamp. Returns an empty list if no rows exist. @return TRowResult containing the rows and map of columns to TCells Parameters: - tableName: name of table - rows: row keys - columns: List of columns to return, null for all columns - timestamp - attributes: Get attributes """ pass
[ "def", "getRowsWithColumnsTs", "(", "self", ",", "tableName", ",", "rows", ",", "columns", ",", "timestamp", ",", "attributes", ")", ":", "pass" ]
https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/core/sqf/src/seatrans/hbase-trx/src/main/python/thrift1/gen-py/hbase/Hbase.py#L275-L289
OpenMined/PyDP
a88ee73053aa2bdc1be327a77109dd5907ab41d6
src/pydp/ml/mechanisms/base.py
python
DPMachine.copy
(self)
return copy(self)
Produces a copy of the class. Returns ------- self : class Returns the copy.
Produces a copy of the class. Returns ------- self : class Returns the copy.
[ "Produces", "a", "copy", "of", "the", "class", ".", "Returns", "-------", "self", ":", "class", "Returns", "the", "copy", "." ]
def copy(self): """Produces a copy of the class. Returns ------- self : class Returns the copy. """ return copy(self)
[ "def", "copy", "(", "self", ")", ":", "return", "copy", "(", "self", ")" ]
https://github.com/OpenMined/PyDP/blob/a88ee73053aa2bdc1be327a77109dd5907ab41d6/src/pydp/ml/mechanisms/base.py#L46-L53
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/quoprimime.py
python
body_length
(bytearray)
return sum(len(_QUOPRI_BODY_MAP[octet]) for octet in bytearray)
Return a body quoted-printable encoding length. :param bytearray: An array of bytes (a.k.a. octets). :return: The length in bytes of the byte array when it is encoded with quoted-printable for bodies.
Return a body quoted-printable encoding length.
[ "Return", "a", "body", "quoted", "-", "printable", "encoding", "length", "." ]
def body_length(bytearray): """Return a body quoted-printable encoding length. :param bytearray: An array of bytes (a.k.a. octets). :return: The length in bytes of the byte array when it is encoded with quoted-printable for bodies. """ return sum(len(_QUOPRI_BODY_MAP[octet]) for octet in bytearray)
[ "def", "body_length", "(", "bytearray", ")", ":", "return", "sum", "(", "len", "(", "_QUOPRI_BODY_MAP", "[", "octet", "]", ")", "for", "octet", "in", "bytearray", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/quoprimime.py#L97-L104
cztomczak/cefpython
5679f28cec18a57a56e298da2927aac8d8f83ad6
examples/pysdl2.py
python
die
(msg)
Helper function to exit application on failed imports etc.
Helper function to exit application on failed imports etc.
[ "Helper", "function", "to", "exit", "application", "on", "failed", "imports", "etc", "." ]
def die(msg): """ Helper function to exit application on failed imports etc. """ sys.stderr.write("%s\n" % msg) sys.exit(1)
[ "def", "die", "(", "msg", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"%s\\n\"", "%", "msg", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/examples/pysdl2.py#L58-L63
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/neighbors/kde.py
python
KernelDensity.score
(self, X, y=None)
return np.sum(self.score_samples(X))
Compute the total log probability under the model. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- logprob : float Total log-likelihood of the data in X.
Compute the total log probability under the model.
[ "Compute", "the", "total", "log", "probability", "under", "the", "model", "." ]
def score(self, X, y=None): """Compute the total log probability under the model. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- logprob : float Total log-likelihood of the data in X. """ return np.sum(self.score_samples(X))
[ "def", "score", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "return", "np", ".", "sum", "(", "self", ".", "score_samples", "(", "X", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/neighbors/kde.py#L161-L175
Tokutek/mongo
0653eabe2c5b9d12b4814617cb7fb2d799937a0f
src/third_party/v8/tools/stats-viewer.py
python
CounterCollection.Counter
(self, index)
return Counter(self.data, 16 + index * self.CounterSize())
Return the index'th counter.
Return the index'th counter.
[ "Return", "the", "index", "th", "counter", "." ]
def Counter(self, index): """Return the index'th counter.""" return Counter(self.data, 16 + index * self.CounterSize())
[ "def", "Counter", "(", "self", ",", "index", ")", ":", "return", "Counter", "(", "self", ".", "data", ",", "16", "+", "index", "*", "self", ".", "CounterSize", "(", ")", ")" ]
https://github.com/Tokutek/mongo/blob/0653eabe2c5b9d12b4814617cb7fb2d799937a0f/src/third_party/v8/tools/stats-viewer.py#L374-L376
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
toolkit/crashreporter/tools/symbolstore.py
python
VCSFileInfo.GetRoot
(self)
This method should return the unmodified root for the file or 'None' on failure.
This method should return the unmodified root for the file or 'None' on failure.
[ "This", "method", "should", "return", "the", "unmodified", "root", "for", "the", "file", "or", "None", "on", "failure", "." ]
def GetRoot(self): """ This method should return the unmodified root for the file or 'None' on failure. """ raise NotImplementedError
[ "def", "GetRoot", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/toolkit/crashreporter/tools/symbolstore.py#L96-L99
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/integrate/quadpack.py
python
nquad
(func, ranges, args=None, opts=None, full_output=False)
return _NQuad(func, ranges, opts, full_output).integrate(*args)
Integration over multiple variables. Wraps `quad` to enable integration over multiple variables. Various options allow improved integration of discontinuous functions, as well as the use of weighted integration, and generally finer control of the integration process. Parameters ---------- func : {callable, scipy.LowLevelCallable} The function to be integrated. Has arguments of ``x0, ... xn``, ``t0, tm``, where integration is carried out over ``x0, ... xn``, which must be floats. Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``. Integration is carried out in order. That is, integration over ``x0`` is the innermost integral, and ``xn`` is the outermost. If the user desires improved integration performance, then `f` may be a `scipy.LowLevelCallable` with one of the signatures:: double func(int n, double *xx) double func(int n, double *xx, void *user_data) where ``n`` is the number of extra parameters and args is an array of doubles of the additional parameters, the ``xx`` array contains the coordinates. The ``user_data`` is the data contained in the `scipy.LowLevelCallable`. ranges : iterable object Each element of ranges may be either a sequence of 2 numbers, or else a callable that returns such a sequence. ``ranges[0]`` corresponds to integration over x0, and so on. If an element of ranges is a callable, then it will be called with all of the integration arguments available, as well as any parametric arguments. e.g. if ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``. args : iterable object, optional Additional arguments ``t0, ..., tn``, required by `func`, `ranges`, and ``opts``. opts : iterable object or dict, optional Options to be passed to `quad`. May be empty, a dict, or a sequence of dicts or functions that return a dict. If empty, the default options from scipy.integrate.quad are used. If a dict, the same options are used for all levels of integraion. If a sequence, then each element of the sequence corresponds to a particular integration. e.g. opts[0] corresponds to integration over x0, and so on. If a callable, the signature must be the same as for ``ranges``. The available options together with their default values are: - epsabs = 1.49e-08 - epsrel = 1.49e-08 - limit = 50 - points = None - weight = None - wvar = None - wopts = None For more information on these options, see `quad` and `quad_explain`. full_output : bool, optional Partial implementation of ``full_output`` from scipy.integrate.quad. The number of integrand function evaluations ``neval`` can be obtained by setting ``full_output=True`` when calling nquad. Returns ------- result : float The result of the integration. abserr : float The maximum of the estimates of the absolute error in the various integration results. out_dict : dict, optional A dict containing additional information on the integration. See Also -------- quad : 1-dimensional numerical integration dblquad, tplquad : double and triple integrals fixed_quad : fixed-order Gaussian quadrature quadrature : adaptive Gaussian quadrature Examples -------- >>> from scipy import integrate >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + ( ... 1 if (x0-.2*x3-.5-.25*x1>0) else 0) >>> points = [[lambda x1,x2,x3 : 0.2*x3 + 0.5 + 0.25*x1], [], [], []] >>> def opts0(*args, **kwargs): ... return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]} >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]], ... opts=[opts0,{},{},{}], full_output=True) (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962}) >>> scale = .1 >>> def func2(x0, x1, x2, x3, t0, t1): ... return x0*x1*x3**2 + np.sin(x2) + 1 + (1 if x0+t1*x1-t0>0 else 0) >>> def lim0(x1, x2, x3, t0, t1): ... return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1, ... scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1] >>> def lim1(x2, x3, t0, t1): ... return [scale * (t0*x2 + t1*x3) - 1, ... scale * (t0*x2 + t1*x3) + 1] >>> def lim2(x3, t0, t1): ... return [scale * (x3 + t0**2*t1**3) - 1, ... scale * (x3 + t0**2*t1**3) + 1] >>> def lim3(t0, t1): ... return [scale * (t0+t1) - 1, scale * (t0+t1) + 1] >>> def opts0(x1, x2, x3, t0, t1): ... return {'points' : [t0 - t1*x1]} >>> def opts1(x2, x3, t0, t1): ... return {} >>> def opts2(x3, t0, t1): ... return {} >>> def opts3(t0, t1): ... return {} >>> integrate.nquad(func2, [lim0, lim1, lim2, lim3], args=(0,0), ... opts=[opts0, opts1, opts2, opts3]) (25.066666666666666, 2.7829590483937256e-13)
Integration over multiple variables.
[ "Integration", "over", "multiple", "variables", "." ]
def nquad(func, ranges, args=None, opts=None, full_output=False): """ Integration over multiple variables. Wraps `quad` to enable integration over multiple variables. Various options allow improved integration of discontinuous functions, as well as the use of weighted integration, and generally finer control of the integration process. Parameters ---------- func : {callable, scipy.LowLevelCallable} The function to be integrated. Has arguments of ``x0, ... xn``, ``t0, tm``, where integration is carried out over ``x0, ... xn``, which must be floats. Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``. Integration is carried out in order. That is, integration over ``x0`` is the innermost integral, and ``xn`` is the outermost. If the user desires improved integration performance, then `f` may be a `scipy.LowLevelCallable` with one of the signatures:: double func(int n, double *xx) double func(int n, double *xx, void *user_data) where ``n`` is the number of extra parameters and args is an array of doubles of the additional parameters, the ``xx`` array contains the coordinates. The ``user_data`` is the data contained in the `scipy.LowLevelCallable`. ranges : iterable object Each element of ranges may be either a sequence of 2 numbers, or else a callable that returns such a sequence. ``ranges[0]`` corresponds to integration over x0, and so on. If an element of ranges is a callable, then it will be called with all of the integration arguments available, as well as any parametric arguments. e.g. if ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``. args : iterable object, optional Additional arguments ``t0, ..., tn``, required by `func`, `ranges`, and ``opts``. opts : iterable object or dict, optional Options to be passed to `quad`. May be empty, a dict, or a sequence of dicts or functions that return a dict. If empty, the default options from scipy.integrate.quad are used. If a dict, the same options are used for all levels of integraion. If a sequence, then each element of the sequence corresponds to a particular integration. e.g. opts[0] corresponds to integration over x0, and so on. If a callable, the signature must be the same as for ``ranges``. The available options together with their default values are: - epsabs = 1.49e-08 - epsrel = 1.49e-08 - limit = 50 - points = None - weight = None - wvar = None - wopts = None For more information on these options, see `quad` and `quad_explain`. full_output : bool, optional Partial implementation of ``full_output`` from scipy.integrate.quad. The number of integrand function evaluations ``neval`` can be obtained by setting ``full_output=True`` when calling nquad. Returns ------- result : float The result of the integration. abserr : float The maximum of the estimates of the absolute error in the various integration results. out_dict : dict, optional A dict containing additional information on the integration. See Also -------- quad : 1-dimensional numerical integration dblquad, tplquad : double and triple integrals fixed_quad : fixed-order Gaussian quadrature quadrature : adaptive Gaussian quadrature Examples -------- >>> from scipy import integrate >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + ( ... 1 if (x0-.2*x3-.5-.25*x1>0) else 0) >>> points = [[lambda x1,x2,x3 : 0.2*x3 + 0.5 + 0.25*x1], [], [], []] >>> def opts0(*args, **kwargs): ... return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]} >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]], ... opts=[opts0,{},{},{}], full_output=True) (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962}) >>> scale = .1 >>> def func2(x0, x1, x2, x3, t0, t1): ... return x0*x1*x3**2 + np.sin(x2) + 1 + (1 if x0+t1*x1-t0>0 else 0) >>> def lim0(x1, x2, x3, t0, t1): ... return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1, ... scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1] >>> def lim1(x2, x3, t0, t1): ... return [scale * (t0*x2 + t1*x3) - 1, ... scale * (t0*x2 + t1*x3) + 1] >>> def lim2(x3, t0, t1): ... return [scale * (x3 + t0**2*t1**3) - 1, ... scale * (x3 + t0**2*t1**3) + 1] >>> def lim3(t0, t1): ... return [scale * (t0+t1) - 1, scale * (t0+t1) + 1] >>> def opts0(x1, x2, x3, t0, t1): ... return {'points' : [t0 - t1*x1]} >>> def opts1(x2, x3, t0, t1): ... return {} >>> def opts2(x3, t0, t1): ... return {} >>> def opts3(t0, t1): ... return {} >>> integrate.nquad(func2, [lim0, lim1, lim2, lim3], args=(0,0), ... opts=[opts0, opts1, opts2, opts3]) (25.066666666666666, 2.7829590483937256e-13) """ depth = len(ranges) ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges] if args is None: args = () if opts is None: opts = [dict([])] * depth if isinstance(opts, dict): opts = [_OptFunc(opts)] * depth else: opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts] return _NQuad(func, ranges, opts, full_output).integrate(*args)
[ "def", "nquad", "(", "func", ",", "ranges", ",", "args", "=", "None", ",", "opts", "=", "None", ",", "full_output", "=", "False", ")", ":", "depth", "=", "len", "(", "ranges", ")", "ranges", "=", "[", "rng", "if", "callable", "(", "rng", ")", "el...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/integrate/quadpack.py#L673-L805
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py
python
AttentionWrapper.state_size
(self)
return AttentionWrapperState( cell_state=self._cell.state_size, time=tensor_shape.TensorShape([]), attention=self._attention_layer_size, alignments=self._item_or_tuple( a.alignments_size for a in self._attention_mechanisms), attention_state=self._item_or_tuple( a.state_size for a in self._attention_mechanisms), alignment_history=self._item_or_tuple( a.alignments_size if self._alignment_history else () for a in self._attention_mechanisms))
The `state_size` property of `AttentionWrapper`. Returns: An `AttentionWrapperState` tuple containing shapes used by this object.
The `state_size` property of `AttentionWrapper`.
[ "The", "state_size", "property", "of", "AttentionWrapper", "." ]
def state_size(self): """The `state_size` property of `AttentionWrapper`. Returns: An `AttentionWrapperState` tuple containing shapes used by this object. """ return AttentionWrapperState( cell_state=self._cell.state_size, time=tensor_shape.TensorShape([]), attention=self._attention_layer_size, alignments=self._item_or_tuple( a.alignments_size for a in self._attention_mechanisms), attention_state=self._item_or_tuple( a.state_size for a in self._attention_mechanisms), alignment_history=self._item_or_tuple( a.alignments_size if self._alignment_history else () for a in self._attention_mechanisms))
[ "def", "state_size", "(", "self", ")", ":", "return", "AttentionWrapperState", "(", "cell_state", "=", "self", ".", "_cell", ".", "state_size", ",", "time", "=", "tensor_shape", ".", "TensorShape", "(", "[", "]", ")", ",", "attention", "=", "self", ".", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py#L2371-L2387
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
validateName
(value, space)
return ret
Check that a value conforms to the lexical space of Name
Check that a value conforms to the lexical space of Name
[ "Check", "that", "a", "value", "conforms", "to", "the", "lexical", "space", "of", "Name" ]
def validateName(value, space): """Check that a value conforms to the lexical space of Name """ ret = libxml2mod.xmlValidateName(value, space) return ret
[ "def", "validateName", "(", "value", ",", "space", ")", ":", "ret", "=", "libxml2mod", ".", "xmlValidateName", "(", "value", ",", "space", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L1726-L1729
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py
python
CompletionState.go_to_index
(self, index: Optional[int])
Create a new :class:`.CompletionState` object with the new index. When `index` is `None` deselect the completion.
Create a new :class:`.CompletionState` object with the new index.
[ "Create", "a", "new", ":", "class", ":", ".", "CompletionState", "object", "with", "the", "new", "index", "." ]
def go_to_index(self, index: Optional[int]) -> None: """ Create a new :class:`.CompletionState` object with the new index. When `index` is `None` deselect the completion. """ if self.completions: assert index is None or 0 <= index < len(self.completions) self.complete_index = index
[ "def", "go_to_index", "(", "self", ",", "index", ":", "Optional", "[", "int", "]", ")", "->", "None", ":", "if", "self", ".", "completions", ":", "assert", "index", "is", "None", "or", "0", "<=", "index", "<", "len", "(", "self", ".", "completions", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py#L105-L113
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py
python
domain_match
(A, B)
return True
Return True if domain A domain-matches domain B, according to RFC 2965. A and B may be host domain names or IP addresses. RFC 2965, section 1: Host names can be specified either as an IP address or a HDN string. Sometimes we compare one host name with another. (Such comparisons SHALL be case-insensitive.) Host A's name domain-matches host B's if * their host name strings string-compare equal; or * A is a HDN string and has the form NB, where N is a non-empty name string, B has the form .B', and B' is a HDN string. (So, x.y.com domain-matches .Y.com but not Y.com.) Note that domain-match is not a commutative operation: a.b.c.com domain-matches .c.com, but not the reverse.
Return True if domain A domain-matches domain B, according to RFC 2965.
[ "Return", "True", "if", "domain", "A", "domain", "-", "matches", "domain", "B", "according", "to", "RFC", "2965", "." ]
def domain_match(A, B): """Return True if domain A domain-matches domain B, according to RFC 2965. A and B may be host domain names or IP addresses. RFC 2965, section 1: Host names can be specified either as an IP address or a HDN string. Sometimes we compare one host name with another. (Such comparisons SHALL be case-insensitive.) Host A's name domain-matches host B's if * their host name strings string-compare equal; or * A is a HDN string and has the form NB, where N is a non-empty name string, B has the form .B', and B' is a HDN string. (So, x.y.com domain-matches .Y.com but not Y.com.) Note that domain-match is not a commutative operation: a.b.c.com domain-matches .c.com, but not the reverse. """ # Note that, if A or B are IP addresses, the only relevant part of the # definition of the domain-match algorithm is the direct string-compare. A = A.lower() B = B.lower() if A == B: return True if not is_HDN(A): return False i = A.rfind(B) if i == -1 or i == 0: # A does not have form NB, or N is the empty string return False if not B.startswith("."): return False if not is_HDN(B[1:]): return False return True
[ "def", "domain_match", "(", "A", ",", "B", ")", ":", "# Note that, if A or B are IP addresses, the only relevant part of the", "# definition of the domain-match algorithm is the direct string-compare.", "A", "=", "A", ".", "lower", "(", ")", "B", "=", "B", ".", "lower", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py#L542-L579
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/rnn.py
python
BeamSearchDecoder.__init__
(self, cell, start_token, end_token, beam_size, embedding_fn=None, output_fn=None)
Constructor of BeamSearchDecoder. Parameters: cell(RNNCellBase): An instance of `RNNCellBase` or object with the same interface. start_token(int): The start token id. end_token(int): The end token id. beam_size(int): The beam width used in beam search. embedding_fn(optional): A callable to apply to selected candidate ids. Mostly it is an embedding layer to transform ids to embeddings, and the returned value acts as the `input` argument for `cell.call`. If not provided, the id to embedding transformation must be built into `cell.call`. Default None. output_fn(optional): A callable to apply to the cell's output prior to calculate scores and select candidate token ids. Default None.
Constructor of BeamSearchDecoder.
[ "Constructor", "of", "BeamSearchDecoder", "." ]
def __init__(self, cell, start_token, end_token, beam_size, embedding_fn=None, output_fn=None): """ Constructor of BeamSearchDecoder. Parameters: cell(RNNCellBase): An instance of `RNNCellBase` or object with the same interface. start_token(int): The start token id. end_token(int): The end token id. beam_size(int): The beam width used in beam search. embedding_fn(optional): A callable to apply to selected candidate ids. Mostly it is an embedding layer to transform ids to embeddings, and the returned value acts as the `input` argument for `cell.call`. If not provided, the id to embedding transformation must be built into `cell.call`. Default None. output_fn(optional): A callable to apply to the cell's output prior to calculate scores and select candidate token ids. Default None. """ self.cell = cell self.embedding_fn = embedding_fn self.output_fn = output_fn self.start_token = start_token self.end_token = end_token self.beam_size = beam_size
[ "def", "__init__", "(", "self", ",", "cell", ",", "start_token", ",", "end_token", ",", "beam_size", ",", "embedding_fn", "=", "None", ",", "output_fn", "=", "None", ")", ":", "self", ".", "cell", "=", "cell", "self", ".", "embedding_fn", "=", "embedding...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/rnn.py#L907-L935
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/python_gflags/gflags2man.py
python
ProgramInfo.__init__
(self, executable)
Create object with executable. Args: executable Program to execute (string)
Create object with executable. Args: executable Program to execute (string)
[ "Create", "object", "with", "executable", ".", "Args", ":", "executable", "Program", "to", "execute", "(", "string", ")" ]
def __init__(self, executable): """Create object with executable. Args: executable Program to execute (string) """ self.long_name = executable self.name = os.path.basename(executable) # name # Get name without extension (PAR files) (self.short_name, self.ext) = os.path.splitext(self.name) self.executable = GetRealPath(executable) # name of the program self.output = [] # output from the program. List of lines. self.desc = [] # top level description. List of lines self.modules = {} # { section_name(string), [ flags ] } self.module_list = [] # list of module names in their original order self.date = time.localtime(time.time())
[ "def", "__init__", "(", "self", ",", "executable", ")", ":", "self", ".", "long_name", "=", "executable", "self", ".", "name", "=", "os", ".", "path", ".", "basename", "(", "executable", ")", "# name", "# Get name without extension (PAR files)", "(", "self", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags2man.py#L169-L183
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/urlhandler/protocol_loop.py
python
Serial._update_dtr_state
(self)
Set terminal status line: Data Terminal Ready
Set terminal status line: Data Terminal Ready
[ "Set", "terminal", "status", "line", ":", "Data", "Terminal", "Ready" ]
def _update_dtr_state(self): """Set terminal status line: Data Terminal Ready""" if self.logger: self.logger.info('_update_dtr_state({!r}) -> state of DSR'.format(self._dtr_state))
[ "def", "_update_dtr_state", "(", "self", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'_update_dtr_state({!r}) -> state of DSR'", ".", "format", "(", "self", ".", "_dtr_state", ")", ")" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/urlhandler/protocol_loop.py#L241-L244
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TNGraph.AddNode
(self, *args)
return _snap.TNGraph_AddNode(self, *args)
AddNode(TNGraph self, int NId=-1) -> int Parameters: NId: int AddNode(TNGraph self) -> int AddNode(TNGraph self, TNGraph::TNodeI const & NodeId) -> int Parameters: NodeId: TNGraph::TNodeI const & AddNode(TNGraph self, int const & NId, TIntV InNIdV, TIntV OutNIdV) -> int Parameters: NId: int const & InNIdV: TIntV const & OutNIdV: TIntV const & AddNode(TNGraph self, int const & NId, TVecPool< TInt > const & Pool, int const & SrcVId, int const & DstVId) -> int Parameters: NId: int const & Pool: TVecPool< TInt > const & SrcVId: int const & DstVId: int const &
AddNode(TNGraph self, int NId=-1) -> int
[ "AddNode", "(", "TNGraph", "self", "int", "NId", "=", "-", "1", ")", "-", ">", "int" ]
def AddNode(self, *args): """ AddNode(TNGraph self, int NId=-1) -> int Parameters: NId: int AddNode(TNGraph self) -> int AddNode(TNGraph self, TNGraph::TNodeI const & NodeId) -> int Parameters: NodeId: TNGraph::TNodeI const & AddNode(TNGraph self, int const & NId, TIntV InNIdV, TIntV OutNIdV) -> int Parameters: NId: int const & InNIdV: TIntV const & OutNIdV: TIntV const & AddNode(TNGraph self, int const & NId, TVecPool< TInt > const & Pool, int const & SrcVId, int const & DstVId) -> int Parameters: NId: int const & Pool: TVecPool< TInt > const & SrcVId: int const & DstVId: int const & """ return _snap.TNGraph_AddNode(self, *args)
[ "def", "AddNode", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TNGraph_AddNode", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L3928-L3957
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/detection.py
python
detection_map
(detect_res, label, class_num, background_label=0, overlap_threshold=0.3, evaluate_difficult=True, has_state=None, input_states=None, out_states=None, ap_version='integral')
return map_out
${comment} Args: detect_res: ${detect_res_comment} label: ${label_comment} class_num: ${class_num_comment} background_label: ${background_label_comment} overlap_threshold: ${overlap_threshold_comment} evaluate_difficult: ${evaluate_difficult_comment} has_state: ${has_state_comment} input_states: (tuple|None) If not None, It contains 3 elements: (1) pos_count ${pos_count_comment}. (2) true_pos ${true_pos_comment}. (3) false_pos ${false_pos_comment}. out_states: (tuple|None) If not None, it contains 3 elements. (1) accum_pos_count ${accum_pos_count_comment}. (2) accum_true_pos ${accum_true_pos_comment}. (3) accum_false_pos ${accum_false_pos_comment}. ap_version: ${ap_type_comment} Returns: ${map_comment} Examples: .. code-block:: python import paddle.fluid as fluid from fluid.layers import detection detect_res = fluid.data( name='detect_res', shape=[10, 6], dtype='float32') label = fluid.data( name='label', shape=[10, 6], dtype='float32') map_out = detection.detection_map(detect_res, label, 21)
${comment}
[ "$", "{", "comment", "}" ]
def detection_map(detect_res, label, class_num, background_label=0, overlap_threshold=0.3, evaluate_difficult=True, has_state=None, input_states=None, out_states=None, ap_version='integral'): """ ${comment} Args: detect_res: ${detect_res_comment} label: ${label_comment} class_num: ${class_num_comment} background_label: ${background_label_comment} overlap_threshold: ${overlap_threshold_comment} evaluate_difficult: ${evaluate_difficult_comment} has_state: ${has_state_comment} input_states: (tuple|None) If not None, It contains 3 elements: (1) pos_count ${pos_count_comment}. (2) true_pos ${true_pos_comment}. (3) false_pos ${false_pos_comment}. out_states: (tuple|None) If not None, it contains 3 elements. (1) accum_pos_count ${accum_pos_count_comment}. (2) accum_true_pos ${accum_true_pos_comment}. (3) accum_false_pos ${accum_false_pos_comment}. ap_version: ${ap_type_comment} Returns: ${map_comment} Examples: .. code-block:: python import paddle.fluid as fluid from fluid.layers import detection detect_res = fluid.data( name='detect_res', shape=[10, 6], dtype='float32') label = fluid.data( name='label', shape=[10, 6], dtype='float32') map_out = detection.detection_map(detect_res, label, 21) """ helper = LayerHelper("detection_map", **locals()) def __create_var(type): return helper.create_variable_for_type_inference(dtype=type) map_out = __create_var('float32') accum_pos_count_out = out_states[ 0] if out_states is not None else __create_var('int32') accum_true_pos_out = out_states[ 1] if out_states is not None else __create_var('float32') accum_false_pos_out = out_states[ 2] if out_states is not None else __create_var('float32') pos_count = input_states[0] if input_states is not None else None true_pos = input_states[1] if input_states is not None else None false_pos = input_states[2] if input_states is not None else None helper.append_op( type="detection_map", inputs={ 'Label': label, 'DetectRes': detect_res, 'HasState': has_state, 'PosCount': pos_count, 'TruePos': true_pos, 'FalsePos': false_pos }, outputs={ 'MAP': map_out, 'AccumPosCount': accum_pos_count_out, 'AccumTruePos': accum_true_pos_out, 'AccumFalsePos': accum_false_pos_out }, attrs={ 'overlap_threshold': overlap_threshold, 'evaluate_difficult': evaluate_difficult, 'ap_type': ap_version, 'class_num': class_num, }) return map_out
[ "def", "detection_map", "(", "detect_res", ",", "label", ",", "class_num", ",", "background_label", "=", "0", ",", "overlap_threshold", "=", "0.3", ",", "evaluate_difficult", "=", "True", ",", "has_state", "=", "None", ",", "input_states", "=", "None", ",", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/detection.py#L1231-L1321
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/_pyio.py
python
open
(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
return text
r"""Open file and return a stream. Raise IOError upon failure. file is either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.) mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (for backwards compatibility; unneeded for new code) ========= =============================================================== The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation. Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode (appending 'b' to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given. buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`. On many systems, the buffer will typically be 4096 or 8192 bytes long. * "Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files. encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings. errors is an optional string that specifies how encoding errors are to be handled---this argument should not be used in binary mode. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register for a list of the permitted encoding error strings. newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case. open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom. It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode.
r"""Open file and return a stream. Raise IOError upon failure.
[ "r", "Open", "file", "and", "return", "a", "stream", ".", "Raise", "IOError", "upon", "failure", "." ]
def open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True): r"""Open file and return a stream. Raise IOError upon failure. file is either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.) mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (for backwards compatibility; unneeded for new code) ========= =============================================================== The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation. Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode (appending 'b' to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given. buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`. On many systems, the buffer will typically be 4096 or 8192 bytes long. * "Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files. encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings. errors is an optional string that specifies how encoding errors are to be handled---this argument should not be used in binary mode. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register for a list of the permitted encoding error strings. newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case. open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom. It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode. """ if not isinstance(file, (basestring, int, long)): raise TypeError("invalid file: %r" % file) if not isinstance(mode, basestring): raise TypeError("invalid mode: %r" % mode) if not isinstance(buffering, (int, long)): raise TypeError("invalid buffering: %r" % buffering) if encoding is not None and not isinstance(encoding, basestring): raise TypeError("invalid encoding: %r" % encoding) if errors is not None and not isinstance(errors, basestring): raise TypeError("invalid errors: %r" % errors) modes = set(mode) if modes - set("arwb+tU") or len(mode) > len(modes): raise ValueError("invalid mode: %r" % mode) reading = "r" in modes writing = "w" in modes appending = "a" in modes updating = "+" in modes text = "t" in modes binary = "b" in modes if "U" in modes: if writing or appending: raise ValueError("can't use U and writing mode at once") reading = True if text and binary: raise ValueError("can't have text and binary mode at once") if reading + writing + appending > 1: raise ValueError("can't have read/write/append mode at once") if not (reading or writing or appending): raise ValueError("must have exactly one of read/write/append mode") if binary and encoding is not None: raise ValueError("binary mode doesn't take an encoding argument") if binary and errors is not None: raise ValueError("binary mode doesn't take an errors argument") if binary and newline is not None: raise ValueError("binary mode doesn't take a newline argument") raw = FileIO(file, (reading and "r" or "") + (writing and "w" or "") + (appending and "a" or "") + (updating and "+" or ""), closefd) line_buffering = False if buffering == 1 or buffering < 0 and raw.isatty(): buffering = -1 line_buffering = True if buffering < 0: buffering = DEFAULT_BUFFER_SIZE try: bs = os.fstat(raw.fileno()).st_blksize except (os.error, AttributeError): pass else: if bs > 1: buffering = bs if buffering < 0: raise ValueError("invalid buffering size") if buffering == 0: if binary: return raw raise ValueError("can't have unbuffered text I/O") if updating: buffer = BufferedRandom(raw, buffering) elif writing or appending: buffer = BufferedWriter(raw, buffering) elif reading: buffer = BufferedReader(raw, buffering) else: raise ValueError("unknown mode: %r" % mode) if binary: return buffer text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering) text.mode = mode return text
[ "def", "open", "(", "file", ",", "mode", "=", "\"r\"", ",", "buffering", "=", "-", "1", ",", "encoding", "=", "None", ",", "errors", "=", "None", ",", "newline", "=", "None", ",", "closefd", "=", "True", ")", ":", "if", "not", "isinstance", "(", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/_pyio.py#L43-L226
networkit/networkit
695b7a786a894a303fa8587597d5ef916e797729
networkit/profiling/multiprocessing_helper.py
python
ThreadPool.__init__
(self, numberOfWorkers, isParallel=True)
constructor Args: numberOfWorkers: number of workers to create isParallel: parallel or sequential task computation
constructor Args: numberOfWorkers: number of workers to create isParallel: parallel or sequential task computation
[ "constructor", "Args", ":", "numberOfWorkers", ":", "number", "of", "workers", "to", "create", "isParallel", ":", "parallel", "or", "sequential", "task", "computation" ]
def __init__(self, numberOfWorkers, isParallel=True): """ constructor Args: numberOfWorkers: number of workers to create isParallel: parallel or sequential task computation """ self.__numberOfTasks = 0 self.__numberOfWorkers = numberOfWorkers self.__isParallel = isParallel if self.__numberOfWorkers < 1: self.__numberOfWorkers = 0 self.__isParallel = False if self.__isParallel: self.__tasks = multiprocessing.JoinableQueue() self.__results = multiprocessing.Queue() self.__workers = [Worker(self.__tasks, self.__results) for i in range(self.__numberOfWorkers)] count = 0 for w in self.__workers: w.deamon = True try: w.start() count += 1 except Exception as e: self.__numberOfWorkers = count if count < 1: self.__tasks.close() self.__results.close() self.__isParallel = False self.__tasks = None self.__results = None self.__workers = None print(e) break if not self.__isParallel: self.__tasks = deque()
[ "def", "__init__", "(", "self", ",", "numberOfWorkers", ",", "isParallel", "=", "True", ")", ":", "self", ".", "__numberOfTasks", "=", "0", "self", ".", "__numberOfWorkers", "=", "numberOfWorkers", "self", ".", "__isParallel", "=", "isParallel", "if", "self", ...
https://github.com/networkit/networkit/blob/695b7a786a894a303fa8587597d5ef916e797729/networkit/profiling/multiprocessing_helper.py#L73-L107
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ListCtrl.Focus
(self, idx)
Focus and show the given item
Focus and show the given item
[ "Focus", "and", "show", "the", "given", "item" ]
def Focus(self, idx): '''Focus and show the given item''' self.SetItemState(idx, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED) self.EnsureVisible(idx)
[ "def", "Focus", "(", "self", ",", "idx", ")", ":", "self", ".", "SetItemState", "(", "idx", ",", "wx", ".", "LIST_STATE_FOCUSED", ",", "wx", ".", "LIST_STATE_FOCUSED", ")", "self", ".", "EnsureVisible", "(", "idx", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4768-L4771
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSProject.py
python
Writer.AddFileConfig
(self, path, config, attrs=None, tools=None)
Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles().
Adds a configuration to a file.
[ "Adds", "a", "configuration", "to", "a", "file", "." ]
def AddFileConfig(self, path, config, attrs=None, tools=None): """Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles(). """ # Find the file node with the right relative path parent = self.files_dict.get(path) if not parent: raise ValueError('AddFileConfig: file "%s" not in project.' % path) # Add the config to the file node spec = self._GetSpecForConfiguration('FileConfiguration', config, attrs, tools) parent.append(spec)
[ "def", "AddFileConfig", "(", "self", ",", "path", ",", "config", ",", "attrs", "=", "None", ",", "tools", "=", "None", ")", ":", "# Find the file node with the right relative path", "parent", "=", "self", ".", "files_dict", ".", "get", "(", "path", ")", "if"...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSProject.py#L166-L186
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
CommandBit.parsetext
(self, pos)
return bracket
Parse a text parameter.
Parse a text parameter.
[ "Parse", "a", "text", "parameter", "." ]
def parsetext(self, pos): "Parse a text parameter." self.factory.clearskipped(pos) if not self.factory.detecttype(Bracket, pos): Trace.error('No text parameter for ' + self.command) return None bracket = Bracket().setfactory(self.factory).parsetext(pos) self.add(bracket) return bracket
[ "def", "parsetext", "(", "self", ",", "pos", ")", ":", "self", ".", "factory", ".", "clearskipped", "(", "pos", ")", "if", "not", "self", ".", "factory", ".", "detecttype", "(", "Bracket", ",", "pos", ")", ":", "Trace", ".", "error", "(", "'No text p...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4177-L4185
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/mox.py
python
MockAnything.__getattr__
(self, method_name)
return self._CreateMockMethod(method_name)
Intercept method calls on this object. A new MockMethod is returned that is aware of the MockAnything's state (record or replay). The call will be recorded or replayed by the MockMethod's __call__. Args: # method name: the name of the method being called. method_name: str Returns: A new MockMethod aware of MockAnything's state (record or replay).
Intercept method calls on this object.
[ "Intercept", "method", "calls", "on", "this", "object", "." ]
def __getattr__(self, method_name): """Intercept method calls on this object. A new MockMethod is returned that is aware of the MockAnything's state (record or replay). The call will be recorded or replayed by the MockMethod's __call__. Args: # method name: the name of the method being called. method_name: str Returns: A new MockMethod aware of MockAnything's state (record or replay). """ return self._CreateMockMethod(method_name)
[ "def", "__getattr__", "(", "self", ",", "method_name", ")", ":", "return", "self", ".", "_CreateMockMethod", "(", "method_name", ")" ]
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/mox.py#L278-L293
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
examples/faster-rcnn/lib/fast_rcnn/train.py
python
get_training_roidb
(imdb)
return imdb.roidb
Returns a roidb (Region of Interest database) for use in training.
Returns a roidb (Region of Interest database) for use in training.
[ "Returns", "a", "roidb", "(", "Region", "of", "Interest", "database", ")", "for", "use", "in", "training", "." ]
def get_training_roidb(imdb): """Returns a roidb (Region of Interest database) for use in training.""" if cfg.TRAIN.USE_FLIPPED: print 'Appending horizontally-flipped training examples...' imdb.append_flipped_images() print 'done' print 'Preparing training data...' rdl_roidb.prepare_roidb(imdb) print 'done' return imdb.roidb
[ "def", "get_training_roidb", "(", "imdb", ")", ":", "if", "cfg", ".", "TRAIN", ".", "USE_FLIPPED", ":", "print", "'Appending horizontally-flipped training examples...'", "imdb", ".", "append_flipped_images", "(", ")", "print", "'done'", "print", "'Preparing training dat...
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/faster-rcnn/lib/fast_rcnn/train.py#L115-L126
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/framework/python/framework/tensor_util.py
python
is_tensor
(x)
return isinstance(x, tensor_types)
Check for tensor types. Check whether an object is a tensor. Equivalent to `isinstance(x, [tf.Tensor, tf.SparseTensor, tf.Variable])`. Args: x: An python object to check. Returns: `True` if `x` is a tensor, `False` if not.
Check for tensor types. Check whether an object is a tensor. Equivalent to `isinstance(x, [tf.Tensor, tf.SparseTensor, tf.Variable])`.
[ "Check", "for", "tensor", "types", ".", "Check", "whether", "an", "object", "is", "a", "tensor", ".", "Equivalent", "to", "isinstance", "(", "x", "[", "tf", ".", "Tensor", "tf", ".", "SparseTensor", "tf", ".", "Variable", "]", ")", "." ]
def is_tensor(x): """Check for tensor types. Check whether an object is a tensor. Equivalent to `isinstance(x, [tf.Tensor, tf.SparseTensor, tf.Variable])`. Args: x: An python object to check. Returns: `True` if `x` is a tensor, `False` if not. """ tensor_types = (ops.Tensor, ops.SparseTensor, variables.Variable) return isinstance(x, tensor_types)
[ "def", "is_tensor", "(", "x", ")", ":", "tensor_types", "=", "(", "ops", ".", "Tensor", ",", "ops", ".", "SparseTensor", ",", "variables", ".", "Variable", ")", "return", "isinstance", "(", "x", ",", "tensor_types", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/framework/python/framework/tensor_util.py#L219-L231
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/mac_tool.py
python
MacTool.ExecMergeInfoPlist
(self, output, *inputs)
Merge multiple .plist files into a single .plist file.
Merge multiple .plist files into a single .plist file.
[ "Merge", "multiple", ".", "plist", "files", "into", "a", "single", ".", "plist", "file", "." ]
def ExecMergeInfoPlist(self, output, *inputs): """Merge multiple .plist files into a single .plist file.""" merged_plist = {} for path in inputs: plist = self._LoadPlistMaybeBinary(path) self._MergePlist(merged_plist, plist) plistlib.writePlist(merged_plist, output)
[ "def", "ExecMergeInfoPlist", "(", "self", ",", "output", ",", "*", "inputs", ")", ":", "merged_plist", "=", "{", "}", "for", "path", "in", "inputs", ":", "plist", "=", "self", ".", "_LoadPlistMaybeBinary", "(", "path", ")", "self", ".", "_MergePlist", "(...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/mac_tool.py#L403-L409
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/loaders.py
python
create_loader
(search_path_string=None)
return Loader(extra_search_paths=paths)
Create a Loader class. This factory function creates a loader given a search string path. :type search_string_path: str :param search_string_path: The AWS_DATA_PATH value. A string of data path values separated by the ``os.path.pathsep`` value, which is typically ``:`` on POSIX platforms and ``;`` on windows. :return: A ``Loader`` instance.
Create a Loader class.
[ "Create", "a", "Loader", "class", "." ]
def create_loader(search_path_string=None): """Create a Loader class. This factory function creates a loader given a search string path. :type search_string_path: str :param search_string_path: The AWS_DATA_PATH value. A string of data path values separated by the ``os.path.pathsep`` value, which is typically ``:`` on POSIX platforms and ``;`` on windows. :return: A ``Loader`` instance. """ if search_path_string is None: return Loader() paths = [] extra_paths = search_path_string.split(os.pathsep) for path in extra_paths: path = os.path.expanduser(os.path.expandvars(path)) paths.append(path) return Loader(extra_search_paths=paths)
[ "def", "create_loader", "(", "search_path_string", "=", "None", ")", ":", "if", "search_path_string", "is", "None", ":", "return", "Loader", "(", ")", "paths", "=", "[", "]", "extra_paths", "=", "search_path_string", ".", "split", "(", "os", ".", "pathsep", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/loaders.py#L178-L199
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/slim/python/slim/data/parallel_reader.py
python
ParallelReader.num_records_produced
(self, name=None)
return math_ops.add_n(num_records, name=name)
Returns the number of records this reader has produced. Args: name: A name for the operation (optional). Returns: An int64 Tensor.
Returns the number of records this reader has produced.
[ "Returns", "the", "number", "of", "records", "this", "reader", "has", "produced", "." ]
def num_records_produced(self, name=None): """Returns the number of records this reader has produced. Args: name: A name for the operation (optional). Returns: An int64 Tensor. """ num_records = [r.num_records_produced() for r in self._readers] return math_ops.add_n(num_records, name=name)
[ "def", "num_records_produced", "(", "self", ",", "name", "=", "None", ")", ":", "num_records", "=", "[", "r", ".", "num_records_produced", "(", ")", "for", "r", "in", "self", ".", "_readers", "]", "return", "math_ops", ".", "add_n", "(", "num_records", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/slim/python/slim/data/parallel_reader.py#L139-L150
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Modules/Scripted/Endoscopy/Endoscopy.py
python
EndoscopyWidget.enableOrDisableCreateButton
(self)
Connected to both the fiducial and camera node selector. It allows to enable or disable the 'create path' button.
Connected to both the fiducial and camera node selector. It allows to enable or disable the 'create path' button.
[ "Connected", "to", "both", "the", "fiducial", "and", "camera", "node", "selector", ".", "It", "allows", "to", "enable", "or", "disable", "the", "create", "path", "button", "." ]
def enableOrDisableCreateButton(self): """Connected to both the fiducial and camera node selector. It allows to enable or disable the 'create path' button.""" self.createPathButton.enabled = (self.cameraNodeSelector.currentNode() is not None and self.inputFiducialsNodeSelector.currentNode() is not None and self.outputPathNodeSelector.currentNode() is not None)
[ "def", "enableOrDisableCreateButton", "(", "self", ")", ":", "self", ".", "createPathButton", ".", "enabled", "=", "(", "self", ".", "cameraNodeSelector", ".", "currentNode", "(", ")", "is", "not", "None", "and", "self", ".", "inputFiducialsNodeSelector", ".", ...
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/Endoscopy/Endoscopy.py#L219-L224
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FocusHandler.SetMenu
(self, menu)
Sets the listener menu. :param `menu`: an instance of :class:`FlatMenu`.
Sets the listener menu.
[ "Sets", "the", "listener", "menu", "." ]
def SetMenu(self, menu): """ Sets the listener menu. :param `menu`: an instance of :class:`FlatMenu`. """ self._menu = menu
[ "def", "SetMenu", "(", "self", ",", "menu", ")", ":", "self", ".", "_menu", "=", "menu" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L7274-L7281
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/filter_design.py
python
_validate_sos
(sos)
return sos, n_sections
Helper to validate a SOS input
Helper to validate a SOS input
[ "Helper", "to", "validate", "a", "SOS", "input" ]
def _validate_sos(sos): """Helper to validate a SOS input""" sos = np.atleast_2d(sos) if sos.ndim != 2: raise ValueError('sos array must be 2D') n_sections, m = sos.shape if m != 6: raise ValueError('sos array must be shape (n_sections, 6)') if not (sos[:, 3] == 1).all(): raise ValueError('sos[:, 3] should be all ones') return sos, n_sections
[ "def", "_validate_sos", "(", "sos", ")", ":", "sos", "=", "np", ".", "atleast_2d", "(", "sos", ")", "if", "sos", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'sos array must be 2D'", ")", "n_sections", ",", "m", "=", "sos", ".", "shape", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/filter_design.py#L696-L706
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/upload.py
python
UploadSubmissionTask._submit
(self, client, config, osutil, request_executor, transfer_future, bandwidth_limiter=None)
:param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for
:param client: The client associated with the transfer manager
[ ":", "param", "client", ":", "The", "client", "associated", "with", "the", "transfer", "manager" ]
def _submit(self, client, config, osutil, request_executor, transfer_future, bandwidth_limiter=None): """ :param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for """ upload_input_manager = self._get_upload_input_manager_cls( transfer_future)( osutil, self._transfer_coordinator, bandwidth_limiter) # Determine the size if it was not provided if transfer_future.meta.size is None: upload_input_manager.provide_transfer_size(transfer_future) # Do a multipart upload if needed, otherwise do a regular put object. if not upload_input_manager.requires_multipart_upload( transfer_future, config): self._submit_upload_request( client, config, osutil, request_executor, transfer_future, upload_input_manager) else: self._submit_multipart_request( client, config, osutil, request_executor, transfer_future, upload_input_manager)
[ "def", "_submit", "(", "self", ",", "client", ",", "config", ",", "osutil", ",", "request_executor", ",", "transfer_future", ",", "bandwidth_limiter", "=", "None", ")", ":", "upload_input_manager", "=", "self", ".", "_get_upload_input_manager_cls", "(", "transfer_...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/upload.py#L523-L560
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/affiliate.py
python
Affiliate.timestamp
(self, timestamp)
Sets the timestamp of this Affiliate. :param timestamp: The timestamp of this Affiliate. # noqa: E501 :type: datetime
Sets the timestamp of this Affiliate.
[ "Sets", "the", "timestamp", "of", "this", "Affiliate", "." ]
def timestamp(self, timestamp): """Sets the timestamp of this Affiliate. :param timestamp: The timestamp of this Affiliate. # noqa: E501 :type: datetime """ self._timestamp = timestamp
[ "def", "timestamp", "(", "self", ",", "timestamp", ")", ":", "self", ".", "_timestamp", "=", "timestamp" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/affiliate.py#L416-L424
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/cpplint.py
python
IsDecltype
(clean_lines, linenum, column)
return False
Check if the token ending on (linenum, column) is decltype(). Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is decltype() expression, False otherwise.
Check if the token ending on (linenum, column) is decltype().
[ "Check", "if", "the", "token", "ending", "on", "(", "linenum", "column", ")", "is", "decltype", "()", "." ]
def IsDecltype(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is decltype(). Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is decltype() expression, False otherwise. """ (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) if start_col < 0: return False if Search(r'\bdecltype\s*$', text[0:start_col]): return True return False
[ "def", "IsDecltype", "(", "clean_lines", ",", "linenum", ",", "column", ")", ":", "(", "text", ",", "_", ",", "start_col", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "column", ")", "if", "start_col", "<", "0", ":", "retu...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/cpplint.py#L3393-L3408
tinyobjloader/tinyobjloader
8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93
deps/cpplint.py
python
NestingState.InTemplateArgumentList
(self, clean_lines, linenum, pos)
return False
Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments.
Check if current position is inside template argument list.
[ "Check", "if", "current", "position", "is", "inside", "template", "argument", "list", "." ]
def InTemplateArgumentList(self, clean_lines, linenum, pos): """Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments. """ while linenum < clean_lines.NumLines(): # Find the earliest character that might indicate a template argument line = clean_lines.elided[linenum] match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) if not match: linenum += 1 pos = 0 continue token = match.group(1) pos += len(match.group(0)) # These things do not look like template argument list: # class Suspect { # class Suspect x; } if token in ('{', '}', ';'): return False # These things look like template argument list: # template <class Suspect> # template <class Suspect = default_value> # template <class Suspect[]> # template <class Suspect...> if token in ('>', '=', '[', ']', '.'): return True # Check if token is an unmatched '<'. # If not, move on to the next character. if token != '<': pos += 1 if pos >= len(line): linenum += 1 pos = 0 continue # We can't be sure if we just find a single '<', and need to # find the matching '>'. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) if end_pos < 0: # Not sure if template argument list or syntax error in file return False linenum = end_line pos = end_pos return False
[ "def", "InTemplateArgumentList", "(", "self", ",", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "while", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "# Find the earliest character that might indicate a template argument", "line", "=", "clean...
https://github.com/tinyobjloader/tinyobjloader/blob/8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93/deps/cpplint.py#L2266-L2316
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/message.py
python
Message.ListFields
(self)
Returns a list of (FieldDescriptor, value) tuples for present fields. A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number. Returns: list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type.
Returns a list of (FieldDescriptor, value) tuples for present fields.
[ "Returns", "a", "list", "of", "(", "FieldDescriptor", "value", ")", "tuples", "for", "present", "fields", "." ]
def ListFields(self): """Returns a list of (FieldDescriptor, value) tuples for present fields. A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number. Returns: list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type. """ raise NotImplementedError
[ "def", "ListFields", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/message.py#L248-L261
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
python
_AddSerializePartialToStringMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddSerializePartialToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializePartialToString(self): out = BytesIO() self._InternalSerialize(out.write) return out.getvalue() cls.SerializePartialToString = SerializePartialToString def InternalSerialize(self, write_bytes): for field_descriptor, field_value in self.ListFields(): field_descriptor._encoder(write_bytes, field_value) for tag_bytes, value_bytes in self._unknown_fields: write_bytes(tag_bytes) write_bytes(value_bytes) cls._InternalSerialize = InternalSerialize
[ "def", "_AddSerializePartialToStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "SerializePartialToString", "(", "self", ")", ":", "out", "=", "BytesIO", "(", ")", "self", ".", "_InternalSerialize", "(", "out", ".", "write", ")", "return", ...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1040-L1055
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMS_AES_SYM_DETAILS.__init__
(self)
Custom data structure representing an empty element (i.e. the one with no data to marshal) for selector algorithm TPM_ALG_AES for the union TPMU_SYM_DETAILS
Custom data structure representing an empty element (i.e. the one with no data to marshal) for selector algorithm TPM_ALG_AES for the union TPMU_SYM_DETAILS
[ "Custom", "data", "structure", "representing", "an", "empty", "element", "(", "i", ".", "e", ".", "the", "one", "with", "no", "data", "to", "marshal", ")", "for", "selector", "algorithm", "TPM_ALG_AES", "for", "the", "union", "TPMU_SYM_DETAILS" ]
def __init__(self): """ Custom data structure representing an empty element (i.e. the one with no data to marshal) for selector algorithm TPM_ALG_AES for the union TPMU_SYM_DETAILS """ pass
[ "def", "__init__", "(", "self", ")", ":", "pass" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L5628-L5634
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBAttachInfo.GetResumeCount
(self)
return _lldb.SBAttachInfo_GetResumeCount(self)
GetResumeCount(SBAttachInfo self) -> uint32_t
GetResumeCount(SBAttachInfo self) -> uint32_t
[ "GetResumeCount", "(", "SBAttachInfo", "self", ")", "-", ">", "uint32_t" ]
def GetResumeCount(self): """GetResumeCount(SBAttachInfo self) -> uint32_t""" return _lldb.SBAttachInfo_GetResumeCount(self)
[ "def", "GetResumeCount", "(", "self", ")", ":", "return", "_lldb", ".", "SBAttachInfo_GetResumeCount", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L1102-L1104
TimoSaemann/caffe-segnet-cudnn5
abcf30dca449245e101bf4ced519f716177f0885
python/caffe/io.py
python
Transformer.set_transpose
(self, in_, order)
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. Parameters ---------- in_ : which input to assign this channel order order : the order to transpose the dimensions
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model.
[ "Set", "the", "input", "channel", "order", "for", "e", ".", "g", ".", "RGB", "to", "BGR", "conversion", "as", "needed", "for", "the", "reference", "ImageNet", "model", "." ]
def set_transpose(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. Parameters ---------- in_ : which input to assign this channel order order : the order to transpose the dimensions """ self.__check_input(in_) if len(order) != len(self.inputs[in_]) - 1: raise Exception('Transpose order needs to have the same number of ' 'dimensions as the input.') self.transpose[in_] = order
[ "def", "set_transpose", "(", "self", ",", "in_", ",", "order", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "if", "len", "(", "order", ")", "!=", "len", "(", "self", ".", "inputs", "[", "in_", "]", ")", "-", "1", ":", "raise", "Except...
https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/python/caffe/io.py#L187-L201
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/mavlink_px4.py
python
MAVLink.change_operator_control_encode
(self, target_system, control_request, version, passkey)
return msg
Request to control this MAV target_system : System the GCS requests control for (uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (uint8_t) version : 0: key as plaintext, 1-255: future, different hashing/encryption variants. The GCS should in general use the safest mode possible initially and then gradually move down the encryption level if it gets a NACK message indicating an encryption mismatch. (uint8_t) passkey : Password / Key, depending on version plaintext or encrypted. 25 or less characters, NULL terminated. The characters may involve A-Z, a-z, 0-9, and "!?,.-" (char)
Request to control this MAV
[ "Request", "to", "control", "this", "MAV" ]
def change_operator_control_encode(self, target_system, control_request, version, passkey): ''' Request to control this MAV target_system : System the GCS requests control for (uint8_t) control_request : 0: request control of this MAV, 1: Release control of this MAV (uint8_t) version : 0: key as plaintext, 1-255: future, different hashing/encryption variants. The GCS should in general use the safest mode possible initially and then gradually move down the encryption level if it gets a NACK message indicating an encryption mismatch. (uint8_t) passkey : Password / Key, depending on version plaintext or encrypted. 25 or less characters, NULL terminated. The characters may involve A-Z, a-z, 0-9, and "!?,.-" (char) ''' msg = MAVLink_change_operator_control_message(target_system, control_request, version, passkey) msg.pack(self) return msg
[ "def", "change_operator_control_encode", "(", "self", ",", "target_system", ",", "control_request", ",", "version", ",", "passkey", ")", ":", "msg", "=", "MAVLink_change_operator_control_message", "(", "target_system", ",", "control_request", ",", "version", ",", "pas...
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L2561-L2573
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/sping/PDF/pdfdoc.py
python
PDFDocument.setSubject
(self, subject)
embeds in PDF file
embeds in PDF file
[ "embeds", "in", "PDF", "file" ]
def setSubject(self, subject): "embeds in PDF file" self.info.subject = subject
[ "def", "setSubject", "(", "self", ",", "subject", ")", ":", "self", ".", "info", ".", "subject", "=", "subject" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/PDF/pdfdoc.py#L124-L126
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBTypeCategory.AddTypeSummary
(self, arg2, arg3)
return _lldb.SBTypeCategory_AddTypeSummary(self, arg2, arg3)
AddTypeSummary(SBTypeCategory self, SBTypeNameSpecifier arg2, SBTypeSummary arg3) -> bool
AddTypeSummary(SBTypeCategory self, SBTypeNameSpecifier arg2, SBTypeSummary arg3) -> bool
[ "AddTypeSummary", "(", "SBTypeCategory", "self", "SBTypeNameSpecifier", "arg2", "SBTypeSummary", "arg3", ")", "-", ">", "bool" ]
def AddTypeSummary(self, arg2, arg3): """AddTypeSummary(SBTypeCategory self, SBTypeNameSpecifier arg2, SBTypeSummary arg3) -> bool""" return _lldb.SBTypeCategory_AddTypeSummary(self, arg2, arg3)
[ "def", "AddTypeSummary", "(", "self", ",", "arg2", ",", "arg3", ")", ":", "return", "_lldb", ".", "SBTypeCategory_AddTypeSummary", "(", "self", ",", "arg2", ",", "arg3", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L13177-L13179
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/__init__.py
python
IndigoObject.findSGroups
(self, prop, val)
return self.dispatcher.IndigoObject( self.dispatcher, self.dispatcher._checkResult( Indigo._lib.indigoFindSGroups( self.id, prop.encode(ENCODE_ENCODING), val.encode(ENCODE_ENCODING), ) ), )
Molecule method finds SGroup by property and value Args: prop (str): property string val (str): value string Returns: IndigoObject: SGroup iterator
Molecule method finds SGroup by property and value
[ "Molecule", "method", "finds", "SGroup", "by", "property", "and", "value" ]
def findSGroups(self, prop, val): """Molecule method finds SGroup by property and value Args: prop (str): property string val (str): value string Returns: IndigoObject: SGroup iterator """ self.dispatcher._setSessionId() return self.dispatcher.IndigoObject( self.dispatcher, self.dispatcher._checkResult( Indigo._lib.indigoFindSGroups( self.id, prop.encode(ENCODE_ENCODING), val.encode(ENCODE_ENCODING), ) ), )
[ "def", "findSGroups", "(", "self", ",", "prop", ",", "val", ")", ":", "self", ".", "dispatcher", ".", "_setSessionId", "(", ")", "return", "self", ".", "dispatcher", ".", "IndigoObject", "(", "self", ".", "dispatcher", ",", "self", ".", "dispatcher", "."...
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L2085-L2105
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.GetCapture
(*args, **kwargs)
return _core_.Window_GetCapture(*args, **kwargs)
GetCapture() -> Window Returns the window which currently captures the mouse or None
GetCapture() -> Window
[ "GetCapture", "()", "-", ">", "Window" ]
def GetCapture(*args, **kwargs): """ GetCapture() -> Window Returns the window which currently captures the mouse or None """ return _core_.Window_GetCapture(*args, **kwargs)
[ "def", "GetCapture", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetCapture", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L10648-L10654